Sub topic 10
Declarative navigation and the Router API
This chapter assumes Dart async and await, basic Flutter widgets, BuildContext, and the ability to run an app on a device or emulator.
Why declarative navigation exists
Imperative navigation tells Flutter what action to perform:
- Push a details route.
- Pop the current route.
- Replace one route with another.
This model works well for small applications. However, the app can become difficult to reason about when navigation depends on authentication, deep links, browser URLs, or several navigation branches.
Declarative navigation describes the screens that should exist for the current application state. Flutter compares that description with the current navigation state and updates the visible pages.
For example, an unauthenticated user might have only a login page. After authentication, the page list changes to include the home page. The navigation state follows the application state instead of being changed by scattered calls to push and pop.
The Router API working model
Flutter's Router API separates navigation into several responsibilities:
RouteInformationProviderreceives route information, such as a browser URL.RouteInformationParserconverts that information into a typed configuration.RouterDelegateconverts the configuration and app state into pages.BackButtonDispatchercoordinates system back-button requests.Routerconnects these parts.
MaterialApp.router creates the application with this system. The delegate owns the navigation state and returns a Navigator whose pages list is derived from that state.
A minimal delegate can support a home page and a details page:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp.router(
routerDelegate: AppRouterDelegate(),
routeInformationParser: AppRouteParser(),
));
}
class AppRoutePath {
const AppRoutePath(this.uri);
final Uri uri;
}
class AppRouteParser extends RouteInformationParser<AppRoutePath> {
@override
Future<AppRoutePath> parseRouteInformation(
RouteInformation information,
) async {
return AppRoutePath(information.uri);
}
}
class AppRouterDelegate extends RouterDelegate<AppRoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<AppRoutePath> {
@override
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
String? productId;
@override
AppRoutePath get currentConfiguration {
return AppRoutePath(
productId == null ? Uri.parse('/') : Uri.parse('/products/$productId'),
);
}
@override
Future<void> setNewRoutePath(AppRoutePath configuration) async {
final segments = configuration.uri.pathSegments;
productId = segments.length == 2 && segments.first == 'products'
? segments.last
: null;
notifyListeners();
}
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
pages: [
MaterialPage<void>(
child: HomePage(
onOpenProduct: (id) {
productId = id;
notifyListeners();
},
),
),
if (productId != null)
MaterialPage<void>(
child: ProductPage(id: productId!),
),
],
onPopPage: (route, result) {
if (!route.didPop(result)) return false;
productId = null;
notifyListeners();
return true;
},
);
}
}
class HomePage extends StatelessWidget {
const HomePage({required this.onOpenProduct, super.key});
final ValueChanged<String> onOpenProduct;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: () => onOpenProduct('42'),
child: const Text('Open product'),
),
),
);
}
}
class ProductPage extends StatelessWidget {
const ProductPage({required this.id, super.key});
final String id;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Product $id')),
body: const Center(child: Text('Product details')),
);
}
}When productId is null, the delegate returns one page. When it contains 42, it returns two pages. The same state also produces the URL /products/42.
Choosing declarative navigation
Use declarative routing when the app needs deep links, web URLs, authentication redirects, nested navigation, or reliable restoration after process death. Imperative navigation remains simpler for a small app with a short, predictable stack.
The Router API is flexible but verbose. Packages such as go_router provide a shorter route-tree syntax while still using Flutter's declarative routing foundation.
Exercise
What should change when an authenticated user opens the login URL?
Show answer
The router should update its application state and return the page list for the authenticated area, usually redirecting the user away from the login page.