Reputation: 574
In flutter, we have two ways of exiting a page while destroying the current page. The first one is pushReplacement-
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context){
return LocationScreen();
}));
The second one is pushAndRemoveUntil-
Navigator.pushAndRemoveUntil(
context, MaterialPageRoute(builder: (context) => LocationScreen()), (
route) => false);
}
These both appear to be exactly same. I searched through google, but couldn't find a satisfactory answer. Can someone explain me the difference between these two?
Upvotes: 12
Views: 10829
Reputation: 1
Navigator.pushReplacement: This replaces the current screen with a new one. The new screen comes in place of the existing screen, and the current screen is removed from the stack.
Navigator.pushAndRemoveUntil: This removes all the previous screens in the stack until a certain condition is met. For example, you can remove all the screens and navigate to the new screen, ensuring the previous context is completely removed.
For example, if you're on a login screen and navigate to the home screen using pushReplacement, the login screen will be replaced by the home screen. But if you use pushAndRemoveUntil, you can remove all previous screens and directly navigate to the home screen, like clearing the stack and starting fresh.
Upvotes: 0
Reputation: 5343
Imagine your current navigation stack being something like this:
/A
/B
/C
Now, you want to get to route /D
. After calling pushReplacement
, the navigation stack will look like this:
/A
/B
/D
That's it, there is nothing more you could do with this method. However, while using pushAndRemoveUntil
, you could also specify the route predicate that will tell you when you need to stop popping your stack before pushing your next route. For instance, your route predicate is route /A
, the result will look like this:
/A
/D
Notice, that routes /B
and /C
were removed from the stack.
To sum up: pushReplacement
only replaces the top route while the pushAndRemoveUntil
could replace multiple routes up until your defined predicate.
Upvotes: 21