Flutter 中的设备返回按钮控制

问题描述

我正在开发一个带有客户列表和“添加”浮动按钮的 Flutter 应用程序。当我点击添加按钮时,我将它带到一个新屏幕以添加新客户。在此屏幕中,当按下设备返回按钮时,它应该返回到列表屏幕。但是,它会返回到仪表板。(应用流程:仪表板屏幕(客户)-> 客户列表屏幕-> 添加客户屏幕。 我已经尝试过 Willscope 方法

我的添加客户屏幕:

Widget build(BuildContext context) {

Future<bool> _onBackpressed() async {
  return (await showDialog(
    context: context,builder: (context) => new AlertDialog(
      title: new Text('Are you sure?'),content: new Text('Do you want to exit Add Customer'),actions: <Widget>[
        new FlatButton(
          onpressed: () => Navigator.of(context).pop(false),child: new Text('No'),),new FlatButton(
          onpressed: () => Navigator.of(context).pop(true),child: new Text('Yes'),],)) ?? false;
}

return new
 WillPopScope(
    onWillPop: _onBackpressed,child : new Scaffold(
  appBar: new AppBar(
    title: new Text(widget.title),backgroundColor: theme_color,body: new SafeArea(
      top: false,bottom: false,child: new Form(
          key: _formKey,autovalidate: true,child: new ListView(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),children: <Widget>[
              SizedBox(
                height: 20,//Form Elements


              new Container(
                  height: 70,padding: const EdgeInsets.only(
                      left: 10.0,right: 10.0,top: 20.0),child: new RaisedButton(
                    color: theme_color,child: const Text(
                      'Save',style: TextStyle(color: Colors.white),onpressed: () {
                    //Send Data to Database
                      }
                    },)),//Save button
            ],))),));
}

解决方法

使用 this ,而不是返回任何东西。

  Future<void> _onBackPressed() async {
      return (await showDialog(
        context: context,builder: (context) => new AlertDialog(
          title: new Text('Are you sure?'),content: new Text('Do you want to exit Add Customer'),actions: <Widget>[
            new FlatButton(
              onPressed: () => Navigator.of(context).pop(false),child: new Text('No'),),new FlatButton(
              onPressed: () => Navigator.of(context).pop(true),child: new Text('Yes'),],));
    }