If you have been using Flutter with BLoc maybe you had the necessity to navigate to a new page inside of your BLoC as we know we don't have a
BuildContext to use
Navigator.of() function to navigate. Let me show you how...
Note: I'm assuming here that you already know BLoC, if not just follow these link: https://felangel.github.io/bloc/
To navigate in reaction to a BLoC's state we sometimes do something like betwen our widgets:
It works but doesn't seems to be the right way because we need to check the state in the UI and wait until Flutter render the last frame to navigate. And then we think, but we can't navigate inside a BLoC because we don't have a BuildContext there!
Basically we use the navigatorState to navigate without a BuildContext, keep reading to see how it works.
- Create your
NavigatorBlocthat receive a global key with the navigator state in the constructor. This bloc should only recieve events to navigate between pages, see the example bellow:
- Create a global key to store with the navigator state and then pass it to your
MaterialApp. Also we should pass this property to NavigatorBloc.
And we're all set, for each navigation you just create a event to navigate for each specific page. Now we can navigate to a page from any BLoC.
BlocProvider.of<NavigatorBloc>(context).dispatch(NavigateToHomeEvent()); inside any widget to navigate to another page using the navigator BLoc. That way you will have a centralized navigation class.
Hope you enjoy the post, don't forget to leave an ❤️ and share the article.