Flutter: How to avoid pushing the same route on existing route
This works for me:
Route route = ModalRoute.of(context);
final routeName = route?.settings?.name;
if (routeName != null && routeName != nav) {
Navigator.of(context).pushNamed(nav);
print(route.settings.name);
}
NavigatorState doesn't expose an API for getting the path of the current route, and Route doesn't expose an API for determining a route's path either. Routes can be (and often are) anonymous. You can find out if a given Route is on the top of the navigator stack right now using the isCurrent method, but this isn't very convenient for your use case.
https://stackoverflow.com/a/46498543/2554745
This is the closest solution I could think of:
Navigator.of(context).pushNamedAndRemoveUntil(
"newRouteName",
(route) => route.isCurrent && route.settings.name == "newRouteName"
? false
: true);
It will pop the current route if name of the route is "newRouteName" and then push new one, else will not pop anything.
Edit: Latest flutter provides ModalRoute.of(context).settings.name
to get the name of current route.