Sub topic 6
Navigating by route name
This chapter assumes you can define a GoRoute with a path and path parameters, and that you know the difference between go and push. If not, review the chapters on defining routes and on path and query parameters first.
Why names exist
A path string such as /books/42 is easy to write by hand. It is also easy to get wrong. Every call site that builds a URL repeats the path structure. If you rename books to library, you must find every string that mentions it. A typo compiles fine and fails at runtime with the error screen.
A route name is a short, stable label you attach to a route. You navigate to the label and pass the parameters as a map. go_router then builds the URL for you. The path can change in one place, and the call sites keep working.
Naming a route
Add the name argument to a GoRoute. Names must be unique across the whole router, including nested routes. go_router checks this when you create the router, and a duplicate triggers an assertion error in debug mode.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(
initialLocation: '/',
routes: <RouteBase>[
GoRoute(
path: '/',
name: 'home',
builder: (context, state) => const HomeScreen(),
routes: <RouteBase>[
GoRoute(
path: 'books/:id',
name: 'book',
builder: (context, state) => BookScreen(
id: state.pathParameters['id']!,
ref: state.uri.queryParameters['ref'],
),
),
],
),
],
);
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(
'book',
pathParameters: {'id': '42'},
queryParameters: {'ref': 'home'},
),
child: const Text('Open book 42'),
),
),
);
}
}
class BookScreen extends StatelessWidget {
const BookScreen({super.key, required this.id, this.ref});
final String 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'}')),
);
}
}The nested route has the path books/:id with no leading slash. Its full location is /books/42. The name book refers to that full location, so you never write the parent path yourself.
The named navigation methods
Each path-based method has a named counterpart.
| Path-based | Named | Behavior |
|---|---|---|
| `context.go(location)` | `context.goNamed(name, ...)` | Replaces the stack with the one for the target |
| `context.push(location)` | `context.pushNamed(name, ...)` | Adds a page on top of the current stack |
| `context.replace(location)` | `context.replaceNamed(name, ...)` | Swaps the top page for the target |
All named methods accept the same optional arguments:
pathParameters: aMap<String, String>that fills the:idstyle segments.queryParameters: aMap<String, dynamic>appended after?.extra: an arbitrary object that is not part of the URL.
The go versus push rules do not change. goNamed still rebuilds the stack, and pushNamed still stacks a page. Only the way you describe the destination differs.
How the URL is built
go_router looks up the route by name, takes its full path template, and substitutes each parameter. It also encodes values, so a value with a space or a slash is escaped.
import 'package:go_router/go_router.dart';
void printBuiltLocations(GoRouter router) {
// Uses the router from the previous example.
final String plain = router.namedLocation(
'book',
pathParameters: {'id': '42'},
);
final String withQuery = router.namedLocation(
'book',
pathParameters: {'id': '42'},
queryParameters: {'ref': 'home page'},
);
print(plain); // /books/42
print(withQuery); // /books/42?ref=home+page
}namedLocation returns the URL without navigating. It is useful when you need a string, for example for a share link or a Link widget, or for comparing against state.matchedLocation in a redirect.
Common errors
Named navigation fails in a few predictable ways.
- Missing path parameter. If the route needs
:idand you omit it frompathParameters, go_router throws an assertion error that lists the missing key. The error appears at the moment you navigate, not at startup. - Unknown name. A misspelled name throws an assertion error saying no route has that name. Strings are still strings, so this is the same typo risk as with paths, only moved to the name.
- Non-string path parameters.
pathParametersonly accepts strings. Convert numbers yourself withid.toString(). The matchingstate.pathParameters['id']is also a string, so parse it when you need anint. - Putting path values in
queryParameters. A value passed there becomes?id=42and does not fill the:idsegment. The route then fails to build its URL. - Duplicate names. Two routes sharing a name fail the router's creation assertion. Pick names that stay unique as the app grows, such as
bookDetailsinstead ofdetails.
Collecting names in one place
Raw strings scattered through widgets bring back the typo problem. A small constants class keeps them together.
abstract final class RouteNames {
static const String home = 'home';
static const String book = 'book';
}Then write context.goNamed(RouteNames.book, pathParameters: {'id': '42'}). The compiler now catches a misspelled constant. It still cannot check that you passed the right parameters, which is the gap that type-safe routes close in a later chapter.
Names in redirects
A redirect callback must return a location string, not a name. Use namedLocation on the router, or state.namedLocation, to turn a name into a path.
final GoRouter guarded = GoRouter(
redirect: (context, state) {
final bool signedIn = false; // Replace with real auth state.
if (!signedIn && state.matchedLocation != '/login') {
return state.namedLocation('login');
}
return null;
},
routes: <RouteBase>[
GoRoute(
path: '/',
name: 'home',
builder: (context, state) => const Text('Home'),
),
GoRoute(
path: '/login',
name: 'login',
builder: (context, state) => const Text('Login'),
),
],
);Because the redirect reads the path from the route table, renaming /login to /sign-in needs no change in the redirect.
When to use names
Names suit apps with many call sites for the same destination, or paths that may change. Plain paths are fine for a small app and are required when you handle an incoming deep link, since the system gives you a URL and not a name. Both styles can coexist in the same router. A route with a name still matches its path.
Exercise
A route is declared as GoRoute(path: 'books/:id', name: 'book', ...) nested under /. You call context.goNamed('book', queryParameters: {'id': '42'}). What happens, and how do you fix it?
Show answer
The call fails with an assertion error in debug mode because the required path parameter id is missing from pathParameters. Putting id in queryParameters does not fill the :id segment. The fix is context.goNamed('book', pathParameters: {'id': '42'}), which navigates to /books/42.
Exercise
You need a redirect to send signed-out users to the route named login. Why can the redirect not return the string 'login' directly, and what should it return instead?
Show answer
A redirect must return a location, and 'login' would be treated as a path that matches no route. It should return state.namedLocation('login'), which resolves the name to its path, such as /login.