Sub topic 5
Path and query parameters
This chapter assumes you can read the GoRouter setup and GoRoute definitions from the earlier chapters, and that you know go and push. Here you will learn how to put data into a location and read it back safely.
Two places to carry data
A location in go_router is a URL-style string. It has two parts that can carry data:
- The path, such as
/books/42. A segment that starts with a colon, like:id, is a path parameter. - The query string, such as
?ref=home&page=2. It holds query parameters.
The router uses the path to decide which routes match. It does not use the query string for matching. This difference decides which one to use for a given piece of data.
| Row | Path parameter | Query parameter |
|---|---|---|
| Syntax | `/books/:id` | `?q=dart&page=2` |
| Required to match | Yes, the route does not match without it | No, the route matches with or without it |
| Read with | `state.pathParameters` | `state.uri.queryParameters` |
| Typical use | Identity of a resource (book, user) | Optional filters, paging, tracking |
Use a path parameter when the value identifies what the screen shows. Use a query parameter when the value is optional or changes how the screen shows it.
Declaring and reading path parameters
Put a colon before the segment name in the route's path. The builder receives a GoRouterState, and pathParameters is a Map<String, String>.
Every path parameter is a String. go_router does not convert it to int. A user can type /books/abc in a browser, or a deep link can contain anything, so treat the value as untrusted input.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
routes: <RouteBase>[
GoRoute(
path: 'books/:id',
name: 'book',
builder: (context, state) {
final int? id = int.tryParse(state.pathParameters['id'] ?? '');
if (id == null) {
return const MessageScreen('That is not a valid book id.');
}
final String? ref = state.uri.queryParameters['ref'];
return BookScreen(id: id, ref: ref);
},
),
GoRoute(
path: 'search',
name: 'search',
builder: (context, state) {
final Map<String, String> query = state.uri.queryParameters;
final String text = query['q'] ?? '';
final int page = int.tryParse(query['page'] ?? '') ?? 1;
return SearchScreen(text: text, page: page);
},
),
],
),
],
);
void main() => runApp(const MyApp());
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: Column(
children: [
TextButton(
onPressed: () => context.go('/books/42?ref=home'),
child: const Text('Book 42'),
),
TextButton(
onPressed: () => context.go('/books/abc'),
child: const Text('Bad id'),
),
TextButton(
onPressed: () => context.goNamed(
'search',
queryParameters: {'q': 'dart & flutter', 'page': '2'},
),
child: const Text('Search'),
),
],
),
);
}
}
class BookScreen extends StatelessWidget {
const BookScreen({super.key, required this.id, this.ref});
final int id;
final String? ref;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Book $id')),
body: Center(child: Text('Opened from: ${ref ?? 'unknown'}')),
);
}
}
class SearchScreen extends StatelessWidget {
const SearchScreen({super.key, required this.text, required this.page});
final String text;
final int page;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Search')),
body: Center(child: Text('"$text", page $page')),
);
}
}
class MessageScreen extends StatelessWidget {
const MessageScreen(this.message, {super.key});
final String message;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Oops')),
body: Center(child: Text(message)),
);
}
}Three habits in this code are worth copying:
- Parse with
int.tryParseand handlenull. A bad value then shows a message instead of throwing inbuild. - Give every query parameter a default with
??. A user can open/searchwith no query string. - Read query parameters from
state.uri.queryParameters, not from the path.
Query parameters in detail
state.uri is a Dart Uri, so everything Uri offers is available. The most useful members are:
queryParameters: aMap<String, String>. If a key appears twice, the last value wins.queryParametersAll: aMap<String, List<String>>. Use it for repeated keys such as?tag=a&tag=b.path: the path without the query string.
final List<String> tags = state.uri.queryParametersAll['tag'] ?? <String>[];Query parameters are always strings too, so the same parsing rules apply. For booleans, compare to a known value such as query['sale'] == 'true'.
Building locations safely
A location is text, so characters such as &, ?, #, / and spaces can break it if you paste them into a string yourself. The string '/search?q=dart & flutter' does not mean what you want.
There are two safe ways to build a location:
goNamedorpushNamedwithpathParametersandqueryParameters. go_router encodes the values for you.Uri(path: ..., queryParameters: ...).toString()withgoorpush.
final String location = Uri(
path: '/search',
queryParameters: {'q': 'dart & flutter', 'page': '2'},
).toString();
// /search?q=dart+%26+flutter&page=2
context.go(location);For a path parameter built into a plain string, call Uri.encodeComponent(value) first. A value like a/b would otherwise add a segment and fail to match books/:id.
When the router reads the location back, the values in pathParameters and queryParameters are already decoded. Do not decode them again.
Edge cases and gotchas
- One segment per parameter.
:idmatches one path segment./books/42/extradoes not matchbooks/:idunless a child route exists. - Unique names. Within one matched location, path parameter names share a single map. In nested routes,
pathParametersholds the parameters of every matched route, parent and child. Two routes in the same chain with the same name, such as:idtwice, collide. Use:authorIdand:bookIdinstead. - Missing names throw. With
goNamed, a path parameter that the route declares must be provided, or go_router raises an assertion error in debug builds. Query parameters are never required. - Query changes keep the route. Moving from
/search?page=1to/search?page=2stays on the same route with new data. Make your screen read fromstateon each build, or it will show stale values. - Case and trailing slashes. Matching of paths is not something to rely on for variants. Link to the exact path you declared.
- Large or structured data. Query strings suit small, flat values. For objects, use
extra, covered in the next chapters, and remember that it does not survive a browser reload as a URL does.
Choosing between them
Ask what the user would expect when they copy the URL. If sharing the URL should open the same book, the book id belongs in the path. If it should keep the same sort order or page, put those in the query. If the data cannot be written as text, it does not belong in either.
Exercise
A route is declared as GoRoute(path: 'users/:userId', ...). Your builder needs the user id as an int and an optional tab filter that defaults to 'posts'. Write the two lines that read these values safely, and say what happens to int.tryParse if the URL is /users/abc.
Show answer
final int? userId = int.tryParse(state.pathParameters['userId'] ?? ''); and final String tab = state.uri.queryParameters['tab'] ?? 'posts';. For /users/abc, int.tryParse('abc') returns null instead of throwing, so the builder can show an error screen when userId is null.
Exercise
Why does context.go('/search?q=a & b') risk a wrong result, and what is the safer way to write it?
Show answer
The & is read as a separator, so the query becomes q=a plus a separate key b. Build the location with Uri(path: '/search', queryParameters: {'q': 'a & b'}).toString(), or call goNamed('search', queryParameters: {'q': 'a & b'}), so the value is encoded.