BuildContext plays an important role while developing Mobile Application using Flutter. It is used to provided reference to the location of widget inside widget tree and also being use as reference to alter UI and display many components on the screen. Among these and all other, one important part of the application where it plays a key role is to Navigate to & between screens. As being an important aspect of application, there are some places where an absence of BuildContext becomes a blocker for a developer to display, update some UI changes or move to specific screens. To tackle one of the situations of all other, is to move to specific screen without using BuildContext is explained and developed further in this article.  

First of all, let’s put some lights on NavigatorState class which provides state of Navigator widget which is used to navigate to different screens using different methods. By creating a GlobalKey of this NavigatorState class we can get the current state of Navigator and use one of the different methods to move to specific screen based on our requirements. Three things we needed to do here so we can achieve our desired tarted,  

  • Key should be accessible in our application from a generalized place. 
  • Our application should be assigned this Key under Material App widget. 
  • Build Navigation methods to move to between routes. 

For first point, a singleton class will be a best solution to manage GlobalKey and accessing same instance of class throughout the application so we can easily call different methods. So, let’s include a class in new file, name it as AppNavigator as below. 

Janki Thaker

Source link