How to pop context with FLUTTER go_router?
Asked Answered
P

2

10

How do I go back to the previous screen with flutter's go_router? How to pop context?

Currently I am simply adding a new screen to the stack whether I want to go back or go forward.

 onTap: (() => context.go("/secondPage"))

I have used context.pop() but it throws error saying -

_AssertionError ('package:go_router/src/matching.dart': Failed assertion: line 102 pos 9: '_matches.isNotEmpty': You have popped the last page off of the stack, there are no pages left to show)

Pantechnicon answered 23/11, 2022 at 6:16 Comment(0)
S
23

You can use context.pop() if your page is rendered via go_router. But if you are using showModalBottomSheet or Dialog class then you should continue to use Navigator.pop(context)

Sundries answered 23/11, 2022 at 6:28 Comment(1)
Okay, that worked. I had to use context.push("/secondPage") to be able to use context.pop(). Thank youPantechnicon
H
15

You pop it using context.pop().

But in order that something will pop out, it should be in the router's stack.

So, the actual question is how to put the route in the router stack. Go_router has two methods go and push both will take you to the next screen specified by the parameter.

But, push will always add (push) a new route to the stack, while go will add a new route only if it is specified as a subroute to the previous screen. Otherwise, it will replace the previous route with a new one.

So, using the given example:

either use push

 onTap: (() => context.push("/secondPage"));

or specify secondPage as a subroute to firstPage and then use go

GoRoute(
    path: "/firstPage",
    builder: (context, state) => const FirstPage(),
    routes: [
      GoRoute(
        path: "secondPage",
        builder: (context, state) => const SecondPage(),
      ),

    ],
  ),

...

   onTap: (() => context.go("/secondPage"));

Here is the article where I learned all the above

Heft answered 13/4, 2023 at 18:16 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.