How to pop two screens without using named routing?

Viewed 20293

For example, my current routing is like this:

Login -> Screen1 -> Screen2 -> Screen3 -> Screen4

I'd like to go back to Screen2 from Screen4. I can't use named routing, because I have to pass a parameter to Screen2. Push Screen2 in Screen4 is not a good solution.

4 Answers

Use popUntil method of Navigator class.

e.g.

int count = 0;
Navigator.of(context).popUntil((_) => count++ >= 2);

However, I would recommend defining names for your routes and using popUntil as it is designed as per docs.

You can just pop it two times;

nav = Navigator.of(context);
nav.pop();
nav.pop();

The class from which the transition will be made as StatefulWidget. To press action add the pushNamed navigator with then, which will trigger after returning to this screen. Pass setState to update the widget:

onTap: () {
  Navigator.pushNamed(
    context,
    RouteNames.viewExercises,
  ).then((value) {
    setState(() {});
  });
},

Screen from which to return to be used:

Navigator.of(context)
  ..pop()
  ..pop()
  ..pop();

where ..pop() is used as many times as needed to back.

if you would like to pop until three times, You can use the code in below.

int count = 3;
Navigator.of(context).popUntil((_) => count-- <= 0);
Related