Sub topic 15
Deep linking and URLs
This chapter assumes you can define routes with go_router, read path parameters, and write a redirect callback, as covered in the earlier chapters. You also need a basic idea of what an Android manifest and an iOS entitlement are.
What a deep link is
A deep link is a URL that opens your app on a specific screen instead of on the home screen. Examples are https://example.com/products/42 in a chat message, a push notification payload, or a web address typed into a browser.
The idea is that every screen worth sharing has an address. Declarative routing makes this practical because the route tree already maps URL paths to screens. The remaining work is getting the operating system to hand the URL to your app and making sure your router handles it safely.
There are three kinds of link:
| Kind | Example | Opens | Needs server setup |
|---|---|---|---|
| Custom scheme | `myapp://products/42` | Your app only | No |
| Android App Link | `https://example.com/products/42` | Your app, with no chooser | Yes, `assetlinks.json` |
| iOS Universal Link | `https://example.com/products/42` | Your app, with no prompt | Yes, `apple-app-site-association` |
Custom schemes are easy to set up, but any app can claim the same scheme, and a user without your app sees an error. Verified HTTPS links fall back to your website when the app is missing. Prefer them for anything public.
How a URL becomes a screen
The operating system delivers the URL to the Flutter engine. The engine passes it to the router as a new route information object. go_router matches the path against the route tree, runs redirects, and builds the pages.
The last step matters for navigation quality. When /products/42 is nested under the / route, go_router builds a stack of HomeScreen and then ProductScreen. The back button has somewhere to go. If you declare /products/:id as a top-level route instead, the user lands on a stack of one page, and back closes the app.
A router that handles incoming links
This example defines a home screen, a product screen, a search screen with a query parameter, and a not-found screen. It runs once go_router is in pubspec.yaml and flutter_web_plugins is added as an SDK dependency.
import 'package:flutter/material.dart';
import 'package:flutter_web_plugins/url_strategy.dart';
import 'package:go_router/go_router.dart';
void main() {
usePathUrlStrategy();
runApp(const MyApp());
}
final GoRouter _router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'products/:id',
redirect: (context, state) {
final id = int.tryParse(state.pathParameters['id'] ?? '');
return id == null ? '/' : null;
},
builder: (context, state) {
final id = int.parse(state.pathParameters['id']!);
return ProductScreen(id: id);
},
),
GoRoute(
path: 'search',
builder: (context, state) {
final query = state.uri.queryParameters['q'] ?? '';
return SearchScreen(query: query);
},
),
],
),
],
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 _Stub extends StatelessWidget {
const _Stub({required this.title, this.children = const []});
final String title;
final List<Widget> children;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: children,
),
),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return _Stub(
title: 'Home',
children: [
ElevatedButton(
onPressed: () => context.go('/products/42'),
child: const Text('Product 42'),
),
ElevatedButton(
onPressed: () => context.go('/search?q=shoes'),
child: const Text('Search shoes'),
),
],
);
}
}
class ProductScreen extends StatelessWidget {
const ProductScreen({super.key, required this.id});
final int id;
@override
Widget build(BuildContext context) =>
_Stub(title: 'Product', children: [Text('Product id: $id')]);
}
class SearchScreen extends StatelessWidget {
const SearchScreen({super.key, required this.query});
final String query;
@override
Widget build(BuildContext context) =>
_Stub(title: 'Search', children: [Text('Query: $query')]);
}
class NotFoundScreen extends StatelessWidget {
const NotFoundScreen({super.key, required this.uri});
final Uri uri;
@override
Widget build(BuildContext context) =>
_Stub(title: 'Not found', children: [Text('No page for $uri')]);
}Three details are worth noting:
- The
redirecton the product route turns/products/abcinto a redirect to home instead of a crash fromint.parse. Treat every URL as untrusted input, because anyone can craft one. state.uri.queryParametersgives you decoded query values./search?q=red%20shoesarrives asred shoes.errorBuilderruns when no route matches, such as/nonsense. Without a useful page here, a stale link shows a generic error.
Clean URLs on the web
On Flutter web the default URL strategy puts the route after a hash, as in example.com/#/products/42. The call usePathUrlStrategy() switches to example.com/products/42. It must run before runApp.
Your web server must then return index.html for any path, or reloading /products/42 produces a 404 from the server. Most static hosts have a "single-page app" or rewrite setting for this.
Android setup
Android needs an intent filter on the main activity in android/app/src/main/AndroidManifest.xml. The autoVerify attribute asks Android to check your domain ownership.
<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>Then host https://example.com/.well-known/assetlinks.json with your package name and the SHA-256 fingerprint of your signing certificate. Recent Flutter versions handle incoming links through the router by default. Older ones need a flutter_deeplinking_enabled metadata entry in the manifest, so check the release notes for your version.
iOS setup
In Xcode, add the Associated Domains capability with the entry applinks:example.com. Then serve an apple-app-site-association file, with no file extension, from https://example.com/.well-known/. It lists your team ID plus bundle ID and the paths your app handles. For a custom scheme, add a URL type in Info.plist instead.
Testing links from the command line
You do not need to send yourself a message every time. Both platforms can open a URL on a running emulator or simulator.
# Android emulator or device
adb shell am start -a android.intent.action.VIEW \
-d "https://example.com/products/42" com.example.myapp
# iOS simulator
xcrun simctl openurl booted "https://example.com/products/42"Test with the app closed and with it already open. Cold start and warm start take different code paths, and bugs often appear in only one.
Deep links and authentication
A link opened while the user is logged out passes through your redirect guard. If the guard sends everyone to /login, the original destination is lost. Carry it along in a query parameter.
redirect: (context, state) {
final loggedIn = authNotifier.isLoggedIn;
final atLogin = state.matchedLocation == '/login';
if (!loggedIn && !atLogin) {
final from = Uri.encodeComponent(state.uri.toString());
return '/login?from=$from';
}
if (loggedIn && atLogin) {
final from = state.uri.queryParameters['from'];
final safe = from != null && from.startsWith('/') && !from.startsWith('//');
return safe ? from : '/';
}
return null;
},Here authNotifier is your own ChangeNotifier, passed to refreshListenable as in the redirects chapter. state.uri keeps the full original location, including its query string, while matchedLocation has only the path. The safe check stops an attacker from using from=https://evil.example to bounce a logged-in user to another site.
Common mistakes
- Declaring a detail route at the top level, so a deep link gives a one-page stack with no way back.
- Using
int.parseon a path parameter without handling bad input. - Forgetting the server rewrite on web, so reloads show a 404.
- Verifying the Android link with a debug signing key, then publishing with a different one. The fingerprint in
assetlinks.jsonmust match the key that signed the installed build. - Using
context.pushfor links and expecting the address bar to update. On web, imperative pushes may not change the URL unless you account for that. Usecontext.gowhen the URL should reflect the destination.
Exercise
Your app has a top-level route /products/:id, and a user opens https://example.com/products/42 from an email. They tap the system back button and the app closes instead of showing the home screen. What is the cause, and how do you fix it?
Show answer
A top-level route builds a stack with only the product page, so there is nothing below it to return to. Nest products/:id as a child of the / route, using the relative path products/:id. go_router then builds a stack of home plus product for the same URL, and back returns to home.
Exercise
A deep link https://example.com/search?q=red%20shoes opens SearchScreen. Where do you read the search text, and what value do you get?
Show answer
Read state.uri.queryParameters['q'] in the route builder. The value is already decoded, so it is red shoes. Use ?? '' because the parameter can be missing.