How to navigate flutter pages without context

There are certain situations in flutter development when we need to navigate to another page from outside the state widget.In such cases the (BuildContext)context is not available to the programmer and this can make it difficult for the programmer to navigate to the inteded page.For example, a Firebase Cloud Messaging push message causes the app to be redirected to a specified page, in such case the message is handled outside the State widget.

final FirebaseMessaging firebaseMessaging = FirebaseMessaging();
void handlePush()
{
 firebaseMessaging.configure(onMessage: <Navigate to desired screen>......)
}
class PushRecieve extends StatefulWidget{........
......}

In normal cases we would have used a simple navigator widget to navigate.

Navigator.of(context).push(MaterialPageRoute(builder: (context)=>MessageRecieved()));

Here, we need an alternative and the solution is simple.Instead of using a “Navigator” which relies on context we can use a global key of type NavigatorState.Something like this.

final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();

Remember to define this variable globally to use it properly.Further we need to pass this key to the MaterialApp which is usually present at the root of the widget tree.

new MaterialApp(
      title: 'Push Message Reciever',
      routes: predefinedRoutes,
      navigatorKey: navigatorKey,
    );

Now we can simply use this GlobalKey to navigate anywhere without any context.We can do so by accessing the currrentState of the key and after that the code is pretty similar to what we normally use .

navigatorKey.currentState.push(MaterialPageRoute(builder: (context)=>MessageRecieved()));

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.