Sub topic 12
Testing navigation between screens
This chapter shows how to test code that pushes and pops routes. It assumes you can already build a widget with pumpWidget, find widgets, tap them, and tell pump from pumpAndSettle. All examples use the Navigator API with MaterialApp.
What a navigation test checks
A navigation test usually checks one of three things:
- The new screen appears after a tap.
- The old screen is gone, or hidden, while the new one is on top.
- Going back returns to the first screen, sometimes with a result.
You can check these through what is on screen, or through the Navigator itself. Both approaches are covered below.
The route needs a Navigator
Navigator.of(context) fails if no Navigator sits above the widget. MaterialApp creates one, so wrap the widget under test in MaterialApp. A bare Scaffold is not enough. The test then runs the same route and transition code that the app uses.
Pushing a screen and going back
This test opens a detail screen, checks it, and returns.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
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.of(context).push(
MaterialPageRoute<void>(builder: (_) => const DetailScreen()),
),
child: const Text('Open details'),
),
),
);
}
}
class DetailScreen extends StatelessWidget {
const DetailScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Details')),
body: const Center(child: Text('Detail body')),
);
}
}
void main() {
testWidgets('opens the detail screen and goes back', (tester) async {
await tester.pumpWidget(const MaterialApp(home: HomeScreen()));
expect(find.text('Detail body'), findsNothing);
await tester.tap(find.text('Open details'));
await tester.pumpAndSettle();
expect(find.text('Detail body'), findsOneWidget);
expect(find.text('Open details'), findsNothing);
await tester.tap(find.byType(BackButton));
await tester.pumpAndSettle();
expect(find.text('Detail body'), findsNothing);
expect(find.text('Open details'), findsOneWidget);
});
}AppBar adds a BackButton on its own when the route can pop, so the test never needs to build one. tester.pageBack() does the same job. It taps either a Material or a Cupertino back button, which helps when the platform varies.
Why pumpAndSettle matters here
A route transition is an animation. It takes about 300 ms on Material. The tap call only runs the button's onPressed. The Navigator has been told to push, but the transition has not started rendering.
pump()builds one frame. The new route exists but is at the start of its animation.pump(const Duration(milliseconds: 500))advances fake time by that amount, which is long enough to finish a typical transition.pumpAndSettle()keeps pumping until no frames are scheduled.
For navigation, pumpAndSettle() is the usual choice.
Offstage routes are skipped by finders
After a push, the previous route often stays in the widget tree. Flutter keeps it alive with maintainState, so it keeps its scroll position and state. The covered route is built offstage, which means it takes part in the tree but is not painted.
Finders skip offstage widgets by default. That is why find.text('Open details') returns findsNothing after the push. The widget still exists. If you want to prove that the state was kept, turn the skipping off:
expect(find.text('Open details', skipOffstage: false), findsOneWidget);Use skipOffstage: false for tests about preserved state. For ordinary assertions about what the user sees, leave the default, because it matches what a user can see.
Verifying navigation with a NavigatorObserver
Sometimes the destination screen is heavy, or you only care that the right route was requested. A NavigatorObserver receives a callback for each push and pop. The observer below records route names.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class RecordingObserver extends NavigatorObserver {
final List<String?> pushedNames = [];
final List<String?> poppedNames = [];
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
pushedNames.add(route.settings.name);
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
poppedNames.add(route.settings.name);
}
}
void main() {
testWidgets('pushes the settings route by name', (tester) async {
final observer = RecordingObserver();
await tester.pumpWidget(
MaterialApp(
navigatorObservers: [observer],
routes: {
'/': (context) => Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () =>
Navigator.of(context).pushNamed('/settings'),
child: const Text('Settings'),
),
),
),
'/settings': (context) => Scaffold(
body: Center(
child: TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Close'),
),
),
),
},
),
);
// The initial route is reported as a push too.
expect(observer.pushedNames, ['/']);
await tester.tap(find.text('Settings'));
await tester.pumpAndSettle();
expect(observer.pushedNames, ['/', '/settings']);
await tester.tap(find.text('Close'));
await tester.pumpAndSettle();
expect(observer.poppedNames, ['/settings']);
});
}The observer approach needs routes with a settings.name. Routes created with MaterialPageRoute and no settings have a null name. Pass settings: const RouteSettings(name: '/detail') in the app code if you want to assert on names.
Choosing a verification style
| Style | What it proves | Weakness |
|---|---|---|
| Finders on the new screen | The user sees the right content | Slower, depends on the destination's build |
| `NavigatorObserver` | The right route was pushed or popped | Does not prove the screen renders |
| `skipOffstage: false` | The old route is kept in memory | Checks an implementation detail |
Most tests need only the first style. Add an observer when the screen is expensive to build or when the push happens as a side effect with no visible change.
Returning a result from a screen
Navigator.push<T> returns a Future<T?> that completes when the route pops. A test for this flow taps through both screens and checks the first one.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class ColorHome extends StatefulWidget {
const ColorHome({super.key});
@override
State<ColorHome> createState() => _ColorHomeState();
}
class _ColorHomeState extends State<ColorHome> {
String _choice = 'none';
Future<void> _pick() async {
final result = await Navigator.of(context).push<String>(
MaterialPageRoute<String>(builder: (_) => const PickerScreen()),
);
if (!mounted) return;
setState(() => _choice = result ?? 'none');
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Text('Chosen: $_choice'),
ElevatedButton(onPressed: _pick, child: const Text('Pick color')),
],
),
);
}
}
class PickerScreen extends StatelessWidget {
const PickerScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: [
ListTile(
title: const Text('Red'),
onTap: () => Navigator.of(context).pop('Red'),
),
ListTile(
title: const Text('Blue'),
onTap: () => Navigator.of(context).pop('Blue'),
),
],
),
);
}
}
void main() {
testWidgets('shows the color returned by the picker', (tester) async {
await tester.pumpWidget(const MaterialApp(home: ColorHome()));
expect(find.text('Chosen: none'), findsOneWidget);
await tester.tap(find.text('Pick color'));
await tester.pumpAndSettle();
await tester.tap(find.text('Red'));
await tester.pumpAndSettle();
expect(find.text('Chosen: Red'), findsOneWidget);
});
}The second pumpAndSettle does two jobs. It finishes the pop animation, and it lets the awaited Future complete so setState runs. Without it, the assertion would see the old text.
Common errors
- "Navigator operation requested with a context that does not include a Navigator." The widget is not under a
MaterialApp. Wrap it. - The new screen is not found. The test used
pump()and checked before the transition finished, or the finder matches text in a widget that is offstage. find.textfinds two widgets. The same title appears on both screens, for example an app bar title repeated in a body. Usefind.descendant(of: find.byType(AppBar), matching: find.text('Details')).- Timeout in
pumpAndSettle. An endless animation is running. Pump a fixed duration instead. pageBackfinds no button. The route is the first one, or the screen has a custom app bar with no back button. Tap your own widget.
If you use a router package such as go_router, the testing pattern is the same. Build MaterialApp.router with the router configuration, tap, pumpAndSettle, and assert on content. Router packages may also let you read the current location, which is the equivalent of the observer approach.
Exercise
A test taps a button that pushes a detail route, calls await tester.pump() once, and then expects find.text('Detail body') to find one widget. The test sometimes fails because the screen is not yet fully visible. Which change fixes it, and when would you choose a fixed-duration pump instead?
Show answer
Replace pump() with pumpAndSettle(), which keeps pumping frames until the route transition has finished. Choose pump(const Duration(milliseconds: 400)) instead when the new screen has an animation that never ends, such as a CircularProgressIndicator, because pumpAndSettle would time out.
Exercise
After pushing a second screen, expect(find.text('Home'), findsNothing) passes, yet the home screen is still in memory. Why does the finder not see it, and how would you assert that it still exists?
Show answer
The covered route is kept in the tree but built offstage, and finders skip offstage widgets by default. Use find.text('Home', skipOffstage: false) with findsOneWidget to assert that the widget still exists.