Sub topic 2
Moving between screens with push and pop
Assume you know basic Dart syntax, async and await, Flutter widgets, BuildContext, and how to run a Flutter app. This chapter uses the imperative navigation model, where your code tells Flutter when to add or remove a screen.
How the route stack works
A route is an object that describes a screen and its transition. The Navigator stores routes in a stack. The route at the top is the screen the user currently sees.
pushadds a route to the top of the stack.popremoves the top route.- The system back button usually performs a
pop. - Popping the first route is not allowed because the app would have no screen to display.
Navigator.of(context) finds the nearest navigator above the current widget. Calling push creates a new route. Calling pop removes the current route and reveals the route underneath it.
| Operation | Effect | Visible screen after the operation |
|---|---|---|
| `push(Details)` | Adds `Details` to the stack | Details |
| `push(Settings)` | Adds `Settings` above Details | Settings |
| `pop()` | Removes Settings | Details |
Push a screen and pop it
MaterialPageRoute builds a Material-style page transition. Its builder receives a context for the destination screen.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: const HomeScreen(),
);
}
}
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: (context) => 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: Center(
child: ElevatedButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Go back'),
),
),
);
}
}When the user taps Open details, Flutter pushes DetailScreen. The Home route remains in memory underneath it. When the user taps Go back, pop removes the detail route and shows Home again.
The Navigator belongs to the widget tree, so use a context below the intended navigator. In an app with nested navigators, the nearest navigator might belong to a tab or modal flow rather than the whole app.
Exercise
Exercise
After pushing Home, Details, and Settings in that order, how many pop calls are needed to show Home again?
Show answer
Two. The first pop removes Settings, and the second removes Details.