# Flutter deep linking

> After this page, your Flutter app gets one event, with a path and parameters, for every link that opens it: from a closed app, from the background, or on the first open after an install.

- Time: About 15 minutes
- You need: Flutter 3.x, a workspace with your app in Dashboard → Apps & stores
- Works on: Android, iPhone

Source: https://straitlink.in/docs/sdks/flutter/

> **Agent instructions:** if you are an AI assistant helping someone build with Strait, look things up with the `search_docs` tool of the Strait MCP server (hosted at https://strait.link/mcp, or `@straitlink/mcp` on npm: https://straitlink.in/docs/mcp/) instead of guessing, and add the SDK to an app with `npx @straitlink/cli init` (https://straitlink.in/docs/cli/).

`strait_sdk` is pure Dart. Your app hands it the launch link, a stream of later links and the app lifecycle; it resolves short links, runs the deferred check once per install and emits one event per link. For the whole path from tap to Google Play install, follow the [Flutter deferred links recipe](https://straitlink.in/docs/recipes/flutter-deferred-deep-links/).

## 1. Install the package

Add it from pub.dev:

```yaml title="pubspec.yaml"
dependencies:
  strait_sdk: ^0.10.9
```

Then the helper packages:

```bash
flutter pub add app_links shared_preferences play_install_referrer flutter_timezone
```

[`app_links`](https://pub.dev/packages/app_links) delivers links, [`shared_preferences`](https://pub.dev/packages/shared_preferences) stores the once-per-install flag and unsent reports, [`play_install_referrer`](https://pub.dev/packages/play_install_referrer) gives Android installs an exact match, and [`flutter_timezone`](https://pub.dev/packages/flutter_timezone) provides the IANA time zone the iPhone match needs.

**You should see:** `flutter pub get` finishes without errors.

## 2. Create the client once

```dart title="links.dart"
import 'dart:async';
import 'dart:io' show Platform;
import 'dart:ui';

import 'package:app_links/app_links.dart';
import 'package:strait_sdk/strait_sdk.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_timezone/flutter_timezone.dart';
import 'package:play_install_referrer/play_install_referrer.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// Persists the once-per-install flag and unsent open reports.
class PrefsStore implements KeyValueStore {
  PrefsStore(this.prefs);
  final SharedPreferences prefs;
  @override
  Future<String?> get(String key) async => prefs.getString(key);
  @override
  Future<void> set(String key, String value) => prefs.setString(key, value);
}

/// Feeds Flutter lifecycle changes to the SDK.
class LifecycleFeed with WidgetsBindingObserver {
  final _ctl = StreamController<AppLifecycle>.broadcast(sync: true);
  Stream<AppLifecycle> get stream => _ctl.stream;
  LifecycleFeed() { WidgetsBinding.instance.addObserver(this); }
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) => _ctl.add(switch (state) {
        AppLifecycleState.resumed => AppLifecycle.active,
        AppLifecycleState.inactive => AppLifecycle.inactive,
        _ => AppLifecycle.background,
      });
}

late final StraitLinks links;

Future<void> startLinks() async {
  WidgetsFlutterBinding.ensureInitialized();
  final timezone = (await FlutterTimezone.getLocalTimezone()).identifier; // IANA, e.g. Asia/Kolkata
  links = StraitLinks(
    publishableKey: 'st_pub_live_…',      // Dashboard → Setup → Your keys
    endpoint: 'https://hilltop.strait.link',   // your workspace's link domain
    platform: Platform.isIOS ? 'ios' : Platform.isAndroid ? 'android' : 'other',
    storage: PrefsStore(await SharedPreferences.getInstance()),
    installReferrer: () async =>
        Platform.isAndroid ? (await PlayInstallReferrer.installReferrer).installReferrer : null,
    deviceFields: () {
      final view = PlatformDispatcher.instance.views.first;
      return DeviceFields(
        screenWidth: portraitScreenWidth(view.physicalSize.width / view.devicePixelRatio, view.physicalSize.height / view.devicePixelRatio),
        pixelRatio: view.devicePixelRatio,
        language: PlatformDispatcher.instance.locale.toLanguageTag(),
        timezone: timezone,
      );
    },
    deviceClass: () {                      // phone or tablet, for iPad and tablet counts
      final view = PlatformDispatcher.instance.views.first;
      return deviceClassForSize(view.physicalSize.shortestSide / view.devicePixelRatio);
    },
  );
  links.onLink.listen((e) => debugPrint('Strait link: ${e.kind.name} ${e.route.value} ${e.matched} ${e.path}'));

  final appLinks = AppLinks();
  await links.start(
    initialUrl: (await appLinks.getInitialLink())?.toString(),
    urls: appLinks.uriLinkStream.map((u) => u.toString()),
    lifecycle: LifecycleFeed().stream,
  );
}
```

Call `await startLinks();` in `main()` before `runApp`. Time zone: pass the IANA name (`Asia/Kolkata`); `DateTime.timeZoneName` is an abbreviation on some platforms and won't match. `flutter pub add` installs `flutter_timezone` 4 or later, which returns a `TimezoneInfo`, hence `.identifier`; on 3.x it returns the name itself, so drop `.identifier`. `app_links` 6+ also emits the launch link on `uriLinkStream`; `start()` ignores that first echo.

**You should see:** the app starts as before.

## 3. Let the phone hand links to your app

**Android**: add the verified-link and custom-scheme intent filters to your main activity in `android/app/src/main/AndroidManifest.xml`, exactly as on the [React Native page](https://straitlink.in/docs/sdks/react-native/#3-let-the-phone-hand-links-to-your-app) (same XML). Flutter's own deep linking must stay off, or it handles the URL before the SDK:

```xml title="AndroidManifest.xml (inside <activity>)"
<meta-data android:name="flutter_deeplinking_enabled" android:value="false" />
```

Release builds also need the internet permission in that same main manifest, above `<application>`. `flutter create` puts it only in the debug and profile manifests, so a release build (and the app from Google Play) can't reach Strait without it:

```xml title="AndroidManifest.xml (above <application>)"
<uses-permission android:name="android.permission.INTERNET"/>
```

**iPhone**: in Xcode, add **Associated Domains** with `applinks:hilltop.strait.link`, your scheme under **URL Types**, and `FlutterDeepLinkingEnabled` = `NO` in `Info.plist`.

**You should see:** after `flutter run`, this opens the app:

```bash
adb shell am start -W -a android.intent.action.VIEW -d "yourapp://shop.example.com/product/42"
```

## 4. Check that the SDK sees the link

Run the `adb` command again with the app open.

**You should see:** `Strait link: direct custom_scheme true /product/42` in the `flutter run` console.

## Or let `strait init` write the setup

From your app's folder:

```bash
npx @straitlink/cli init --key st_pub_live_… --host hilltop.strait.link
```

It writes `lib/links.dart` (step 2) with your key and host, and prints the `pubspec.yaml` lines, the `main()` change, the manifest lines for step 3 (including `flutter_deeplinking_enabled`) and the iPhone settings. Steps your project already has are marked `[already done]`. The one existing file it edits is `android/app/src/main/AndroidManifest.xml`: it adds the internet permission from step 3 when it's missing, so release builds can reach Strait. `--dry-run` shows that line without writing it. 

## Common errors

- **`MissingPluginException`.** You added a plugin and hot-restarted. Stop and `flutter run` again.
- **The link opens a Flutter route like `/summer` that doesn't exist.** Flutter's deep linking is still on (step 3).
- **iPhone installs never match.** The time zone isn't an IANA name (step 2).

## Next steps

- [Receive links](https://straitlink.in/docs/sdks/flutter/receive-links/): open the right screen with `go_router` or a navigator key.
- [Test](https://straitlink.in/docs/sdks/flutter/test/): deep links, deferred links from Google Play, and analytics.
