Be aware of your routes with RouteAware — Flutter!

There can be cases when you wish to perform certain actions on the change navigation history. This is where RouteAware comes to the rescue!

Abhishek Doshi
3 min readSep 10, 2021

Let’s say we have 2 pages, Page1 and Page2 in our app. So whenever Page2 pops, we want to print something on Page1. In normal flow, there’s no method from Widget Lifecycle that is called when the next screen is poped! (Feel free to check out Widget Lifecycle in Flutter to know more)!

RouteAware class provides the following methods which we can extend:

  • didPop()
    When we pop the current screen, didPop method is called.
  • didPopNext()
    If you have extended Page1 with RouteAware, and if Page2 is popped so that Page1 is visible now, didPopNext is called. In other words, this method is called when the top screen is popped off and the current screen is visible.
  • didPush()
    This is called when the current screen or route has been pushed into the navigation stack!
  • didPushNext()
    When we push Page2 from Page1, didPushNext is called. In other words, this method is called when a new screen/route is pushed from the current screen and the current screen is no longer visible.

Let’s now see an example!

Step 1: Create a variable of RouteObserver in main.dart

final RouteObserver<ModalRoute> routeObserver = RouteObserver<ModalRoute>();

Step 2: Inside your, MaterialApp you need to set navigatorObservers and pass our variable into it! Here’s how your main.dart will look like:

Step 3: The next step will be to extend RouteAware so that you can override the different methods! Also, inside initState of Page1, subscribe to the route.

@override
void initState() {
WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
routeObserver.subscribe(this, ModalRoute.of(context)!);
});
super.initState();
}

Step 4: Override the methods. This is how your page1.dart looks like:

Here, we are just overriding all the methods available and navigating to our next page onClick of our Floating Action Button.

Step 5: The same thing can be done for page2.dart!

Let’s see it practically!

When we followed the above steps, here’s the output in the console:

Explanation: When Page1 is loaded, didPush of Page1 is called. When we clicked on the floating action button, first didPushNext of Page1 got called and then our Page2 got rendered and didPush of Page2 got called. When we clicked on back from Page2, the Page1’s didPopNext got called and then Page2 got poped and didPop of Page2 got called. And then the steps were again repeated. You can get the entire project on my GitHub!

Hope you enjoyed this article!

If you loved it, you can Buy Me A Coffee!

Don’t forget to connect with me!

Don’t stop, until you are breathing!💙
- Abhishek Doshi

--

--

Abhishek Doshi

Google Developer Expert — Dart, Flutter & Firebase 💙💛