Sub topic 15
Deep links and web URLs
This chapter assumes you can define a GoRouter with nested routes, path parameters, and a top-level redirect, as covered in earlier chapters. Here you will see how an address from outside the app, such as a browser URL or a tapped link, becomes a screen stack.
What a deep link is
A deep link is a URL that opens a specific screen instead of the app's front page. https://example.com/books/42 is one. On the web, the browser's address bar is the deep link. On Android and iOS, the operating system hands the URL to your app when the user taps it in a message or email.
With go_router, you write no extra parsing code for this. The incoming URL is treated like a call to context.go with the same location string. The router matches it against your route table, runs redirects, and builds the pages.
Nested routes decide the back stack
The shape of your route tree controls what the user sees when they press Back after arriving by deep link. Consider this tree:
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const Text('Home'),
routes: <RouteBase>[
GoRoute(
path: 'books/:id',
builder: (context, state) =>
Text('Book ${state.pathParameters['id']}'),
),
],
),
],
);Opening /books/42 builds two pages: Home at the bottom and the book on top. Back returns to Home. If you had declared /books/:id as a top-level sibling of /, the stack would hold only the book page. Back would then close the app or leave the browser tab's history, because nothing sits underneath.
Choose the nesting so that a deep-linked screen has a sensible parent. This also matters on the web, where the browser's Back button follows the history, not your route tree.
Web: choosing a URL strategy
Flutter web uses hash URLs by default, such as https://example.com/#/books/42. They work on any static host. Path URLs, https://example.com/books/42, look cleaner and are what most deep links use. Enable them before runApp:
import 'package:flutter/material.dart';
import 'package:flutter_web_plugins/url_strategy.dart';
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const Scaffold(body: Text('Home')),
),
GoRoute(
path: '/books/:id',
builder: (context, state) =>
Scaffold(body: Text('Book ${state.pathParameters['id']}')),
),
],
);
void main() {
usePathUrlStrategy();
runApp(MaterialApp.router(routerConfig: router));
}flutter_web_plugins ships with the Flutter SDK. Add it to pubspec.yaml as an SDK dependency:
dependencies:
flutter_web_plugins:
sdk: flutterPath URLs need server support. When a user reloads /books/42, the browser asks your server for that path. The server must return index.html for every path that is not a real file, and Flutter then reads the location and routes it. Without this rewrite you get a 404 on reload, even though in-app navigation worked.
Pushed pages and the address bar
By default, the address bar updates for go but not for push. A page added with context.push does not change the URL. If you want the URL to follow pushed pages, set this before creating the router:
GoRouter.optionURLReflectsImperativeAPIs = true;Do this only if you want a shareable URL for pushed pages. Remember that anyone who opens that URL gets the location through the normal route-matching path, not through your push.
Android and iOS setup
Routing code is the same on mobile, but the operating system must first send the URL to your app. Recent Flutter versions enable the engine's deep-link handling by default. Older projects may need a flutter_deeplinking_enabled meta-data entry set to true inside the <activity> element. Check the Flutter documentation for your SDK version.
On Android, declare an intent filter on the main activity in android/app/src/main/AndroidManifest.xml:
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="example.com" />
</intent-filter>With autoVerify, Android checks a /.well-known/assetlinks.json file on your domain. Verified links open straight in the app without a chooser dialog.
On iOS, Universal Links need two parts. In Xcode, add the Associated Domains capability with an entry like applinks:example.com. On your server, publish an apple-app-site-association file at /.well-known/. A custom scheme such as myapp://books/42 needs no server files, but any app can claim the same scheme, and a link on a web page cannot fall back to a site when the app is missing. Prefer HTTPS links for anything users share.
Testing from the command line
You do not need to send real messages to test. Use these commands against an Android device or an iOS simulator:
adb shell am start -a android.intent.action.VIEW \
-d "https://example.com/books/42" com.example.myapp
xcrun simctl openurl booted "https://example.com/books/42"Deep links meet redirects
A deep link can arrive while the user is signed out. Your redirect sends them to /login, and after sign-in they land on Home, so the original target is lost. Keep it in a query parameter:
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
bool loggedIn = false;
final GoRouter router = GoRouter(
redirect: (context, state) {
final bool atLogin = state.matchedLocation == '/login';
if (!loggedIn && !atLogin) {
final String from = Uri.encodeQueryComponent(state.uri.toString());
return '/login?from=$from';
}
if (loggedIn && atLogin) {
return state.uri.queryParameters['from'] ?? '/';
}
return null;
},
routes: <RouteBase>[
GoRoute(path: '/', builder: (context, state) => const Text('Home')),
GoRoute(path: '/login', builder: (context, state) => const Text('Login')),
GoRoute(
path: '/books/:id',
builder: (context, state) =>
Text('Book ${state.pathParameters['id']}'),
),
],
);state.matchedLocation has no query string, so it suits path comparisons. state.uri is the full URI with its query, so it suits saving the target. The router decodes query parameters, so queryParameters['from'] returns the original string.
Edge cases to check
- Unknown paths. A deep link that matches no route triggers
errorBuilder. Old links from earlier app versions land here, so give users a way back to Home. - Trailing slashes.
/books/42/is matched like/books/42, but verify this against your own route table. - Bad parameters.
/books/abcmatchesbooks/:ideven if ids are numeric. Parse withint.tryParsein the builder and show a not-found view when parsing fails. - Cold start and warm start. The same URL may arrive while the app is closed or already running. Both go through the router, but a cold start also runs
initialLocationlogic. A deep link overridesinitialLocation. - Encoding. Path segments with spaces or slashes must be percent-encoded.
go_routerdecodes path parameters for you. When you build locations by hand, useUri.encodeComponent.
Summary table
| Concern | Where it is handled |
|---|---|
| Parsing the URL into a route | `GoRouter`, using your route table |
| Back stack after arrival | Route nesting |
| Clean web URLs | `usePathUrlStrategy()` and server fallback |
| Opening the app from a link | Android intent filter, iOS associated domains |
| Signed-out visitors | `redirect` plus a saved `from` location |
| Unmatched URLs | `errorBuilder` |
Exercise
Your app has a top-level route /books/:id and a route /. A user opens https://example.com/books/42 from an email and presses Back. The app closes. What change to the route tree gives them Home underneath, and how does the stack differ?
Show answer
Nest the book route under the home route by declaring GoRoute(path: 'books/:id', ...) inside the routes list of the / route. The location is still /books/42, but the router now builds two pages, Home and the book page on top. Back pops to Home instead of leaving the app.
Exercise
After deploying a Flutter web app with path URLs, navigating inside the app works, but reloading /books/42 returns a 404 from the server. What is the cause?
Show answer
The server looks for a file at /books/42 and finds none. It must be configured to return index.html for any path that is not a real file. Flutter then reads the location from the URL and go_router shows the matching screen.