Sub topic 13
Handling links manually with app_links
By default, go_router and MaterialApp.router receive platform links from Flutter and route them for you. Sometimes that isn't enough. You may need to inspect or reject a link before routing, run analytics on every link, or route into an app that doesn't use go_router. The app_links package gives you the raw incoming Uri so you can decide what to do with it.
This chapter assumes you have already set up Android App Links and iOS Universal Links, and that you have a working go_router configuration with a /products/:id route. It also assumes you know how to read a Uri in Dart.
When manual handling is worth it
Most apps should not handle links manually. Use the built-in routing unless one of these applies.
| Situation | Built-in routing | app_links |
|---|---|---|
| Map a URL to a screen | Yes | Not needed |
| Redirect through login | Yes, with `redirect` | Not needed |
| Log every link before routing | No hook | Yes |
| Reject links by host or path before the router sees them | Only through route `redirect` logic | Yes |
| Rewrite a legacy URL format into new paths | Possible with `redirect` | Yes, in one place |
| Navigation with the plain `Navigator` | No | Yes |
If you only need to block or rewrite paths, a top-level redirect in go_router is usually simpler. Reach for app_links when you need the link as an event, separate from navigation.
Adding the package
Add the dependency next to go_router.
flutter pub add app_links go_routerapp_links needs no extra native setup beyond the intent filter and Associated Domains entitlement you already configured. It reads the same platform links that Flutter would otherwise pass to the router.
Turn off Flutter's built-in handling
Flutter forwards platform links to the router on its own. If you also listen with app_links, the same link can navigate twice: once through Flutter and once through your handler. Disable the built-in path.
On Android, add this inside the <activity> element of AndroidManifest.xml:
<meta-data
android:name="flutter_deeplinking_enabled"
android:value="false" />On iOS, add this to Info.plist:
<key>FlutterDeepLinkingEnabled</key>
<false/>After this change, nothing reaches your router unless your code sends it there.
How the two sources fit together
app_links exposes two things. getInitialLink() returns the link that launched the app, or null if the user opened the app normally. uriLinkStream emits each link that arrives while the app is already running.
Mermaid diagrams must use the diagram fence, so here is the flow in the required form:
Both sources feed one function. That is the main benefit of manual handling: a single place to validate, log, and route.
A complete link handler
The class below handles both sources, validates each link, and sends only a path and query to the router.
import 'dart:async';
import 'package:app_links/app_links.dart';
import 'package:flutter/foundation.dart';
import 'package:go_router/go_router.dart';
class LinkHandler {
LinkHandler(this._router, {AppLinks? appLinks})
: _appLinks = appLinks ?? AppLinks();
final GoRouter _router;
final AppLinks _appLinks;
StreamSubscription<Uri>? _subscription;
Uri? _initialLink;
static const _allowedHosts = {'example.com'};
static const _allowedPrefixes = ['/products'];
Future<void> start() async {
// Cold start: the link that launched the app, if any.
_initialLink = await _appLinks.getInitialLink();
if (_initialLink != null) {
_handle(_initialLink!);
}
// Warm start: links that arrive while the app runs.
_subscription = _appLinks.uriLinkStream.listen(
(uri) {
// Some versions also replay the initial link on the stream.
// Skip that one replay so the screen is not pushed twice.
if (_initialLink != null && uri == _initialLink) {
_initialLink = null;
return;
}
_handle(uri);
},
onError: (Object error) => debugPrint('Link stream error: $error'),
);
}
void _handle(Uri uri) {
if (!_isAllowed(uri)) {
debugPrint('Ignored link: $uri');
return;
}
final target = uri.hasQuery ? '${uri.path}?${uri.query}' : uri.path;
_router.go(target);
}
bool _isAllowed(Uri uri) {
if (uri.scheme != 'https') return false;
if (!_allowedHosts.contains(uri.host)) return false;
return _allowedPrefixes.any(uri.path.startsWith);
}
Future<void> dispose() async {
await _subscription?.cancel();
}
}Start the handler once, from a widget that lives for the whole app session.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class MyApp extends StatefulWidget {
const MyApp({super.key, required this.router});
final GoRouter router;
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late final LinkHandler _links = LinkHandler(widget.router);
@override
void initState() {
super.initState();
_links.start();
}
@override
void dispose() {
_links.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp.router(routerConfig: widget.router);
}
}Several details in this code matter.
- Only path and query go to the router. The router should never see the scheme or host. Passing a full URL to
router.gocan produce a location the router doesn't recognize. - The allowlist is explicit. A prefix such as
/productsblocks paths you did not plan for. Note thatstartsWith('/products')also matches/products-admin. If that matters, compare against/productsexactly or against/products/. - Rejected links are logged and dropped. The user stays where they are. If you prefer a visible fallback, send them to your not-found route instead.
disposecancels the subscription. A leaked subscription keeps delivering links to a router that may no longer exist, which matters in tests and when hot restarting.
Cold start and timing
On a cold start, getInitialLink() returns before your first screen finishes building. router.go is safe at that point because go_router stores the new location and applies it when the router is attached. If you use Navigator.push instead, wait for the first frame, for example with WidgetsBinding.instance.addPostFrameCallback. A push before the navigator exists throws.
Redirects still apply. If a signed-out user opens /products/42, your redirect from the earlier chapter sends them to /login?from=.... The manual handler does not need to know about authentication.
Common errors
- Screens open twice. Built-in handling is still on. Set
flutter_deeplinking_enabledandFlutterDeepLinkingEnabledto false, then do a full rebuild. Manifest and plist changes do not apply through hot reload. - Nothing happens on a cold start. You subscribed to the stream but never called
getInitialLink(). A link that launched the app arrived before the subscription existed. - The same link is ignored the second time. You deduplicated by comparing against the last handled link forever. Deduplicate only the one replayed initial link, as the code above does.
- Custom scheme links route to the wrong place. For
myapp://products/42, Dart parsesproductsas the host and/42as the path. Normalize those links before routing, or use verified HTTPS links. - Links work in a browser test but not from the command line. Check that the
adborsimctlcommand uses the same host as your allowlist.
Testing the handler
Use the commands from the testing chapter to send links to the app. Try three cases: launch the app with a link while it is closed, send a link while it is open, and send a link with a host you did not allow. The first should show the product screen. The second should navigate without restarting. The third should log Ignored link and change nothing.
adb shell am start -a android.intent.action.VIEW \
-d "https://example.com/products/42" com.example.app
xcrun simctl openurl booted "https://example.com/products/42"Exercise
You enabled app_links and your product screen now opens twice for each link. What are the two settings you should change, and why does a hot reload not fix the problem?
Show answer
Set the Android meta-data flutter_deeplinking_enabled to false in AndroidManifest.xml, and set FlutterDeepLinkingEnabled to false in Info.plist on iOS. Flutter's built-in handling forwards each link to the router, and your app_links handler forwards it a second time. These are native configuration files, so changes to them need a full rebuild. Hot reload only updates Dart code.
Exercise
Why does the handler call getInitialLink() in addition to listening on uriLinkStream?
Show answer
A link that launches a closed app arrives before your code subscribes to the stream, so the stream never delivers it. getInitialLink() returns that launch link. The stream covers links that arrive after the app is running.