Sub topic 9
Observing navigation with NavigatorObserver
This chapter assumes you know Dart async and await, basic Flutter widgets, BuildContext, and how to run a Flutter app. You will learn how to watch route changes without putting logging or analytics code inside every button callback.
What a NavigatorObserver does
A Navigator manages a stack of routes. A route is an object that represents a screen or page. When a route is pushed, it becomes the top route. When it is popped, the previous route becomes visible.
A NavigatorObserver receives callbacks when this stack changes. It can record screen views, measure navigation events, or help diagnose unexpected transitions. It observes navigation but does not initiate or cancel it.
The most common callbacks are:
| Callback | When it runs |
|---|---|
| `didPush` | A route is added to the stack |
| `didPop` | The top route is removed |
| `didReplace` | One route replaces another |
| `didRemove` | A route is removed without becoming the current route |
Add an observer
The following complete app logs route changes. Named routes provide useful names through RouteSettings.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class LoggingObserver extends NavigatorObserver {
void _log(String event, Route<dynamic>? route) {
final name = route?.settings.name ?? '<unnamed>';
debugPrint('$event: $name');
}
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPush(route, previousRoute);
_log('push', route);
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didPop(route, previousRoute);
_log('pop', route);
}
@override
void didReplace({
Route<dynamic>? newRoute,
Route<dynamic>? oldRoute,
}) {
super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
_log('replace', newRoute);
}
@override
void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
super.didRemove(route, previousRoute);
_log('remove', route);
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
static final observer = LoggingObserver();
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorObservers: [observer],
initialRoute: '/',
routes: {
'/': (_) => const HomeScreen(),
'/details': (_) => const DetailsScreen(),
},
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: () => Navigator.pushNamed(context, '/details'),
child: const Text('Open details'),
),
),
);
}
}
class DetailsScreen extends StatelessWidget {
const DetailsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Details')),
body: Center(
child: ElevatedButton(
onPressed: () => Navigator.pop(context),
child: const Text('Go back'),
),
),
);
}
}When the app opens, the observer usually logs a push for /. Tapping Open details logs a push for /details. Pressing the system back button or Go back logs a pop.
RouteObserver and RouteAware
RouteObserver<T> is a specialized observer for widgets that need to know when they become visible or hidden. A widget can implement RouteAware and respond to events such as didPushNext, which runs when another route appears above it.
Use NavigatorObserver for app-wide events. Use RouteObserver when a particular screen must refresh after the user returns to it.
Common errors
- Expecting an observer to stop navigation: Observers report changes after navigation decisions. Use
PopScopeor application state for back-navigation rules. - Reading a missing route name: Routes created with
MaterialPageRoutemay have a null name. Check for null or provideRouteSettings. - Observing only the root navigator: A nested navigator has its own stack. Attach an observer to each navigator whose events matter.
- Sending sensitive data to logs: Log route names and safe identifiers, not tokens, passwords, or private user data.
Exercise
Which callback should record that a screen was removed from the top of the navigation stack?
Show answer
didPop. It receives the removed route and the route that becomes current.