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?
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.