In this post we will learn a technique on how to perform navigation in when there is no context available.
As we learned in the previous post on Navigation and Routing, in Flutter we can perform navigation with the help of Navigator class. We looked at some of the basic methods for Navigation which looked like this:
Navigator.push( context, MaterialPageRoute(builder: (context) => MyRoute()), );
Although we can use the Navigator class in the above manner, you might come across a scenario where the above method will not work.
What if you do not have access to the context object? What if you have not yet wrapped your widget inside the MaterialApp? So how do you use the Navigator without the context?
In such scenario, we can not directly call the Navigator.push method.
To resolve this, you can make use of the GlobalKey class.
First, create a global key that will hold your app’s navigator state:
final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();
Next, set the value of this navigatorKey where you initialize the MaterialApp or CupertinoApp.
... child: CupertinoApp( navigatorKey: navigatorKey, ...
Finally, wherever you need in your app, you use this key to perform navigation.