Sub topic 10
Declarative navigation and the Router API
This chapter assumes you know Navigator.push and Navigator.pop, MaterialPageRoute, and basic StatefulWidget and ChangeNotifier usage. You should also be comfortable with Future and async. It explains why Flutter has a second navigation model, what the pieces of the Router API do, and how they fit together. The next chapters use go_router, which hides most of this machinery.
Why imperative navigation falls short
With push and pop you describe navigation as a series of commands: "add this screen", "remove the top screen". The stack is the result of every command run so far. This works well for small apps. Four situations make it awkward:
- Deep links. A link such as
/products/42/reviewsshould open a stack of several screens at once. With commands you must push each screen in order and hope nothing else changed the stack. - Web URLs. The browser address bar must always match what is on screen, and the browser back button must move through history. Command-based navigation has no built-in place to report the current location.
- State-driven changes. After login, you may want to replace the whole stack. Removing a screen because some data changed means calling
popfrom code that does not own the screen. - Predictability. If two parts of the app push at the same time, the stack depends on timing.
Declarative navigation reverses the direction. You keep the navigation state as data, and the UI is a function of that data: given this state, the stack is exactly this list of pages.
The declarative idea
The Navigator widget accepts a pages list. Each entry is a Page, such as MaterialPage, that describes one route. When the list changes and the widget rebuilds, the Navigator compares the old and new lists, matches pages by key, and adds, removes, or keeps routes to match. You never call push.
| Aspect | Imperative (`push`/`pop`) | Declarative (`pages`) |
|---|---|---|
| Source of truth | The Navigator's internal stack | Your own state |
| To open a screen | Call `push` | Change state so the page list gains an entry |
| To close a screen | Call `pop` | Change state so the page list loses it |
| Replace the whole stack | Several calls, easy to get wrong | Return a different list |
| URL and deep-link support | Manual | Designed for it |
| Code volume | Small | Larger, unless a package wraps it |
A user can still leave a screen with the back button or a swipe. The Navigator then removes the page itself and calls onDidRemovePage, so your state can catch up. If you skip that callback, your state and the screen disagree.
The Router API pieces
A Navigator with pages handles the stack. To connect the stack to the operating system, URLs, and the system back button, Flutter adds the Router widget. MaterialApp.router creates one for you. It is configured with these objects:
| Object | Role |
|---|---|
| `RouteInformationProvider` | Receives new locations from the platform, such as a deep link or the browser address bar. The default implementation is usually enough. |
| `RouteInformationParser<T>` | Converts a `RouteInformation` (which holds a `Uri`) into your configuration type `T`, and converts `T` back. |
| `RouterDelegate<T>` | Holds the navigation state, builds the `Navigator`, and accepts new configurations in `setNewRoutePath`. |
| `BackButtonDispatcher` | Routes the system back button to the delegate. `MaterialApp.router` supplies a root one. |
The flow runs in both directions. An incoming URL is parsed into a configuration and given to the delegate. When the delegate's state changes, the Router reads currentConfiguration, asks the parser to turn it back into route information, and reports it to the platform. That second direction keeps the browser URL correct.
A complete example
The app below has a home screen and an item screen at /items/<id>. The configuration type is a plain Uri, which keeps the parser trivial. The delegate derives its pages from the current location.
import 'package:flutter/material.dart';
void main() => runApp(const ItemApp());
class ItemApp extends StatefulWidget {
const ItemApp({super.key});
@override
State<ItemApp> createState() => _ItemAppState();
}
class _ItemAppState extends State<ItemApp> {
final ItemDelegate _delegate = ItemDelegate();
final ItemParser _parser = ItemParser();
@override
void dispose() {
_delegate.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerDelegate: _delegate,
routeInformationParser: _parser,
);
}
}
class ItemParser extends RouteInformationParser<Uri> {
@override
Future<Uri> parseRouteInformation(RouteInformation routeInformation) async {
return routeInformation.uri;
}
@override
RouteInformation? restoreRouteInformation(Uri configuration) {
return RouteInformation(uri: configuration);
}
}
class ItemDelegate extends RouterDelegate<Uri>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<Uri> {
@override
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
Uri _location = Uri.parse('/');
@override
Uri get currentConfiguration => _location;
@override
Future<void> setNewRoutePath(Uri configuration) async {
_location = configuration;
}
void _goTo(Uri location) {
_location = location;
notifyListeners();
}
@override
Widget build(BuildContext context) {
final segments = _location.pathSegments;
final isItem = segments.length == 2 && segments.first == 'items';
return Navigator(
key: navigatorKey,
pages: [
MaterialPage<void>(
key: const ValueKey('home'),
child: HomeScreen(
onOpen: (id) => _goTo(Uri.parse('/items/$id')),
),
),
if (isItem)
MaterialPage<void>(
key: ValueKey(_location.path),
child: ItemScreen(id: segments[1]),
),
],
onDidRemovePage: (page) {
if (page.key != const ValueKey('home')) {
_goTo(Uri.parse('/'));
}
},
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key, required this.onOpen});
final void Function(int id) onOpen;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: () => onOpen(42),
child: const Text('Open item 42'),
),
),
);
}
}
class ItemScreen extends StatelessWidget {
const ItemScreen({super.key, required this.id});
final String id;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Item $id')),
body: Center(child: Text('Details for item $id')),
);
}
}Follow what happens when the user taps the button:
onOpen(42)calls_goTo, which changes_locationand callsnotifyListeners.- The Router rebuilds the delegate, and the page list now has two entries. The Navigator animates the item page in.
- The Router reads
currentConfiguration, callsrestoreRouteInformation, and the browser URL becomes/items/42.
When the user presses back, the PopNavigatorRouterDelegateMixin forwards the event to the Navigator found through navigatorKey. The Navigator removes the item page and calls onDidRemovePage, and the delegate resets _location to /. On launch with a deep link to /items/7, the parser returns that Uri, setNewRoutePath stores it, and the first build already contains both pages.
Common errors
- Missing or unstable page keys. The Navigator matches old and new pages by key. Without keys, or with a key that changes on every build, pages are rebuilt or animated incorrectly. Use a stable key per logical screen, such as the path.
- State and stack out of sync. If
onDidRemovePagedoes not update your state, the next rebuild brings the popped page back. - Creating the delegate inside
build. A new delegate on every rebuild discards the navigation state. Create it once ininitStateor a field, as above. - Using a nullable configuration for "home". A
nullconfiguration is ambiguous for the Router. Use a value such asUri.parse('/')for the home screen. - Forgetting
navigatorKey. Without it, the system back button cannot reach the Navigator.
When to choose declarative routing
Choose imperative navigation for small apps, prototypes, and flows that are naturally commands: a dialog, a color picker, a confirmation screen that returns a value. Choose declarative routing when the app targets the web, needs deep links, must restore state from a URL, or changes the whole stack in response to state such as authentication.
Writing a delegate and parser by hand is verbose. Most apps use a package that implements these classes for you. The next chapter sets up go_router, which provides a ready-made parser and delegate and lets you describe routes as a tree of paths.
Exercise
In the example, the user taps "Open item 42" and then presses the system back button. Name the two places where the app's navigation state is updated, and say what would go wrong if onDidRemovePage did nothing.
Show answer
The state is first updated in _goTo, which sets _location to /items/42 and calls notifyListeners. It is updated again in onDidRemovePage, which calls _goTo(Uri.parse('/')) after the Navigator pops the item page. If onDidRemovePage did nothing, _location would still be /items/42. The next rebuild would produce a page list that includes the item page again, so the screen the user just left would reappear, and the URL would still show the item.
Exercise
Why does the example use Uri as the configuration type instead of int? for the selected item id?
Show answer
A nullable type uses null to mean "home", but the Router treats a null configuration as "nothing to report". The browser URL would then not be updated when the user returns home. A Uri always has a value, so / can represent home, and it also maps directly to what the address bar shows.