Navigator routes Clear the stack of flutter
DartFlutterDart Problem Overview
In my app i have three screens login , verifyotp , generatepass. I know how to move from one page to other page eg: Navigator.pushNamed(context, "/theNameOfThePage");
.
I have a flow in which i move from login->verifyotp->generatepass my question is now how can i move from generatepass to login page and clearing all the stack.
I am an android developer so in android we have intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
.
How can i achieve same result in flutter!
Dart Solutions
Solution 1 - Dart
Full clean of Navigator's history and navigate to new route:
void _logout() {
Navigator.pushNamedAndRemoveUntil(context, "/newRouteName", (r) => false);
}
Solution 2 - Dart
Use Navigator.popUntil
.
void _logout() {
Navigator.popUntil(context, ModalRoute.withName('/login'));
}
Solution 3 - Dart
To add to Paul Iluhin's answer above, if you want to pass arguments to the new page, just add the arguments after (r) => false
. Here is an example.
Navigator.pushNamedAndRemoveUntil(context, "/newRouteName", (r) => false, arguments: {
"arg_1": firstArgument,
"arg_2": secondArgument
});
Solution 4 - Dart
As others have already mentioned, Navigator.pushNamedAndRemoveUntil
is the way to go, but in case if anyone is wondering how to do that using the component type (instead of a string route path), this is how you do it.
> Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (_) > => LoginPage()), (route) => false);
I personally prefer using the type name because I change my route path multiple times during the initial development until I reach a stable route name pattern and when I do that, I don't want to do a mass search/replace.