捕获导航栏返回事件

默认情况下,用户在按导航栏的返回键时,会返回到上一个路由页面,但我们希望在此拦截用户事件,弹出一个对话框询问用户是否退出,若用户点击确定的话,则退出当前会话。

我们使用WillPopScope这个Widget来完成这个设定。

///构建WillPopScope
 WillPopScope buildBody(BuildContext context, Scaffold scaffold){
   return WillPopScope(
     onWillPop: () => _showMessage(context, "信息", "退出登录?"),
     child: scaffold,
   );
 }

 将所有的Scaffold外层都套上这样一个WillPopScope之后,就可以进行全局捕获了。

WillPopScope buildWillPopScope(BuildContext context) {
    return BackExit().buildBody(context, buildScaffold(context));
}

 可以将各自页面的主体Scaffold写在单独的buildScaffold中,而在重载的build函数中调用这个buildWillPopScope进行主体包裹。

现在我们已经捕获到了用户返回的事件,接下来只需要弹出一个消息框,让用户确认是否退出即可:

///登出确认
  Future<void> _showMessage(
      BuildContext context, String title, String message) {
    return showDialog(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text(title),
            content: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  Text(message),
                ],
              ),
            ),
            actions: <Widget>[
              FlatButton(
                child: Text('确定'),
                onPressed: () {
                  AccountUtil.logOff(context);
                },
              )
            ],
          );
        });
  }

 这样实现之后的效果图:

 

posted @ 2020-10-15 15:57  猎喵Rachel  阅读(219)  评论(0)    收藏  举报