Navigator.popUntil flutter show black screen

Viewed 5117

I have two different flows in my project.

  1. Main Page -> PageA -> Page B -> Page C -> Page A

From Page C to Page A, I use this code , which works fine.

   Navigator.popUntil(context, ModalRoute.withName(AssetMenu.ROUTE));
  1. When receive push notification, user tap on the push notification, I want it straight away navigate like this

Main Page -> Page B -> Page C -> then back to Page A when button in Page C is clicked.

But when button in Page C is clicked, it shows black screen.

How should I handle this?

4 Answers

In your second use case Page A is missing. When you invoke Navigator.popUntil() the navigator goes up the stack of routes and pops them until it find the specified one. If the specified route is not on the stack, it will remove routes until the stack is empty. That is why you get the black screen.

If you want to turn Main Page -> Page B -> Page C into Main Page -> Page A you have to invoke Navigator.pushAndRemoveUntil() where the new route is Page A and the predicate matches the Main Page. Alternatively use Navigator.pushNamedAndRemoveUntil().

Maybe you can try this

Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => AssetMenu(),), (route) => route.isFirst);

I suggest using name routes, it's more easy even if you're app gets bigger with more pages. I prefer to let widgets outside main.dart and inside dart just use logic and routes, and after Create those 3 pages that you need A,B,C and set in you're main dart code that you're first page(home page) has to be page A.

Go on you're pages and just under Statefull{ or Stateless { type the route name:

static const routeName = '/pageA';
static const routeName = '/pageB';
static const routeName = '/pageC';

Define in your main.dart the routes:

home: WidgetFromPageA(),
      routes: {
        WidgetFromPageB.routeName: (ctx) => WidgetFromPageB(),
        WidgetFromPageC.routeName: (ctx) => WidgetFromPageC(),
        },

From any page you can call this action:

Navigator.of(context).pushNamed(WidgetFromPageA.routeName);
Navigator.of(context).pushNamed(WidgetFromPageB.routeName);
Navigator.of(context).pushNamed(WidgetFromPageC.routeName);

In this way you can go to page B and on the new page in the app bar you got the return button. For example, when you are in the second page, use the pushReplacement() method and open the third page, when you hit the back button you will go to the first page and skip the second page.

To make it more clear you can navigate to the forth page like this:

[ 1 --push()--> 2 --pushReplacement()--> 3 --pushReplacement()--> 4] and when you hit the back button you will get to the first page.

Do this if you want to go to the main page when you are not using named Routes

Navigator.of(context).popUntil((route) {
   if (route.settings.name != "/") return false;
   return true;
});
Related