Sub topic 11
Showing a fallback for unknown links
This chapter assumes you already have a working go_router setup with path parameters, as covered in the earlier chapters on routing. It also assumes you can parse a URI with Dart's Uri class. Here you decide what the app does when a link arrives and nothing sensible can be shown for it.
What counts as an unknown link
Every link can fail in one of four ways:
- No route matches. The path is
/offers/summer, but no route has that pattern. This can be an old link, a typo, or a feature you removed. - A route matches but the data is bad.
/products/abcmatches/products/:id, butabcis not a valid ID./products/9999has a valid ID, but no such product exists. - The link is malformed. The string cannot be parsed as a URI at all, for example
https://exa mple.com/%zz. - The link is not yours. The host is not one your app serves. This can only happen when you handle raw links yourself.
Each case needs a different response. The first is a routing problem. The second is a data problem, and the router cannot detect it for you. The third is an input problem. The fourth should usually be ignored without any UI.
Unmatched paths with errorBuilder
GoRouter takes an errorBuilder. It runs whenever the requested location matches no route. The GoRouterState it receives has the requested uri and an error object that describes the failure.
The fallback screen should do three things: say plainly that the content was not found, show what was requested, and give the user a way out. A dead end with only a back arrow is a poor result, because on a cold start there may be nothing to go back to.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class NotFoundScreen extends StatelessWidget {
const NotFoundScreen({super.key, required this.requested});
final String requested;
@override
Widget build(BuildContext context) {
final shown =
requested.length > 100 ? '${requested.substring(0, 100)}…' : requested;
return Scaffold(
appBar: AppBar(title: const Text('Page not found')),
body: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('We could not open this link:'),
const SizedBox(height: 8),
Text(shown, textAlign: TextAlign.center),
const SizedBox(height: 24),
FilledButton(
onPressed: () => context.go('/'),
child: const Text('Go to home'),
),
],
),
),
),
);
}
}The screen uses context.go('/') rather than pop. go replaces the whole stack with the home route, so it works whether the user arrived from a running app or from a cold start.
The requested string is shown with a plain Text widget, which renders it literally, and it is cut to 100 characters. Flutter does not interpret link content as markup, but a very long URL would still break your layout.
Valid route, invalid data
A pattern like /products/:id matches any single segment, so the router cannot tell you that abc is not an ID. You have to check the value in the route. Reusing the same fallback screen keeps the behavior consistent.
This example is complete and runnable with go_router in pubspec.yaml:
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
const _catalog = {1: 'Tea', 2: 'Coffee', 3: 'Cocoa'};
final router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
GoRoute(
path: '/products/:id',
builder: (context, state) {
final id = int.tryParse(state.pathParameters['id'] ?? '');
final name = id == null ? null : _catalog[id];
if (name == null) {
return NotFoundScreen(requested: state.uri.toString());
}
return ProductScreen(id: id!, name: name);
},
),
],
errorBuilder: (context, state) =>
NotFoundScreen(requested: state.uri.toString()),
);
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: FilledButton(
onPressed: () => context.go('/products/1'),
child: const Text('Open product 1'),
),
),
);
}
}
class ProductScreen extends StatelessWidget {
const ProductScreen({super.key, required this.id, required this.name});
final int id;
final String name;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(name)),
body: Center(child: Text('Product #$id: $name')),
);
}
}
// NotFoundScreen is the class from the previous listing.
void main() => runApp(MaterialApp.router(routerConfig: router));Using int.tryParse instead of int.parse matters here. int.parse('abc') throws a FormatException inside a builder, which gives the user a red error screen in debug mode and a crash-like blank in release. Every parse of link input should be a tryParse followed by a null check.
In a real app the lookup is usually asynchronous, such as a network call. The same idea applies, but the not-found state becomes one branch of a loading, loaded, or not-found view inside the screen. Do not treat "still loading" as "not found".
Choosing a fallback strategy
Showing an error page is not the only choice. The right one depends on how likely the link is to be valid for the user.
| Strategy | Behavior | Good for |
|---|---|---|
| Not-found screen | Shows the URL and a button to go home | Most apps; honest and easy to debug |
| Redirect to a parent | Sends `/products/9999` to `/products` | Catalog or list sections where a parent page is useful |
| Redirect to home | Silently opens `/` | Retired campaign links where an error would confuse |
| Ignore | Does nothing | Links with a foreign host, in manual handlers |
Recent versions of go_router also provide an onException callback on GoRouter. It receives the context, the state, and the router, so you can call router.go(...) yourself instead of building a widget. Check the changelog for your installed version before relying on it. errorBuilder works in every version.
Whichever you choose, record the event. A not-found log with the requested URL tells you which old links are still in circulation, such as emails or printed QR codes. That is the evidence for adding a redirect later.
Malformed links and manual handlers
When go_router receives the link from the platform, parsing is done for you. If you receive raw strings, for example from a push notification payload, parse them defensively. Uri.parse throws a FormatException on bad input. Uri.tryParse returns null instead.
import 'package:go_router/go_router.dart';
const _allowedHosts = {'example.com'};
void handleRawLink(GoRouter router, String raw) {
final uri = Uri.tryParse(raw);
if (uri == null || !_allowedHosts.contains(uri.host)) {
return; // malformed or not ours: do nothing
}
final target = uri.hasQuery ? '${uri.path}?${uri.query}' : uri.path;
router.go(target.isEmpty ? '/' : target);
}A link with your own host and an unknown path falls through to the router, which shows the fallback screen. A link with another host never reaches the router at all. That split is deliberate. The first is a mistake in your content, and the user should be told. The second is not for your app, so opening a screen would be wrong. The security chapter returns to host checks in more detail.
Which links can actually arrive
The fallback only sees links the operating system gives to your app. This catches people out when testing. The Android intent filter from the setup chapter declares android:pathPrefix="/products". A link to https://example.com/offers/summer does not match that filter, so Android opens it in the browser and your fallback never runs.
If you want the app to show its own not-found screen for every path on your domain, widen the filter. On Android that means a broader pathPrefix. On iOS it means a broader components entry in the association file. The trade-off is that the app then captures links that you might prefer to leave in the browser. Many teams keep the filters narrow and accept that unknown paths open the website.
Custom schemes behave differently. Any myapp://anything link opens the app, so the fallback sees all of them.
Testing the fallback
Use the commands from the testing chapter with deliberately bad links. These two exercise the route-level checks:
# Android: invalid ID, then a product that does not exist
adb shell am start -a android.intent.action.VIEW \
-d "https://example.com/products/abc" com.example.app
adb shell am start -a android.intent.action.VIEW \
-d "https://example.com/products/9999" com.example.app
# iOS simulator
xcrun simctl openurl booted "https://example.com/products/abc"Run each one twice: once with the app closed (cold start) and once with it running. Confirm that the fallback appears in both cases and that the "Go to home" button leaves the user on a working screen.
Exercise
A link to https://example.com/products/12abc opens your app, and the product screen crashes with a FormatException. Which line most likely caused it, and how do you fix it so the user sees the not-found screen instead?
Show answer
The route builder almost certainly calls int.parse on state.pathParameters['id'], which throws on '12abc'. Replace it with int.tryParse, check for null (and for a missing catalog entry), and return NotFoundScreen(requested: state.uri.toString()) in those cases.
Exercise
You add a not-found screen, but https://example.com/offers/summer still opens the browser on Android instead of your app. Why, and what are two ways to respond?
Show answer
The intent filter only declares pathPrefix /products, so Android never delivers /offers links to the app and errorBuilder cannot run. You can widen the intent filter's path (and the iOS components list) so the app receives more paths, or leave the filters narrow and accept that unknown paths open the website.