Flutter 使用 WillPopScope 组件来拦截页面的返回操作

6 min read

WillPopScope 组件是 Flutter 中的一个用于处理页面返回操作的组件。

当用户点击页面的返回按钮时,WillPopScope 组件会拦截返回操作,并调用 onWillPop 回调函数来处理返回事件。onWillPop 回调函数需要返回一个 Future 对象,用于指示是否允许返回操作。如果返回 true,则允许返回;如果返回 false,则禁止返回。

例如,下面的代码使用 WillPopScope 组件来拦截页面的返回操作,并在用户确认后才允许返回:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        bool canPop = await showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: Text('确认退出'),
              content: Text('是否确认退出应用'),
              actions: <Widget>[
                FlatButton(
                  child: Text('确认'),
                  onPressed: () {
                    Navigator.of(context).pop(true);
                  },
                ),
                FlatButton(