Sub topic 5
Mapping URLs to screens with go_router
This chapter assumes you can build and run a Flutter app and that you know the parts of a URI (scheme, host, path, query). You should also know the basics of Navigator. The platform setup for Android and iOS comes in later chapters. Here you build the Dart side: a router that turns any incoming URL into the right screen.
Why a router package
Flutter's Navigator keeps a stack of pages. It has no built-in idea of a URL. Deep linking needs the opposite: a URL arrives first, and the app must work out which stack of screens it stands for.
Flutter's Router widget provides that. It takes a RouteInformation object (essentially a URI plus optional state) from the platform and turns it into a list of pages. Writing that translation by hand is tedious. go_router, a package maintained by the Flutter team, does it with a declarative list of routes. You describe the URL patterns, and the package builds the page stack.
Add the package:
flutter pub add go_routerHow a link reaches a screen
When the operating system opens your app with a link, Flutter passes the URL to the router as route information. go_router matches it against your route list and builds the screens.
In Flutter 3.27 and later, this delivery is on by default when you use a router. Older versions needed a flutter_deeplinking_enabled meta-data entry on Android and an FlutterDeepLinkingEnabled key on iOS. If links open your app but land on the home screen on an older SDK, check those flags first.
A complete minimal router
The following file runs as shown. It defines a home screen, a product screen that reads a path parameter and a query parameter, and a fallback screen.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() => runApp(const MyApp());
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) => 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 Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: () => context.go('/products/42?ref=button'),
child: const Text('Open product 42'),
),
),
);
}
}
class ProductScreen extends StatelessWidget {
const ProductScreen({super.key, required this.id, this.ref});
final String id;
final String? ref;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Product $id')),
body: Center(child: Text('Referrer: ${ref ?? 'none'}')),
);
}
}
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 matter here.
MaterialApp.routerreplacesMaterialApp. You passrouterConfigand nohome,routes, oronGenerateRoute.- The router is a top-level
final, not something created insidebuild. If you create it inbuild, every rebuild resets navigation state. state.pathParametersandstate.uri.queryParametersare different sources. The first holds values from:idsegments. The second holds the?key=valuepairs, as the DartUriclass parsed them.
Matching rules
go_router compares the URL path to your route patterns segment by segment.
| Pattern | Matches | Does not match |
|---|---|---|
| `/` | `/` | `/products` |
| `/products/:id` | `/products/42` | `/products`, `/products/42/reviews` |
| `/search` | `/search?q=shoes` | `/search/shoes` |
The query string never takes part in matching. /search?q=shoes and /search hit the same route, and the route reads the query itself. A parameter such as :id matches one segment only and is always a String. Convert it yourself, for example with int.tryParse(id).
Nested routes and the page stack
Routes can have children. A child path is relative to its parent, so it must not start with /.
GoRoute(
path: '/products/:id',
builder: (context, state) =>
ProductScreen(id: state.pathParameters['id']!),
routes: [
GoRoute(
path: 'reviews',
builder: (context, state) =>
ReviewsScreen(productId: state.pathParameters['id']!),
),
],
),The child matches /products/42/reviews, and it can read id from its parent's pattern. The important behavior is on the deep link side. When a link opens /products/42/reviews on a cold start, go_router builds the stack ProductScreen then ReviewsScreen. The back button then goes to the product, which is what users expect. If you declare reviews as a separate top-level route, the stack has only one page, and back leaves the app.
Put another way, route nesting decides your back stack for links. Plan it when you design the route tree.
go, push, and the back stack
Inside the app, you move between routes with extension methods on BuildContext.
| Call | Effect |
|---|---|
| `context.go('/products/7')` | Replaces the stack with the pages the URL implies, as a deep link would |
| `context.push('/products/7')` | Adds a page on top of the current stack |
| `context.pop()` | Removes the top page |
| `context.goNamed('product', pathParameters: {'id': '7'})` | Navigates by a route `name`, which avoids hand-built strings |
Use go when the destination is a place in the URL space, and push when it is a temporary screen like a detail view you return from. Because go behaves like a deep link, calling it from a button is also a cheap way to test your route table.
Named routes avoid typos in path strings. Give the route a name: and build locations with goNamed. The package encodes parameter values for you.
Reading data safely
A deep link is outside input, so treat parameters as untrusted text. Keep the screen code defensive:
builder: (context, state) {
final id = int.tryParse(state.pathParameters['id'] ?? '');
if (id == null) return NotFoundScreen(uri: state.uri);
return ProductScreen(id: id.toString());
},This keeps /products/abc from reaching your data layer. A later chapter covers validation in depth. For now, remember that matching a pattern does not mean the value is meaningful.
The fallback screen
errorBuilder runs when no route matches the location, or when a route throws during building. The state.uri it receives holds the full original URL, which makes the fallback useful for logging and for a "go home" button. Without errorBuilder, go_router shows a default error page.
Common errors
- Child path starts with
/.go_routerasserts at startup that nested paths are relative. Remove the leading slash. - Mixing
Navigator.pushNamedwith the router. Named routes registered in the oldMaterialApp.routesmap do not exist underMaterialApp.router. Usecontext.goorcontext.push. - Parameter name mismatch. If the pattern says
:idand the code readspathParameters['productId'], the value isnulland the!throws. Keep the names in one place or use named routes. - Router built inside
build. Navigation state resets whenever the widget rebuilds. - Trailing slash surprises.
/products/42/and/products/42both normally match, but links from outside may carry odd forms. Test the exact URLs your website emits. - Route order. Overlapping patterns resolve in declaration order, so put specific routes such as
/products/newbefore/products/:id.
What you have now
You have a router that maps /products/:id to a screen, reads a path value and a query value, builds a sensible back stack from nested routes, and falls back to an error page. The next chapters connect the operating system to this router and add authentication redirects on top of it.
Exercise
Your router declares /products/:id with a nested child GoRoute(path: 'reviews', ...). A user taps a link to https://example.com/products/9/reviews while the app is closed. Which screens are in the back stack after launch, and what happens if you move reviews to a top-level route with path /products/:id/reviews?
Show answer
With the nested child, the stack is ProductScreen (for id 9) with ReviewsScreen on top, so Back returns to the product. With the top-level route, the URL still matches and ReviewsScreen is shown, but it is the only page in the stack, so Back leaves the app instead of showing the product.
Exercise
A route is declared as GoRoute(path: '/search', ...). Will https://example.com/search?q=boots match it, and where does the screen read boots from?
Show answer
Yes, it matches, because the query string is ignored during matching. The screen reads the value with state.uri.queryParameters['q'].