Navigator.pop() not popping latest route off

青春壹個敷衍的年華 提交于 2019-12-13 04:13:27

问题


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.

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);
  }

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...


回答1:


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

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.

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();


来源:https://stackoverflow.com/questions/49438917/navigator-pop-not-popping-latest-route-off

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!