首页 > 解决方案 > 如果用户注销并重新登录,WillPopScope 将不起作用

问题描述

我现在已经编写了一个完整的应用程序,并将 WillPopScope 添加到每个页面,以防止任何屏幕上的任何用户能够使用返回按钮。

当用户按下后退按钮时,它会显示一个弹出对话框,询问用户是否希望关闭应用程序。

我尚未启动该应用程序,但使用我的移动设备测试该应用程序。当我第一次加载应用程序时,WillPopScope 可以在每个页面上运行。我可以在任何页面之间导航,并且在任何时候如果我按下后退按钮,对话框就会出现......这就是我想要的。

如果我退出应用程序,然后重新登录,WillPopScope 无法工作,并且如果我按下后退按钮,无论我在应用程序中的哪个位置或导航多少页,我总是返回登录屏幕通过。

为什么这在我注销并重新登录之前可以正常工作 - 然后当我重新登录时,为什么当我按下后退按钮时它总是让我回到登录屏幕,而不是我刚刚来自的页面?

每一页的代码是:

@override
  Widget build(BuildContext context) {
    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 and close the app?'),
              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;
    }

然后我将脚手架包裹在 WillPopScope 周围:

return WillPopScope(
      child: Scaffold(
        resizeToAvoidBottomPadding: false,
        backgroundColor: Colors.white,
        ....

然后在关闭前调用 _onWillPop:

onWillPop: _onWillPop,
    );
  }

正如我所说,我知道代码可以工作,因为它可以完成我需要它做的所有事情,直到我注销并重新登录。

请帮忙!:)


更新:

如果其他人有类似的问题 - 根据 Devayan 的有用答案,我将导航从登录页面更新到主页,方法是:

Future navigateToSubPageMain(context) async {
    Navigator.push(
        context, MaterialPageRoute(builder: (context) => Home()));
  }

到.....

Future navigateToSubPageMain(context) async {
    Navigator.pushReplacement(
        context, MaterialPageRoute(builder: (context) => Home()));
  }

这现在有效!

标签: flutterdartnavigation

解决方案


Navigator.pop(context)从最直接的导航器堆栈中弹出路线。

因为,我没有看到你的完整代码,我猜当你注销时,所有其他路由都replaced使用登录页面路由。现在,登录后只有一个页面可以返回,那就是登录页面。

如果你pushReplacementNamed在导航器上做了,恐怕你将无法回到旧路线。

如果您想避免登录后返回登录页面,则必须pushReplacementNamed从登录页面进行,这样就没有从主页“返回”的路线。

这是有关 Navigator 如何处理路由堆栈的官方文档。 https://api.flutter.dev/flutter/widgets/Navigator-class.html


推荐阅读