Reputation: 1058
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
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
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
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.
List<Route> arrayRoutes = [];
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