'Flutter get current route name, of Navigator, from GlobalKey

In my Flutter application I need to know the current path to avoid pushing the same path twice.

I found that I can use the following code:

    ModalRoute.of(context).settings.name

It works, but only for the main Navigator.

Since I have a second Navigator in my app that I target with a GlobalKey, how can I access its current path?

I tried like this:

ModalRoute.of(HomePage.navigatorKey.currentContext).settings.name

But it returns the main route.



Solution 1:[1]

Don't know if you still need it but here is my solution to problem.

String route = "";
HomePage.navigatorKey.currentContext!.popUntil((currentRoute) {
  route = currentRoute.settings.name;
  // Return true so popUntil() pops nothing.
  return true;
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DharmanBot