Flutter Navigator Middleware Part 1 — RouteObserver

Payam Zahedi
Flutter Community
Published in
3 min readMay 25, 2020

Intro

Maybe you have heard about RouteObserver when you work with Navigator widget. This class is used when you want to observe over navigator changes(like Navigator Pop or Push). If you want to be aware of Navigator changes you should implement RouteAware as a mixin for your single widget(Screen). In this article, we will create a simple example to see how RouteObserver works. In part2, we will create NavigatorMiddleware with RouteObserver. NavigatorMiddleware class will help us be aware of all changes about Navigator, not only a single widget. Also, we can do many other things with this service class like creating Navigator Stack. You can use this link, for the complete source code of this part.

How RouteObserver works?

As I mentioned before:

RouteObserver class used when you want to observe over navigator changes.

But how to use it?

  1. Create your MaterialApp widget.
  2. Create an instance of RouteObserver and pass it to your MaterialApp widget.
  3. Use RouteAware mixin in your widget(Screen) and subscribe to RouteObserver.

Let’s dive into it. Imagine this is your main.dart file:

In MeterialApp widget we have navigatorObservers property. We should first create NavigatorObservers and pass it to MaterialApp.

note: I will create NavigatorObservers instance in global scope.

So our code will be changed to something like this:

We create a RouteObserver instance and pass it to MaterialApp. Now it’s time to register HomePage with RouteAware mixin.

In Line 6, we use with keyword to use RouteAware class as a mixin in our widget. This Class helps us define some callbacks(did* method in code) and we can use these callbacks when we subscribe to RouteObserver. With this approach we can be aware of navigation in our widget.

Note: remember to subscribe to routeObserver in didChangeDependencies method. check the documentation for more info

Conclusion

So in this part, we learned about what RouteObserver is, and how we can use it. We create an instance of RouteObserver and use it in Material App. After that we subscribe to RouteObserver with RouteAware class. Now we can be aware of App Navigation with overriding of some did* methods in our widget.

Remember that our HomePage widget is only aware of navigator changes near itself. But what if we want to be aware of navigator changes in the whole app? There are two ways that we can solve this problem:

  1. Register all widgets(pages) to RouteObserver.
  2. Create a navigation middleware service class.

In the next part, I will inform you how to creating NavigationMiddleware. This approach can be very useful when you want to be aware of every navigator change in your app.

https://www.twitter.com/FlutterComm

--

--

Payam Zahedi
Flutter Community

I’m a Software Engineer, Flutter Developer, Speaker & Open Source Lover. find me in PayamZahedi.com