Navigator.pop() not popping latest route off

2019-08-22 23:34发布

问题:

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