Sub topic 5
Mapping URLs to Screens with `go_router`
Assume you know basic Dart and Flutter widgets, understand URL parts, and have used Navigator or named routes. This chapter uses the go_router package to connect incoming URLs to Flutter screens.
Why use declarative routing?
A router describes the relationship between a URL and the screen that should display it. For example, /products/42 can open the product screen for product 42.
go_router works with MaterialApp.router. Instead of calling Navigator.push from several places, you define routes in one configuration.
flowchart TD
A[Incoming URL] --> B[go_router]
B --> C{Route matches?}
C -->|Yes| D[Read path and query values]
D --> E[Build the matching screen]
C -->|No| F[Show fallback screen]Define routes with `GoRouter`
Add go_router to pubspec.yaml, then create a router. A route's path describes the URL pattern. A colon introduces a path parameter.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
GoRoute(
path: '/products/:id',
builder: (context, state) {
final id = state.pathParameters['id']!;
final ref = state.uri.queryParameters['ref'];
return ProductScreen(id: id, ref: ref);
},
),
],
errorBuilder: (context, state) {
return NotFoundScreen(uri: state.uri);
},
);
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 const Scaffold(
body: Center(child: Text('Home')),
);
}
}
class ProductScreen extends StatelessWidget {
const ProductScreen({
required this.id,
this.ref,
super.key,
});
final String id;
final String? ref;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Product $id')),
body: Center(child: Text('Referral: ${ref ?? 'none'}')),
);
}
}
class NotFoundScreen extends StatelessWidget {
const NotFoundScreen({required this.uri, super.key});
final Uri uri;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Text('No page for ${uri.path}')),
);
}
}The route /products/:id matches /products/42. The value 42 is available through state.pathParameters['id']. The URL /products/42?ref=email also has a query parameter. Read it with state.uri.queryParameters['ref'].
| URL part | Example | `go_router` access |
|---|---|---|
| Fixed path | `/products` | Defined directly in `path` |
| Path parameter | `/products/42` | `state.pathParameters['id']` |
| Query parameter | `?ref=email` | `state.uri.queryParameters['ref']` |
Navigate to a route
Use context.go when the destination should become the current location. Use context.push when you want to add a page to the navigation stack.
ElevatedButton(
onPressed: () {
context.go('/products/42?ref=home');
},
child: const Text('Open product'),
)When values come from users or external links, validate them before using them to load data. A route parameter is text from outside the screen, not proof that a product exists.
> callout note > Keep route paths stable. Links may be stored in messages, browser history, and search results. Changing /products/:id later can break existing links.
Exercise
Which expression reads the id from /products/42?ref=email, and which expression reads email?
Show answer
Use state.pathParameters['id'] for 42 and state.uri.queryParameters['ref'] for email.