Sub topic 9
Observing navigation with NavigatorObserver
This chapter assumes you can push and pop routes with Navigator, give routes names through RouteSettings, and write a StatefulWidget with didChangeDependencies and dispose. For the go_router section, you should also know what a GoRouter configuration looks like.
A NavigatorObserver is a listener you attach to a Navigator. The navigator calls it whenever its route stack changes. Observers are the standard place for screen-view analytics, navigation logging, and "refresh when I come back" behavior. They only watch. They cannot veto a navigation.
What an observer sees
Every change to the stack produces one callback. The callbacks receive Route objects, and each route carries its RouteSettings (name and arguments).
| Callback | Fires when | Typical trigger |
|---|---|---|
| `didPush(route, previousRoute)` | A route is added on top | `push`, `pushNamed`, `showDialog` |
| `didPop(route, previousRoute)` | The top route is removed | `pop`, back button, `showDialog` closing |
| `didReplace(newRoute:, oldRoute:)` | A route is swapped for another | `pushReplacement`, `replace` |
| `didRemove(route, previousRoute)` | A route below the top is removed | `removeRoute`, `pushAndRemoveUntil` |
| `didStartUserGesture` / `didStopUserGesture` | An interactive gesture begins or ends | iOS swipe-back |
Newer Flutter versions also provide didChangeTop(topRoute, previousTopRoute). It fires whenever the topmost route changes, whatever caused the change. Check that your Flutter version has it before you rely on it.
An observer also has a navigator property, the NavigatorState it is attached to. You can use it to read the current context or the overlay.
Writing a logging observer
Subclass NavigatorObserver and override only the callbacks you need. Register the observer in MaterialApp.navigatorObservers.
import 'package:flutter/material.dart';
class LoggingObserver extends NavigatorObserver {
String _name(Route<dynamic>? route) => route?.settings.name ?? 'unnamed';
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
debugPrint('push ${_name(route)} (from ${_name(previousRoute)})');
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
debugPrint('pop ${_name(route)} (back to ${_name(previousRoute)})');
}
@override
void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
debugPrint('replace ${_name(oldRoute)} with ${_name(newRoute)}');
}
@override
void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
debugPrint('remove ${_name(route)}');
}
}
void main() => runApp(const DemoApp());
class DemoApp extends StatelessWidget {
const DemoApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: '/',
navigatorObservers: [LoggingObserver()],
routes: {
'/': (context) => Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: () => Navigator.of(context).pushNamed('/details'),
child: const Text('Open details'),
),
),
),
'/details': (context) => Scaffold(
appBar: AppBar(title: const Text('Details')),
),
},
);
}
}When the app starts, the log shows push / (from unnamed). The initial route is pushed onto an empty stack, so it has no previous route. Tapping the button logs push /details (from /). Pressing back logs pop /details (back to /).
Route names can be missing
route.settings.name is null when you navigate with push(MaterialPageRoute(...)) and do not pass settings: RouteSettings(name: ...). An analytics observer that depends on names will then record nothing useful. Either always supply names, or fall back to the route's runtime type, as the unnamed fallback above does.
Dialogs, bottom sheets, and popup menus are also routes. They trigger didPush and didPop too, usually with a null name. Filter on the route type if you only want screens:
bool isScreen(Route<dynamic> route) => route is PageRoute;Reacting inside a screen with RouteObserver and RouteAware
A global observer knows what happened but not which widget cares. For per-screen reactions, Flutter provides RouteObserver, a NavigatorObserver subclass. A widget that mixes in RouteAware can subscribe to it. The most common use is refreshing a list after the user returns from an edit screen.
RouteAware has four callbacks. Each is named from the subscribed screen's point of view.
didPush: this screen was just pushed.didPopNext: a screen above this one was popped, so this screen is visible again.didPushNext: another screen was pushed on top of this one.didPop: this screen was popped.
import 'package:flutter/material.dart';
final RouteObserver<ModalRoute<void>> routeObserver =
RouteObserver<ModalRoute<void>>();
void main() => runApp(
MaterialApp(
navigatorObservers: [routeObserver],
home: const CounterScreen(),
),
);
class CounterScreen extends StatefulWidget {
const CounterScreen({super.key});
@override
State<CounterScreen> createState() => _CounterScreenState();
}
class _CounterScreenState extends State<CounterScreen> with RouteAware {
int _returns = 0;
@override
void didChangeDependencies() {
super.didChangeDependencies();
final route = ModalRoute.of(context);
if (route != null) {
routeObserver.subscribe(this, route);
}
}
@override
void didPopNext() {
setState(() => _returns++);
}
@override
void dispose() {
routeObserver.unsubscribe(this);
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Returned to this screen $_returns times'),
ElevatedButton(
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (context) => Scaffold(
appBar: AppBar(title: const Text('Other')),
),
),
),
child: const Text('Open another screen'),
),
],
),
},
);
}
}Fix before running: the Center closes with }, above by mistake. Use this corrected ending for build:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Returned to this screen $_returns times'),
ElevatedButton(
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (context) => Scaffold(
appBar: AppBar(title: const Text('Other')),
),
),
),
child: const Text('Open another screen'),
),
],
),
),
);
}Three details matter here:
- Subscribe in
didChangeDependencies, notinitState.ModalRoute.of(context)depends on an inherited widget, so it is not safe to call ininitState. - Always unsubscribe in
dispose. A forgotten subscription keeps the state object alive and leaks memory. RouteObservermust be in thenavigatorObserverslist of the navigator that hosts the screen. Otherwisesubscribesucceeds but no callback ever fires.
Observers with go_router
go_router builds a Navigator for you, so you pass observers to the GoRouter constructor instead of MaterialApp.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class LoggingObserver extends NavigatorObserver {
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
debugPrint('push ${route.settings.name ?? route.settings}');
}
}
Widget _page(String title) => Scaffold(appBar: AppBar(title: Text(title)));
final GoRouter router = GoRouter(
observers: [LoggingObserver()],
routes: [
GoRoute(path: '/', builder: (context, state) => _page('Home')),
ShellRoute(
observers: [LoggingObserver()],
builder: (context, state, child) => Scaffold(body: child),
routes: [
GoRoute(path: '/feed', builder: (context, state) => _page('Feed')),
],
),
],
);
void main() => runApp(MaterialApp.router(routerConfig: router));The root observers list watches only the root navigator. A ShellRoute creates its own nested navigator, so pushes inside the shell are invisible to the root observer. Give the shell its own observers list. Observer instances belong to a single navigator, so create a separate instance for each list instead of sharing one.
Also remember that context.go replaces the stack contents. Depending on the target, you may see didPush, didReplace, or didRemove rather than a plain push. Log all of them when you debug.
Common mistakes
- Navigating from inside a callback. Callbacks run while the navigator is changing its stack. Calling
pushorpopsynchronously there can cause reentrancy errors. Schedule follow-up work withWidgetsBinding.instance.addPostFrameCallback. - Counting screen views from
didPushalone. Returning to a screen firesdidPopon the top route, not a push of the screen you land on. UsedidChangeToporRouteAware.didPopNextif "screen became visible" is the event you want. - Assuming one observer sees every navigator. Each
Navigatorneeds its own registration. Nested navigators are the usual surprise. - Heavy work in callbacks. They run on the UI thread during a transition. Queue analytics events and send them asynchronously.
Exercise
A list screen uses RouteAware and calls setState in didPopNext to reload data. After the user opens a detail screen and returns, the list never reloads. The screen subscribes in didChangeDependencies and unsubscribes in dispose. Name two likely causes.
Show answer
First, the RouteObserver instance was never added to navigatorObservers (or to the GoRouter or ShellRoute observers list for the navigator that hosts the list), so no events reach it. Second, the detail screen is pushed on a different navigator than the one the observer is registered with, such as a nested ShellRoute navigator or a root navigator opened with useRootNavigator. Either way the subscription succeeds silently but didPopNext never fires.