Sub topic 12
Path and query parameters
This chapter covers how go_router reads data from a URL. It assumes you can define a GoRouter with nested GoRoute entries (the previous chapter), you know basic Dart async code, and you know what BuildContext is.
Why parameters live in the URL
With imperative navigation you pass data through constructors or arguments. Those values exist only in memory. If the app restarts, or a link opens the app directly, the values are gone.
go_router puts the identifying data in the location string, which is the URL-like text such as /products/42?tab=reviews. That string can be restored, shared, and opened as a deep link. The location has two kinds of parameters:
- A path parameter is a named segment of the path, such as
:idinproducts/:id. It identifies which resource to show. - A query parameter comes after
?askey=valuepairs separated by&. It holds optional settings such as a filter, a sort order, or a selected tab.
A good rule: if the screen cannot make sense without the value, use a path parameter. If the value tweaks how the screen looks, use a query parameter.
Reading path parameters
Declare a parameter with a leading colon. Read it from GoRouterState.pathParameters, a Map<String, String>.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
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 42'),
),
),
);
}
}
class ProductScreen extends StatelessWidget {
const ProductScreen({super.key, required this.id, this.tab = 'details'});
final String id;
final String tab;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Product $id')),
body: Center(child: Text('Showing the $tab tab')),
);
}
}
final GoRouter router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'products/:id',
builder: (context, state) {
final id = state.pathParameters['id']!;
final tab = state.uri.queryParameters['tab'] ?? 'details';
return ProductScreen(id: id, tab: tab);
},
),
],
),
],
);
void main() => runApp(MaterialApp.router(routerConfig: router));Three details matter here.
- Child paths do not start with a slash.
products/:idunder/produces the full path/products/:id. A leading slash on a child path is an error. - Every path parameter is a
String. The!is safe because a route with:idonly matches when the segment exists. state.uriis a DartUri. ItsqueryParametersmap holds the query values, also as strings.
Reading query parameters
Query parameters are never part of the route's path pattern. You do not declare them. The route products/:id matches /products/42, /products/42?tab=reviews, and /products/42?foo=bar. Your builder decides which keys it cares about.
Query values may be absent, so always handle null. The example above falls back to 'details'.
If a key can repeat, as in ?tag=a&tag=b, queryParameters keeps only one value. Use state.uri.queryParametersAll, which returns a Map<String, List<String>>.
final tags = state.uri.queryParametersAll['tag'] ?? const <String>[];Converting types safely
Because everything arrives as a string, convert it yourself. A user, or a stale link, can supply anything, so never assume the conversion works.
GoRoute(
path: 'products/:id',
builder: (context, state) {
final id = int.tryParse(state.pathParameters['id'] ?? '');
if (id == null) {
return const Scaffold(body: Center(child: Text('Invalid product id')));
}
return ProductScreen(id: id.toString());
},
),int.parse throws a FormatException on /products/abc. int.tryParse returns null, which lets you show a fallback screen. For a nicer experience, you can also redirect to a not-found page, which a later chapter on redirects covers.
Building locations correctly
When you build a location from user input, do not concatenate raw strings. A value containing /, ?, #, or a space would break the structure. Two tools help.
Uribuilds an encoded location.context.namedLocationandcontext.goNamedfill in parameters for you when the route has aname.
GoRoute(
name: 'product',
path: 'products/:id',
builder: (context, state) => ProductScreen(
id: state.pathParameters['id']!,
tab: state.uri.queryParameters['tab'] ?? 'details',
),
),context.goNamed(
'product',
pathParameters: {'id': '42'},
queryParameters: {'tab': 'reviews'},
);This navigates to /products/42?tab=reviews. go_router encodes the values, so a query value of red & blue becomes red%20%26%20blue and is decoded again when you read it. Named navigation also protects you from typos in long paths and from path changes: you rename the pattern in one place and the call sites keep working.
You can do the same with a plain string by using Uri:
final location = Uri(
path: '/products/42',
queryParameters: {'tab': 'reviews'},
).toString();
context.go(location);Passing objects with `extra`
Sometimes you already hold a full object and want to avoid loading it again. go and push accept an extra argument, and the destination reads it from state.extra.
context.push('/products/42', extra: product);builder: (context, state) {
final product = state.extra as Product?;
return ProductScreen(id: state.pathParameters['id']!, preloaded: product);
},Treat extra as an optimization, not as the source of truth. It is not part of the URL. On the web, after a refresh, or when a deep link opens the app, extra is null. The screen must be able to load the product from the id alone. Casting with as Product (without ?) crashes in those cases.
Query parameter changes and rebuilds
Navigating from /products/42?tab=details to /products/42?tab=reviews keeps the same route and changes only the query. go_router rebuilds the builder with the new state, so your screen reads the new tab. Use context.replace or context.go to change the query without growing the back stack:
void selectTab(BuildContext context, String id, String tab) {
context.go('/products/$id?tab=$tab');
}Here id and tab are known-safe values. For free-form text, build the location with Uri as shown earlier.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Assertion about a path starting with `/` | A nested `GoRoute` path begins with a slash | Remove the leading slash from child paths |
| `Null check operator used on a null value` on `pathParameters['id']!` | The key name in the builder differs from the pattern, such as `:productId` vs `'id'` | Use the same name in both places |
| `type 'String' is not a subtype of type 'int'` | Treating a path parameter as an `int` | Parse it with `int.tryParse` |
| `extra` is `null` after a refresh | `extra` is not stored in the URL | Load the data from the path parameter |
| A query value with `&` is cut off | The location was built by string concatenation | Use `Uri` or `goNamed` with `queryParameters` |
| Wrong route matches | Two patterns overlap, such as `products/new` and `products/:id` | Put the more specific route first |
The last row deserves a note. go_router tries routes in order, so products/new must appear before products/:id. Otherwise new is captured as an id.
How matching works
The following diagram shows what happens when the location /products/42?tab=reviews arrives.
Choosing between the options
| Data | Best place | Reason |
|---|---|---|
| Identity of a resource (product id, user id) | Path parameter | Required, part of the URL, survives restart |
| Filters, sort, selected tab, search text | Query parameter | Optional, shareable, order-independent |
| A large or already-loaded object | `extra` | Avoids a reload, but must be optional |
| Secrets or tokens | Neither | URLs appear in logs and history |
Exercise
A route is declared as GoRoute(path: 'search/:category', ...) under /. The user opens /search/shoes?sort=price&sort=rating. Write the builder lines that read the category as a string, read the first sort value with a default of 'relevance', and read all sort values as a list. Also say what happens with context.go('/search/shoes?q=red & blue') and how to fix it.
Show answer
Category: final category = state.pathParameters['category']!;. First sort: final sort = state.uri.queryParameters['sort'] ?? 'relevance';. For queryParameters, repeated keys keep a single value, so it does not return both. All sort values: final sorts = state.uri.queryParametersAll['sort'] ?? const <String>[];, which gives ['price', 'rating']. The call with q=red & blue breaks because the unencoded & and spaces end or corrupt the value, so q would be read as red and a stray key would appear. Fix it by building the location with Uri(path: '/search/shoes', queryParameters: {'q': 'red & blue'}).toString(), or by calling context.goNamed with a queryParameters map.
Exercise
Why is it a bug to write final product = state.extra as Product; in a builder for /products/:id, and what should the screen do instead?
Show answer
extra is not part of the URL, so it is null after a browser refresh, a restart, or a deep link. The non-nullable cast throws in those cases. Cast to Product? and, when it is null, load the product using the id path parameter.