Sub topic 14
Handling unknown locations
This chapter assumes you can define GoRoutes, navigate with go and push, and write a redirect. It covers what go_router does when a location matches no route, how to replace its default error screen, and how to deal with URLs that match a route but point at data that doesn't exist.
What counts as an unknown location
go_router matches a URL against your route tree from the top. A location is unknown when no chain of routes can consume the whole path. Common causes:
- A typo in a string passed to
context.go, such as/bok/42. - A deep link or web URL typed by a user for a page that was removed.
- A path with extra segments, such as
/books/42/reviewswhenbooks/:idhas no childreviews. - A redirect that returns a location that is not declared.
When matching fails, go_router builds a match for a special error route. It does not throw to your app code. By default it shows a Material error page with the attempted location. That page is fine in development and wrong for users, so you replace it.
Replacing the default error screen with errorBuilder
Pass errorBuilder to GoRouter. It receives a BuildContext and a GoRouterState. In the error case, state.uri holds the location that failed and state.error holds the exception.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(
initialLocation: '/',
errorBuilder: (context, state) =>
NotFoundScreen(location: state.uri.toString()),
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
],
);
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: Center(
child: ElevatedButton(
onPressed: () => context.go('/does-not-exist'),
child: const Text('Go somewhere unknown'),
),
),
);
}
}
class NotFoundScreen extends StatelessWidget {
const NotFoundScreen({super.key, required this.location});
final String location;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Page not found')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('No page exists at $location'),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () => context.go('/'),
child: const Text('Back to home'),
),
],
),
),
);
}
}The "Back to home" button uses go, not pop. After a failed deep link there may be nothing below the error page to pop to, so pop could leave the user stuck. Always give the error screen a way out that does not depend on history.
Controlling the page with errorPageBuilder
errorBuilder returns a widget, and go_router wraps it in the platform's default page. If you need to control the page itself, for example to disable the transition or set a page key, use errorPageBuilder. It returns a Page.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(
errorPageBuilder: (context, state) => NoTransitionPage<void>(
key: state.pageKey,
child: Scaffold(
body: Center(child: Text('Unknown: ${state.uri}')),
),
),
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const Text('Home'),
),
],
);Use one or the other. If you set both, errorPageBuilder wins, so errorBuilder is dead code.
Handling exceptions in one place with onException
Recent go_router versions also offer onException. It runs when the router cannot resolve a location, and it gives you the router so you can respond in code instead of showing a page.
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(
onException: (context, state, router) {
// Log the attempted location, then send the user somewhere safe.
router.go('/');
},
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const Text('Home'),
),
],
);This suits apps that treat any bad URL as "go home" and want to record it for analytics. When onException is set, it takes over this job and the error builders are not the main path. Check the changelog of the version you use, since this API is newer than errorBuilder.
A valid route is not a valid resource
The most common mistake is expecting errorBuilder to handle /books/9999 when no book 9999 exists. The path books/:id matches any value, so routing succeeds and your builder runs. go_router knows nothing about your data.
You have two options. The first is to handle it in the screen:
import 'package:flutter/material.dart';
class BookScreen extends StatelessWidget {
const BookScreen({super.key, required this.id});
final String id;
static const Map<String, String> books = {
'1': 'Dune',
'42': 'The Hitchhiker\'s Guide',
};
@override
Widget build(BuildContext context) {
final String? title = books[id];
if (title == null) {
return Scaffold(
appBar: AppBar(title: const Text('Not found')),
body: Center(child: Text('There is no book with id $id')),
);
}
return Scaffold(
appBar: AppBar(title: Text(title)),
body: const Center(child: Text('Details')),
);
}
}The second is a route-level redirect that checks the data and returns a location. This keeps the screen simple, and the URL changes to reflect the problem:
import 'package:go_router/go_router.dart';
final GoRoute bookRoute = GoRoute(
path: 'books/:id',
redirect: (context, state) {
final String? id = state.pathParameters['id'];
const Set<String> knownIds = {'1', '42'};
return knownIds.contains(id) ? null : '/not-found';
},
builder: (context, state) => Text('Book ${state.pathParameters['id']}'),
);For this to work, /not-found must be declared as a real route. Redirecting to an undeclared path sends the user to the error screen anyway.
| Situation | Who handles it | Mechanism |
|---|---|---|
| No route matches the path | go_router | `errorBuilder`, `errorPageBuilder` or `onException` |
| Route matches, data missing | Your code | Screen state or route-level `redirect` |
| Redirect returns an undeclared path | go_router | Same as no match |
Testing the error path
A widget test can navigate to a bad location and assert on the screen. Add flutter_test to dev_dependencies.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
void main() {
testWidgets('shows custom screen for unknown location', (tester) async {
final GoRouter router = GoRouter(
errorBuilder: (context, state) =>
Text('Missing ${state.uri.path}'),
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const Text('Home'),
),
],
);
await tester.pumpWidget(MaterialApp.router(routerConfig: router));
expect(find.text('Home'), findsOneWidget);
router.go('/nope');
await tester.pumpAndSettle();
expect(find.text('Missing /nope'), findsOneWidget);
});
}Common errors
- Forgetting the leading slash on top-level paths. Top-level routes need
/. Child routes must not start with/. A child declared as/books/:idraises an assertion at startup. - Using
popon the error screen. Deep links can leave an empty stack. Usego. - Setting both error builders. Only
errorPageBuilderruns. - Expecting a 404 for missing data. Routing only checks the shape of the path.
- Assuming
state.erroris non-null everywhere. It is set on the error route only. In ordinary route builders it isnull.
Exercise
A user opens /books/9999. Your router has GoRoute(path: 'books/:id', ...) under /, and an errorBuilder. The error builder never runs. Why, and how do you show a "book not found" screen?
Show answer
The path matches books/:id for any id, so routing succeeds and the route builder runs instead of errorBuilder. go_router does not check data. Show the not-found state inside the screen when the lookup returns null, or add a route-level redirect that returns a declared /not-found location when the id is unknown.
Exercise
Why should the "Back to home" button on an error screen call context.go('/') instead of context.pop()?
Show answer
When the app is opened from a deep link, the error page can be the only page in the stack. pop would have nothing to return to. go rebuilds the stack for /, so it always works.