Sub topic 9
Links on Cold Start and While the App Is Running
This chapter assumes you can already map URLs to screens with go_router and have the platform side (intent filter or Associated Domains) working. It covers what changes depending on whether your app process was alive when the link arrived.
The two launch states
A link can reach your app in two situations:
- Cold start: the app process is not running. The operating system starts the app and passes the link as part of the launch.
- Warm start: the app is running, either in the foreground or suspended in the background. The operating system delivers the link to the existing process.
The platform delivers the link differently in each case. Flutter hides most of the difference when you use MaterialApp.router. The difference shows up in your own code at the moments when app state is not ready yet.
What Flutter does for you
Flutter's built-in deep linking is enabled by default in current stable releases. On older versions, you had to set flutter_deeplinking_enabled to true in the Android manifest and FlutterDeepLinkingEnabled in Info.plist. Check the documentation for your Flutter version.
With the default behavior, the platform code passes the link to the engine and the engine reports it to the framework as route information.
- Cold start: the link becomes the app's initial route.
MaterialApp.routerreads it through its route information provider before building the first screen. go_router then matches it as if the user had typed that URL. - Warm start: the framework receives a new route information event while the app runs. The router matches it and updates the screen.
Two consequences follow:
- A link that arrives at launch overrides
GoRouter'sinitialLocation. That value is only used when the platform supplies no link, which is a normal launch from the home screen icon. - A link that arrives while the app runs behaves like
context.go. It replaces the navigation stack with the stack that the matched route describes. It does not push on top of what the user was doing. If the user was in the middle of a form, that screen is gone.
Cold start: when the app is not ready for the link
On cold start the router parses the link almost immediately, often before your app has done any asynchronous startup work. That work usually includes:
- restoring a saved session from secure storage,
- loading remote configuration,
- opening a local database.
If your redirect function reads auth state that has not been loaded, it will make the wrong decision. The common bug is that a signed-in user opens a link on cold start, the router sees isLoggedIn == false because the token has not been read yet, and the user lands on the login page. The original link is lost.
The fix is a third state. Treat "not known yet" as different from "signed out". Send the link to a splash route and keep the original location in a query parameter. When startup finishes, notify the router and send the user on to the saved location.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class AuthState extends ChangeNotifier {
bool _ready = false;
bool _loggedIn = false;
bool get isReady => _ready;
bool get isLoggedIn => _loggedIn;
Future<void> restore() async {
// Stands in for reading a stored token.
await Future<void>.delayed(const Duration(milliseconds: 500));
_loggedIn = true;
_ready = true;
notifyListeners();
}
}
final auth = AuthState();
/// Accept only in-app paths, so a crafted `from` value cannot send the
/// user to another site or another host.
String _safeFrom(String? from) {
if (from == null || !from.startsWith('/') || from.startsWith('//')) {
return '/';
}
return from;
}
final router = GoRouter(
refreshListenable: auth,
routes: [
GoRoute(path: '/', builder: (c, s) => const _Page('Home')),
GoRoute(
path: '/products/:id',
builder: (c, s) => _Page('Product ${s.pathParameters['id']}'),
),
GoRoute(path: '/splash', builder: (c, s) => const _Page('Loading...')),
GoRoute(path: '/login', builder: (c, s) => const _Page('Login')),
],
redirect: (context, state) {
final loc = state.matchedLocation;
final here = Uri.encodeComponent(state.uri.toString());
if (!auth.isReady) {
return loc == '/splash' ? null : '/splash?from=$here';
}
if (loc == '/splash') {
return _safeFrom(state.uri.queryParameters['from']);
}
if (!auth.isLoggedIn && loc != '/login') {
return '/login?from=$here';
}
return null;
},
);
class _Page extends StatelessWidget {
const _Page(this.title);
final String title;
@override
Widget build(BuildContext context) =>
Scaffold(appBar: AppBar(title: Text(title)));
}
void main() {
auth.restore();
runApp(MaterialApp.router(routerConfig: router));
}Trace a cold start with https://example.com/products/42:
- The router matches the link and runs
redirect.auth.isReadyis false, so it returns/splash?from=.... - The splash screen shows while
restore()runs. notifyListeners()triggersrefreshListenable, and the router runsredirectagain.- The location is
/splash, soredirectreturns the decodedfromvalue,/products/42. If the user turned out to be signed out, the next pass sends them to/login?from=...instead.
The _safeFrom helper matters. A from value is input from a link, so treat it as untrusted. The security chapter returns to this.
Warm start: the link arrives mid-session
While the app is running, the same router and the same redirect apply. Auth state is already loaded, so the splash path is skipped. Watch for these issues:
- Lost context. Because the link replaces the stack, a user editing a draft loses it. If that matters, keep draft state outside the widget tree, for example in a provider or repository. You can also decide that certain links should use
context.pushinstead. To do that, you would handle links yourself (see below). - Same route, new parameters. If the user is on
/products/42and a link opens/products/43, the route builder runs again with a newstate. AStatefulWidgetthat reads the id only ininitStatewill keep showing product 42. Read the id from the widget's constructor and implementdidUpdateWidget, or give the page a key that includes the id. - Backgrounded apps. The OS may have killed a suspended app without telling you. The link then arrives as a cold start, so you cannot assume that "I was open recently" means warm.
Handling links yourself with app_links
If you use app_links instead of relying on Flutter's built-in handling, you take on both states. The package exposes a stream of incoming links. In recent versions, the stream also emits the link that launched the app, so one subscription covers cold and warm starts. Older versions needed a separate call for the initial link. Check the version you depend on.
Subscribe once, as early as you can, and keep a reference to the subscription. Remember that the stream may deliver the cold-start link before your router is ready, so route it through the same auth-aware redirect.
Do not enable both mechanisms at once. If Flutter's default deep linking is still on and you also call router.go from an app_links listener, each link is handled twice. Turn the default off with flutter_deeplinking_enabled set to false in the Android manifest and FlutterDeepLinkingEnabled set to false in Info.plist.
Testing both states
Test each state separately, because most launch-state bugs appear in only one of them. Stop the app first to force a cold start, and leave it running for a warm start.
# Cold start on Android
adb shell am force-stop com.example.app
adb shell am start -a android.intent.action.VIEW \
-d "https://example.com/products/42" com.example.app
# Warm start on Android: launch the app normally first, then run only this
adb shell am start -a android.intent.action.VIEW \
-d "https://example.com/products/43" com.example.app
# Cold start on the iOS simulator
xcrun simctl terminate booted com.example.app
xcrun simctl openurl booted "https://example.com/products/42"For each state, check these cases: signed in, signed out, and a link to a protected route.
Common errors
| Symptom | Likely cause |
|---|---|
| Signed-in users land on the login page after a cold-start link | `redirect` ran before the session was restored. Add a "not ready" state and a splash route. |
| Link works warm but opens home on cold start | The router or redirect drops the original location, or `initialLocation` logic overrides it. |
| Each link triggers two navigations | Built-in deep linking and an `app_links` listener are both active. |
| Link to another product does nothing visible | The page reads the id only in `initState`. |
| Link opens in the browser instead of the app | Not a launch-state issue. Recheck domain verification. |
Exercise
A signed-in user taps https://example.com/products/42 while your app is fully closed. The app opens on the login screen. Name the cause and the fix.
Show answer
On cold start the router parses the link before the stored session is restored, so the redirect sees the user as signed out. Add an "auth ready" flag, redirect to a splash route with the original URL in a from query parameter while it is false, call notifyListeners() when restore finishes, and then redirect to the validated from location (or to login if the user is signed out).
Exercise
Why can a link opened while the app is running discard a half-filled form, and how can you reduce that risk?
Show answer
The platform reports the link as new route information, and go_router handles it like context.go, which replaces the navigation stack. Keep draft data in state that outlives the widget, such as a repository or provider, or handle links yourself and use push for links where preserving the current screen matters.