Search code examples
flutternavigationflutter-go-router

How to fix GoRouter.of(context).pop() so it will navigate to the previous page?


I am using

GoRouter.of(context).pop(); to navigate from my Settings page to the previous screen and it works fine.

But if I use it on another screen to navigate back it sends me to the main screen.

This is how it looks like in both cases:

         onPressed: () {
        GoRouter.of(context).pop();
      }

Solution

  • Think navigation as a stack, if you are doing GoRouter.of(context).go('/route') you are clearing the stack with your new route. If you do GoRouter.of(context).push('/route') you are adding to the stack.

    So if when you use .go() and you do .pop() you will either run into error if you don't have a default route and no other navigations in the stack, or you will go to the next navigation in the stack. Ideally if you are wanting navigation up and down the stack stick to .push() and .pop() if you are doing a one time to a new screen, to .go().