Navigation When There Is No Context

In this post we will learn a technique on how to perform navigation in when there is no context available.

Introduction

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:

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.

Solution

To resolve this, you can make use of the GlobalKey class.

First, create a global key that will hold your app’s navigator state:

Next, set the value of this navigatorKey where you initialize the MaterialApp or CupertinoApp.

Finally, wherever you need in your app, you use this key to perform navigation.

About the author