Sub topic 6
Path and query parameters
This chapter assumes you have read the earlier chapters on URI anatomy and on mapping URLs to screens with go_router. You should know what Uri.parse returns and how a GoRoute maps a path to a builder. Here the focus is on the data inside a link: where it lives, how to read it, and what to do when it is missing or wrong.
Two places for data in a URL
A deep link such as https://example.com/products/42?ref=email carries data in two places.
- Path parameters are segments of the path that identify a resource. In
/products/42, the value42says which product to show. - Query parameters come after
?askey=valuepairs joined by&. They hold optional modifiers such asref=email, a sort order, or a filter.
The rule of thumb: if the screen cannot exist without the value, make it a path parameter. If the screen works without it, make it a query parameter.
| Question | Path parameter | Query parameter |
|---|---|---|
| Part of route matching? | Yes. `/products/:id` will not match `/products` | No. Any query string matches the same route |
| Required? | Yes | No, and may be absent |
| Typical use | Resource identity (`42`) | Tracking, filters, sort, return address |
| Can repeat? | No, one value per segment | Yes: `?tag=a&tag=b` |
| go_router accessor | `state.pathParameters` | `state.uri.queryParameters` |
Declaring and reading parameters
A path parameter is declared with a leading colon. The route builder receives a GoRouterState that exposes both kinds of data. The example below is a complete app you can paste into main.dart after adding go_router to pubspec.yaml.
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',
name: 'product',
builder: (context, state) {
final id = int.tryParse(state.pathParameters['id'] ?? '');
if (id == null) return NotFoundScreen(uri: state.uri);
final ref = state.uri.queryParameters['ref'];
return ProductScreen(id: id, ref: ref);
},
),
],
errorBuilder: (context, state) => NotFoundScreen(uri: state.uri),
);
void main() => runApp(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.goNamed(
'product',
pathParameters: {'id': '42'},
queryParameters: {'ref': 'home'},
),
child: const Text('Open product 42'),
),
),
);
}
}
class ProductScreen extends StatelessWidget {
const ProductScreen({super.key, required this.id, this.ref});
final int id;
final String? ref;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Product $id')),
body: Center(child: Text('Arrived from: ${ref ?? 'unknown'}')),
);
}
}
class NotFoundScreen extends StatelessWidget {
const NotFoundScreen({super.key, required this.uri});
final Uri uri;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Not found')),
body: Center(child: Text('No screen for $uri')),
);
}
}Three details in this code matter.
state.pathParametersis aMap<String, String>. Every value is a string, even when it looks like a number. Convert it yourself.state.uri.queryParametersis aMap<String, String>too, and a missing key returnsnull. Treat every query value as nullable.- The
goNamedcall builds the URL for you, so you do not concatenate strings. This is also how you build links to share, which keeps the format in one place.
Type conversion and bad values
Anyone can type /products/abc into a browser or craft such a link. Matching only checks that a segment exists, not that it is a number. If you write int.parse(state.pathParameters['id']!), a malformed link throws a FormatException inside the builder.
Use int.tryParse and decide what a failure means. The example above shows the NotFoundScreen without a redirect. You can also reject bad values earlier with a route-level redirect, so the builder only ever sees valid input:
GoRoute(
path: '/products/:id',
redirect: (context, state) {
final id = int.tryParse(state.pathParameters['id'] ?? '');
return id == null ? '/' : null;
},
builder: (context, state) {
final id = int.parse(state.pathParameters['id']!);
return ProductScreen(id: id);
},
),Here int.parse is safe because the redirect already ran and returned null only for valid ids. Choose between a redirect and a fallback screen by asking whether the user should see the bad URL. A fallback screen keeps the address visible, which helps support and debugging. A redirect hides the problem.
Query parameters with several values
A query key can appear more than once, as in /search?tag=dart&tag=flutter. The queryParameters map keeps only one value per key, and the last one wins. To get all of them, use queryParametersAll:
GoRoute(
path: '/search',
builder: (context, state) {
final q = state.uri.queryParameters['q'] ?? '';
final tags = state.uri.queryParametersAll['tag'] ?? const <String>[];
return Text('Search "$q" with tags $tags');
},
),When you build such a link with goNamed, pass a list as the value: queryParameters: {'tag': ['dart', 'flutter']}. go_router expands it into repeated keys.
Encoding
Values in a URL are percent-encoded. A space becomes %20 and a slash inside a value becomes %2F. go_router decodes values before it gives them to you, so state.pathParameters['id'] for /products/a%20b is a b. Do not decode again. Decoding twice corrupts values that legitimately contain a %.
The reverse matters when you build strings by hand. If you place a whole URL inside a query parameter, as the login redirect from the guards chapter does, call Uri.encodeComponent on it first. Without this, the ? and & inside the inner URL are read as part of the outer one.
Things deep links cannot carry
Inside the app you can pass a Dart object with context.go('/products/42', extra: product). A deep link cannot do this. The operating system delivers only a URL string, so state.extra is null when the screen is opened from a link. A screen that depends on extra works from in-app taps and breaks from deep links.
Design each screen to rebuild itself from the URL alone. Pass the id, then load the product from your repository or cache inside the screen. Use extra only as an optional shortcut that avoids a reload, and fall back to loading by id when it is null.
Common errors
- Route never matches. The pattern
/product/:iddoes not match/products/42. The path must match segment for segment, and the colon part matches exactly one segment. - Query parameter ignored. Putting
?ref=into the route'spathstring does not work. Query strings are never part of the pattern. Read them fromstate.uri. - Crash on a malformed id. Using
int.parseor the!operator on user-controlled input. UsetryParseand handlenull. - Parameter null after navigation. The name in
pathParametersmust match the name in the pattern, including case::idis read as'id'. - Screen empty from a link. The screen reads
state.extra, which a link never provides.
Exercise
A link https://example.com/orders/17?expand=items&expand=history opens a route declared as /orders/:orderId. Write the expressions that read the order id as an int (possibly null) and the list of expand values, and say why state.uri.queryParameters['expand'] is the wrong choice for the list.
Show answer
Use int.tryParse(state.pathParameters['orderId'] ?? '') for the id, and state.uri.queryParametersAll['expand'] ?? const <String>[] for the list, which gives [items, history]. queryParameters keeps one value per key and the last one wins, so it would return only history and drop items.
Exercise
Your OrderScreen works when opened with context.go('/orders/17', extra: order) but shows a blank page when opened from a deep link. What is the cause and the fix?
Show answer
A deep link delivers only the URL string, so state.extra is null and the screen has no Order object. Pass or read only the id from pathParameters, load the order by id inside the screen, and treat extra as an optional shortcut that skips the load when present.