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

How to handle Android device BACK button press in Flutter?

如何在 Android 的 Flutter 中处理设备后退按钮的 onPressed()?我知道我必须为 iOS 手动放置一个后退按钮,但 Android 设备具有内置的后退按钮,用户可以按下它。如何处理?

您可以使用 WillPopScope 来实现。

首先将 Scaffold 包裹在 WillPopScope 内。我在第一页显示一个对话框,要求确认退出应用程序。您可以根据自己的需要进行修改。

示例:

@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;
  }
}

在上面的示例中,我在用户点击 BACK 按钮和 AppBar 中的后退按钮时调用此 _onWillPop() 函数。

您可以使用此 WillPopScope 来实现按下 BACK 按钮并执行您想要的操作。