Navigator.pop()未弹出最新路线 [英] Navigator.pop() not popping latest route off

查看:285
本文介绍了Navigator.pop()未弹出最新路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个流程,如果用户未登录,则应用程序会将登录页面推送到堆栈中。他们完成登录后,将弹出登录页面并返回首页。

I'm trying to build a flow where, if user is not logged in, the application pushes the login page onto the stack. Once they finish logging in, it pops the login page off and returns to the homepage.

虽然推送有效,但弹出段却没有-我可以弹出返回要推送的值,但无法获得/ login路由。我错过了什么吗?

While the push works, the pop segment doesn't - I can get the pop to return values to push, but I cannot get the /login route off. Am I missing something?

home_page.dart

class _HomePageState extends State<HomePage> with UserAccount {
  @override
  void initState() {
    super.initState();

    if (!isLoggedIn) {
      print("not logged in, going to login page");
      SchedulerBinding.instance.addPostFrameCallback((_) async{
        var _val = await Navigator.of(context).pushNamed("/login");
        print("I SHOULD HAVE POPPED");
        print(_val);
        Navigator.of(context).pop();
      });
    }
  }

login_page.dart

class _LoginPageState extends State<LoginPage> with UserAccount {
  void _googleLogin() async {
    await googleClient.doGooglesignIn();
    Navigator.of(context).pop(true);
  }

结果是:

1.登录屏幕被按下

2.我可以登录

3.在完成登录

4.后,print( I SHOULD HAVE POPPED)运行。 (_val)返回true

5.弹出窗口似乎不起作用...

The behavior that results is:
1. Login screen is pushed
2. I can log in
3. print("I SHOULD HAVE POPPED") runs after I complete logging in
4. print(_val) returns true
5. the pop does not seem to work...

推荐答案

是因为 pushNamed 隐藏当前视图以显示新视图。

That is because pushNamed hide the current view to show the new one.

这意味着您的旧视图不再位于小部件树上。因此,您以前用于 Navigator.of(context)的上下文不再存在。

Which means your old view is not on the widget tree anymore. And therefore, the context you used to do Navigator.of(context) doesn't exist anymore.

什么您可以做的是将 Navigator.of(context)的结果存储在本地变量中。并重用它来调用 pushNamed pop

What you could do instead is to store the result of Navigator.of(context) in a local variable. And reuse it to call both pushNamed and pop.

final navigator = Navigator.of(context);
await navigator.pushNamed('/login');
navigator.pop();

这篇关于Navigator.pop()未弹出最新路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆