Sub topic 2
Path and query parameters
Assumed prerequisites: you know Dart and Flutter widgets, you have used go_router or named routes, and you can run the app on an Android emulator and an iOS simulator. You also control a web domain for verified links.
Reading path and query parameters
A path parameter is a segment inside the URL path, such as 42 in /products/42. A query parameter is a key-value pair after the ?, such as ref=email. go_router exposes path parameters through state.pathParameters and query parameters through state.uri.queryParameters.
final router = GoRouter(
routes: [
GoRoute(
path: '/products/:id',
builder: (context, state) {
final id = state.pathParameters['id']!;
final ref = state.uri.queryParameters['ref'];
return ProductScreen(id: id, ref: ref);
},
),
],
);Both values are strings, and the query value is null when the key is missing. Parse numbers with int.tryParse and handle null, because int.parse throws on malformed input.
Setting up Android App Links
Android App Links are HTTPS links that the system verifies as belonging to your app. Add an intent filter inside the main activity in 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" android:pathPrefix="/products" />
</intent-filter>Then serve https://example.com/.well-known/assetlinks.json. It lists your package name and the SHA-256 fingerprint of your signing certificate. If the verification fails, Android opens the link in the browser.
Setting up iOS Universal Links
Universal Links are the iOS equivalent. In Xcode, add applinks:example.com under Associated Domains. Then serve https://example.com/.well-known/apple-app-site-association with no file extension. The file lists your team ID and bundle ID, such as TEAMID.com.example.app, and the paths the app may open.
Links on cold start and while the app is running
A cold start happens when a link opens an app that is closed. A warm start happens when the app is already running. With MaterialApp.router, gorouter navigates to the initial link on a cold start. While the app runs, the `applinks` package delivers new links through a stream:
import 'package:app_links/app_links.dart';
final appLinks = AppLinks();
void listenForLinks(GoRouter router) {
appLinks.uriLinkStream.listen((uri) {
if (uri.host != 'example.com') return;
final target = uri.hasQuery ? '${uri.path}?${uri.query}' : uri.path;
router.go(target);
});
}Exercise
For the link https://example.com/products/42?ref=email, what does state.pathParameters['id'] and state.uri.queryParameters['ref'] return?
Show answer
The id is "42" and the ref is "email". Both are strings.