Haroon khan
Haroon khan

Reputation: 1058

How to pop last three routes from the navigator stack in flutter

Scenario

I'm navigating user to loginScreen/signUpScreen from different screens (Say destinationScreen, attractionScreens, reviewScreen etc) in the app and after loggingIn successfully, I want to pop him back to same screen from where he was navigated to the loginScreen/signupScreen.

So, I want to pop all the screens involved in the signup/login process say 3 screens.

What I've already tried

I've already tried navigator.popUntil but it can work only if you want to pop back to a single screen every time like this:

Pushing route:

Navigator.push(
  context,
  MaterialPageRoute(
    settings: RouteSettings(name: '/loginRedirect'),
      builder: (context) => AttractionScreen(
            attractionData: att,
          )),
);

Popping route in signInScreen:

Navigator.popUntil(context, ModalRoute.withName('/loginRedirect'));

But this scenario only works when you have to route to a single specific screen but in my case, I've to route to different screens depending on from where the user was directed to login screen.

What I want to do now

Now I want to have an implementation where after successful login, I pop the top three screens from the navigator stack which I search a lot but couldn't find any solution for that. So, how can I pop the last routes from the navigator stack?

Upvotes: 1

Views: 5986

Answers (3)

Haroon khan
Haroon khan

Reputation: 1058

I just got a solution which I was not sure on before.

I just need to call three times:

Navigator.pop(context)

like this:

if (needBackRedirect) {
    Navigator.of(context)..pop()..pop()..pop();
}

Upvotes: 4

Kamlendra Pandey
Kamlendra Pandey

Reputation: 366

Simply define the routes in the main.dart(appRoutes) file, use navigator pushNamed method to navigate between screen & to pop till any number of screen just use popUnti for example

Navigator.of(context).popUntil((route) {
               return route.settings.name ==
                          'RouteName'; // Use defined route like Dashboard.routeName
     });

Upvotes: 3

Bhoomi Prajapati
Bhoomi Prajapati

Reputation: 146

If you want to pop until 3 screens from the navigation stack, take one variable and keep track of removed Routes. Then check if that count is reached to 3 then stop popping the routes.

  1. add this variable:
   List<Route> arrayRoutes = [];
  1. add this where you want to perform your pop logic :
    Navigator.popUntil(context, (Route<dynamic> route){
                          arrayRoutes.add(route);
                          if (arrayRoutes.length != 3) {
                            print('continue popping if length is not 3');
                            return true;
                          } else {
                            print('stop to pop when count is 3');
                            return false;
                          }
                        }); 

Upvotes: 3

Related Questions