Flutter GetX通过调用 Get.offNamed 方法来拦截页面的返回操作

10 min read

GetX 中,可以通过调用 Get.offNamed 方法来拦截页面的返回操作。该方法需要接收一个回调函数作为参数,当用户点击返回按钮时,回调函数会被调用。在回调函数中,可以通过调用 Navigator.of(context).pop 方法来进行页面返回操作。

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      home: Scaffold(
        body: Center(
          child: RaisedButton(
            child: Text('返回'),
            onPressed: () {
              Get.offNamed(() {
                return AlertDialog(
                  title: Text('确认退出'),
                  content: Text('是否确认退出应用'),
                  actions: <Widget>[
                    FlatButton(
                      child: Text('确认'),
                      onPressed: () {
                        Navigator.of(context).pop(true);
                      },
                    ),
                    FlatButton(
                      child: Text('取消'),
                      onPressed: () {
                        Navigator.of(context).pop(false);
                      },
                    ),
                  ],
                );
              });
            },
          ),
        ),
      ),
    );
  }
}