How to pop two screens without using named routing?
Asked Answered
H

5

34

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.

Houston answered 23/6, 2019 at 15:16 Comment(1)
Possible duplicate of Flutter Navigation pop to index 1Edytheee
I
79

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.

Immeasurable answered 23/6, 2019 at 16:3 Comment(0)
H
21

You can just pop it two times;

nav = Navigator.of(context);
nav.pop();
nav.pop();
Haemolysin answered 25/6, 2019 at 20:15 Comment(0)
S
13

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.

Sweat answered 7/6, 2021 at 17:13 Comment(0)
C
7

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);
Cortex answered 4/3, 2021 at 13:52 Comment(3)
Is this really different from the accepted answer from 2019?Twaddle
.pop()..pop()..pop() 3 times or count++ >=2 makes same effect. You can use 3 of those solutions depends on your requirement, it's up to you.Hypothermal
No its not lol.Commissure
B
-1

two lines.

Navigator.pop(context);
Navigator.of(context, rootNavigator: true).pop();
Bunny answered 19/6, 2023 at 0:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.