How to get current route path in Flutter?

In Flutter, getting the current route path is an essential task when building applications that require navigating through different screens. The ModalRoute class provides a way to access various settings related to the current route, including its name.

Using ModalRoute to get the current route name

You can use the following method to retrieve the current route path:

String? currentPath = ModalRoute.of(context).settings.name;

This will give you the exact name of the current route, which can be used for various purposes such as navigation and state management.

Handling Navigator.popUntil

If you’re using Navigator.popUntil, there’s an important note to keep in mind. The other answer by Rémi Rousselet provides valuable insight into handling this scenario:

This is because Navigator.popUntil can modify the current route path, and you need to take this into account when getting the current route name.

Using navigator key with popUntil method

If you’re using a navigator key, you might want to get the current route by utilizing the popUntil method. Here’s how you can do it:

String? currentPath;
navigatorKey.currentState?.popUntil((route) {
  currentPath = route.settings.name;
  return true;
});

This approach allows you to get the current route name by iterating through the routes using the popUntil method. The resulting path will be stored in the currentPath variable.

Conclusion

In conclusion, getting the current route path in Flutter can be achieved through various methods depending on your specific use case. By utilizing the ModalRoute class and handling scenarios involving Navigator.popUntil, you’ll be able to retrieve the exact name of the current route.

References:

Rémi Rousselet’s answer on Stack Overflow