Need to know exactly when a user moves from one page to another in your Flutter app? Maybe you want to log which pages they visit, update some state, or show a special message.
Flutter provides a handy tool for this called RouteObserver
. It lets you listen to what's happening with the pages (routes) in your app's navigator.
Using RouteObserver
To use RouteObserver
, you need to create your own class that extends it. This new class will listen for navigation changes.
Create Your Observer Class
In this class, you can override methods like didPush
, didPop
, and didReplace
to react to different navigation actions.
class MyNavigatorObserver extends RouteObserver<PageRoute<dynamic>> {
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
// This runs when a new page is opened
print('Navigated to: ${route.settings.name}');
}
void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
// This runs when a page is replaced by another
print('Page replaced with: ${newRoute?.settings.name}');
}
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
// This runs when you go back from a page
print('Returned from: ${route.settings.name}');
}
}
Add the Observer to Your App
Next, you need to tell your MaterialApp
(or CupertinoApp
) to use your new observer. You do this by adding an instance of your observer to the navigatorObservers
list.
class MyApp extends StatelessWidget {
// Create an instance of your observer
final navObserver = MyNavigatorObserver();
Widget build(BuildContext context) {
return MaterialApp(
// Provide your observer to the app
navigatorObservers: [navObserver],
// ... other app setup ...
);
}
}
Now, whenever a page is pushed, popped, or replaced in your app's main navigator, the corresponding method in your MyNavigatorObserver
class will run. This lets you run specific code right when these navigation events happen.
Key Navigation Events
Here are the main events you can listen for:
didPush
Happens when you navigate to a new page (like using Navigator.push
).
didPop
Happens when you go back from a page (like using Navigator.pop
).
didReplace
Happens when one page is swapped for another without adding to the stack (like using Navigator.pushReplacement
).
Using RouteObserver
is a simple and powerful way to manage actions based on page changes in your Flutter applications.