Contextless Navigation in Flutter

Navigation in Flutter is just straightforward. All you need to do is wrap a widget inside Route and push it to the Navigator.
Navigation can be done in two ways. First, passing the Navigator with a Route object and the other, using a route generator function. Both of the above require the Context to work.

What’s the issue with requiring the Context for navigation?
Sometimes, in our app, we may face some situations where we may need to navigate but the context won’t be available. Take this for an example, you may want to create a global dialog interface and would like to show it from anywhere in the app. Of course, you will have the context available if you are showing the dialog from a Widget. In this case, you have complete control but let’s assume that your app is heavily dependent on API calls and you need to show a No Internet Connection dialog whenever the API call fails and you detect no active internet connection. For achieving this, the easiest way to detect no internet connection would be to check the status code from your interceptors. But the interceptors are not bound to any widget and the context won’t be available. This can be a perfect situation to use Contextless Navigation in your app.
Another case would be to log out the user when their refresh token expires. When the access token expires and your server returns you a 401 status code, you would try to refresh the access token using the provided refresh token. But what if the refresh token expires, you will not have any way to fetch a fresh access token. In this case, you need to make the user log in again. This again would be handled by an interceptor and you will have the context available.
Contextless Navigation to the rescue
Setting up contextless navigation using the route generator
Define your paths in a separate constant file
Create your routes generator
Setup your navigation service
Using navigation service
Use GetIt to create a singleton class for navigation service
And here’s how you can call it
Easy! Now you can call navigation service from anywhere in the app. No need to worry about the context!