If you use Getx, it’s easy to find current route or path in Flutter. Flutter Getx provides one of the best solution for finding your current route in Flutter app.
First make sure you installed Getx package and you are wrapping your MaterialApp() using GetMaterialApp().
I use the below syntax to do it
Get.currentRoute.contains(AppRoutes.Message)
Here I am if the current route matches AppRoutes.Message route. It could be a string of route name.
If you don’t use Getx, you may do the original way. But it’s a hack. Look at the below code
final newRouteName = "/NewRoute";
bool isNewRouteSameAsCurrent = false;
Navigator.popUntil(context, (route) {
if (route.settings.name == newRouteName) {
isNewRouteSameAsCurrent = true;
}
return true;
});
if (!isNewRouteSameAsCurrent) {
Navigator.pushNamed(context, newRouteName);
}
Here we are using Navigator.popUntil() which takes a callback function. Inside the function you do conditional check.
So far Getx provide the best solution to get the current route at any situation among the solutions out there. They are also error prone and as well a lot of bipolerate code is involved..