代码之家  ›  专栏  ›  技术社区  ›  Mohsen Emami

如何处理Android设备的后退按钮在Flutter中按下

  •  -1
  • Mohsen Emami  · 技术社区  · 6 年前

    如何处理设备后退按钮 onPressed() 安卓的颤振?我知道我必须手动为iOS设置一个后退按钮,但是Android设备有内置的后退按钮,用户可以按下它。怎么处理?

    1 回复  |  直到 6 年前
        1
  •  4
  •   Amit Jangid    6 年前

    你可以用 WillPopScope 为了达到这个目的。

    先把你的 Scaffold 里面 意志力显微镜 . 我在第一页上显示一个对话框,要求退出应用程序的确认。你可以根据需要修改这个。

    例子:

    @override
      Widget build(BuildContext context) {
        return new WillPopScope(
          child: Scaffold(
              backgroundColor: Color.fromRGBO(255, 255, 255, 20.0),
              resizeToAvoidBottomPadding: true,
              appBar: AppBar(
                  elevation: 4.0,
                  title:
                      Text('Dashbaord', style: Theme.of(context).textTheme.title),
                  leading: new IconButton(
                    icon: new Icon(Icons.arrow_back, color: Colors.white),
                    onPressed: () => _onWillPop(),
                  )),
              body: new Container(), // your body content
          onWillPop: _onWillPop,
        );
      }
    
     // this is the future function called to show dialog for confirm exit.
     Future<bool> _onWillPop() {
        return showDialog(
              context: context,
              builder: (context) => new AlertDialog(
                    title: new Text('Confirm Exit?',
                        style: new TextStyle(color: Colors.black, fontSize: 20.0)),
                    content: new Text(
                        'Are you sure you want to exit the app? Tap \'Yes\' to exit \'No\' to cancel.'),
                    actions: <Widget>[
                      new FlatButton(
                        onPressed: () {
                          // this line exits the app.
                          SystemChannels.platform
                                .invokeMethod('SystemNavigator.pop');
                        },
                        child:
                            new Text('Yes', style: new TextStyle(fontSize: 18.0)),
                      ),
                      new FlatButton(
                        onPressed: () => Navigator.pop(context), // this line dismisses the dialog
                        child: new Text('No', style: new TextStyle(fontSize: 18.0)),
                      )
                    ],
                  ),
            ) ??
            false;
      }
    }
    

    在上面的例子中,我称之为 _onWillPop() 当用户点击 BACK 按钮和后退按钮 AppBar

    你可以用这个 意志力显微镜 实现 按钮按下并执行您想要的操作。