Sub topic 11
Setting up go_router
Assume you know Dart async and await, basic Flutter widgets, BuildContext, and how to run a Flutter app. This chapter uses go_router to describe navigation as a tree of URL paths instead of calling Navigator.push throughout the widget tree.
Add go_router to the project
From the project directory, run:
flutter pub add go_routerThis adds the package to pubspec.yaml and fetches its dependencies. Import it where you define the app's routing configuration:
import 'package:go_router/go_router.dart';Define a route tree
A GoRouter contains GoRoute objects. Each GoRoute maps a path to a widget. The builder receives the current BuildContext and route state.
The child path is written without its leading slash because it is relative to /. Together, the routes match URLs such as /products/42.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(
initialLocation: '/',
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'products/:id',
builder: (context, state) {
final id = state.pathParameters['id']!;
return ProductScreen(id: id);
},
),
],
),
],
);
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(routerConfig: router);
}
}
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: () => context.go('/products/42'),
child: const Text('Open product'),
),
),
);
}
}
class ProductScreen extends StatelessWidget {
const ProductScreen({required this.id, super.key});
final String id;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Product')),
body: Center(child: Text('Product ID: $id')),
);
}
}MaterialApp.router connects Flutter's application widget to the router. The initialLocation determines the first location when the app starts.
| Part | Purpose |
|---|---|
| `GoRouter` | Stores the route configuration |
| `GoRoute` | Maps one path to a page |
| `builder` | Creates the page for a matched route |
| `pathParameters` | Reads values such as `42` from `:id` |
| `MaterialApp.router` | Installs router-based navigation |
Choose the navigation operation
Use context.go('/products/42') when the new location should become the current app location. This is useful for links and destinations represented by URLs. Use context.push('/products/42') when you want to add a page to the navigation stack and return with the back button.
Exercise
What value does state.pathParameters['id'] contain when the location is /products/42?
Show answer
It contains the string 42, because :id names the dynamic path segment.