Navigator manages a stack of routes. Pushing places a route on top; popping removes the current route. For a small local screen flow, this is a useful starting point before introducing URL-driven routing.
Keep navigation at an interaction boundary
Navigate from a user callback or a deliberate feature event. Do not push a route every time build runs. A rebuild describes a screen and can happen repeatedly for reasons unrelated to navigation.
Worked example
This is a complete example. Open it with Run example, then use Run inside DartPad.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: LibraryPage()));
class LibraryPage extends StatelessWidget {
const LibraryPage({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Library')),
body: Center(child: FilledButton(onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => const DetailPage())),
child: const Text('Open a lesson'))),
);
}
class DetailPage extends StatelessWidget {
const DetailPage({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Lesson details')),
body: Center(child: TextButton(onPressed: () => Navigator.pop(context),
child: const Text('Return to library'))),
);
}Read the result
The first screen remains below the detail route. The AppBar back button and explicit return action can both pop the current route. The generic void indicates this route is not expected to return a result.
Read the stack as a history of locations
After the detail route is pushed, the library route still exists underneath it. Popping removes the detail route and reveals that earlier location. Repeatedly pushing another copy of the library would create a different history and can leave the user pressing Back through duplicate home screens.
The callback executes only when the control is activated. Putting the push inside build would make navigation a side effect of rendering and could repeat it during unrelated updates.
Next use typed route results when a destination must return a selection. Choose declarative routing when a URL or incoming link should describe the destination independently of the current in-memory history.
Practice and verification
Push another detail screen and draw the resulting stack. Then use the back action one step at a time. Explain why repeatedly pushing a home screen is different from returning to an existing one.