# Install on Flutter

> Add the Herald Flutter plugin to a Flutter app. It wraps the native iOS and Android SDKs, installs from git, and covers identity, events, push, content cards and in-app messages.

`herald_flutter` is a Flutter plugin that wraps the native Herald SDKs: `herald-ios` on iOS and `herald-android` on Android, version 0.6.0. It is a thin layer, not a separate SDK, so behavior, limits and threading are the native SDKs' ([iOS API](/docs/reference/ios-api), [Android API](/docs/reference/android-api)). Calls return once the native SDK has queued them; the few that can throw are listed under [Errors](#errors). It isn't on pub.dev yet; install it from git.

:::prereq
- Flutter 3.50 or later (Dart 3.14), with Swift Package Manager turned on for iOS: `flutter config --enable-swift-package-manager`. The plugin has no CocoaPods spec.
- iOS 16 or later (set the Runner's deployment target to 16.0) and Android 8.0, API level 26 (`minSdk = 26`).
- A Herald app key and endpoint, from the connection's **Mobile SDK** card.
- For push: an APNs key on the connection for iOS, and Firebase set up in the Android app (`google-services.json`). See [iOS push setup](/docs/push-notifications/ios-setup) and [Android push setup](/docs/push-notifications/android-setup).
:::

## 1. Add the plugin

```yaml
# pubspec.yaml
dependencies:
  herald_flutter:
    git:
      url: https://github.com/ender1311/herald.git
      path: sdks/flutter
```

On Android, add JitPack to `android/build.gradle.kts`, where the native modules come from:

```kotlin
allprojects {
    repositories {
        google()
        mavenCentral()
        maven { url = uri("https://jitpack.io") }
    }
}
```

and make `MainActivity` extend `FlutterFragmentActivity` instead of `FlutterActivity`. The native in-app message views need a `ComponentActivity`.

## 2. Configure the SDK

Call `Herald.configure` once in `main()`. It also installs the native default in-app message views.

```dart
import 'package:flutter/widgets.dart';
import 'package:herald_flutter/herald_flutter.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  Herald.configure(
    appKey: 'YOUR_APP_KEY',
    endpoint: 'https://YOUR_HERALD_HOST',
    options: const HeraldOptions(logLevel: HeraldLogLevel.debug),
  );
  runApp(const MyApp());
}
```

On Android, also start the SDK from your `Application` class. Dart code runs after the first activity has started, so a Dart-only start misses that first app open: the push tap that launched the app is lost (no open is logged and its deep link doesn't open), and the session and in-app messages wait until the app next comes to the foreground.

**On Android the native call wins.** Once it has run, the Dart `Herald.configure` is ignored there, its options included, with one warning in the log. Pass the same options to the Kotlin call that you pass in Dart, or the two platforms behave differently (for example, Android would keep sending standard device data while iOS sends minimal):

```kotlin
import com.herald.sdk.DeviceDataCollection
import com.herald.sdk.Herald
import com.herald.sdk.HeraldOptions
import com.herald.sdk.LogLevel

class MainApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        Herald.configure(
            this, "YOUR_APP_KEY", "https://YOUR_HERALD_HOST",
            HeraldOptions(
                deviceDataCollection = DeviceDataCollection.MINIMAL, // Dart: DeviceDataCollection.minimal
                logLevel = LogLevel.DEBUG,                           // Dart: HeraldLogLevel.debug
                flushIntervalSeconds = 10,                           // Dart: flushInterval: Duration(seconds: 10)
                foregroundSessionTimeoutMinutes = 30,                // Dart: foregroundSessionTimeout: Duration(minutes: 30)
                trackDeepLinkQuery = false,                          // Dart: trackDeepLinkQuery: false
            ),
        )
    }
}
```

Every Android option is listed on [Android API](/docs/reference/android-api).

Name it in `AndroidManifest.xml` with `android:name=".MainApplication"` on `<application>`.

In Dart, `HeraldOptions` takes `deviceDataCollection`, `flushInterval`, `flushAt`, `foregroundSessionTimeout`, `backgroundSessionTimeout`, `inAppMinimumInterval`, `logLevel`, `trackLifecycleEvents`, `trackDeepLinks`, `trackDeepLinkQuery`, `trackExternalPushes` and `crashReports` (iOS only). A field left out keeps the native default. They apply on iOS, and on Android only when there is no native `configure` call. Android rounds session timeouts down to whole minutes.

## 3. Identify, track and set attributes

```dart
await Herald.identify('user-123', traits: {'plan': 'free'});
await Herald.setUserToken(tokenFromYourBackend);
await Herald.track('lesson_completed', properties: {'minutes': 12});
await Herald.screen('Home');
await Herald.trackPurchase(productId: 'pro_monthly', price: 9.99, currency: 'USD');
await Herald.setEmail('ada@example.com');
await Herald.setPhone('+15551234567');
final supportId = await Herald.heraldId;
```

Values are Dart strings, numbers, booleans, null, lists and maps, with the same rules as the native SDKs. `reset()` signs the user out; `flush()`, `setEnabled()`, `isEnabled` and `wipeData()` work as on [iOS](/docs/reference/ios-api#data-control).

## 4. Push

```dart
final granted = await Herald.requestPushAuthorization(); // iOS: true or false. Android: null
```

What the plugin does for you:

- **iOS** forwards the APNs token, push taps and sync pushes from your `FlutterAppDelegate`, and shows a Herald push that arrives while the app is open as a banner. Other notifications are left to your other plugins. Set the notification center's delegate to it in `application(_:didFinishLaunchingWithOptions:)`: `UNUserNotificationCenter.current().delegate = self`. Add the Push Notifications capability and the Remote notifications background mode.
- **Android** brings in `herald-fcm`. Its messaging service registers the FCM token and shows Herald pushes, and the plugin passes notification taps to the SDK.

If another plugin owns push, such as `firebase_messaging`, pass its token to `Herald.setPushToken`: the FCM token on Android, the APNs token as hex on iOS. Only one `FirebaseMessagingService` gets messages on Android; see [Android push setup](/docs/push-notifications/android-setup) for an app with its own service.

Deep links from pushes, cards and messages open through the system, so your app's deep link handling receives them.

## 5. Content cards

The plugin gives you the card data; draw the cards with your own widgets and log what the user does.

```dart
final cards = await Herald.contentCards;
Herald.contentCardsStream.listen((cards) => setState(() => _cards = cards));

Herald.logImpression(card); // once, when it is shown
Herald.logClick(card);
Herald.logDismissal(card);
await Herald.refreshContentCards();
```

Numbers in a card's `extras` arrive as `int` when whole and `double` otherwise, on both platforms.

## 6. In-app messages

Messages are drawn by the native default views. To decide whether one shows, set a handler:

```dart
Herald.setInAppMessageHandler((message) {
  if (_inCheckout) return InAppMessageDisplayChoice.later;
  return InAppMessageDisplayChoice.display;
});
```

The handler runs in Dart, so the native SDK keeps the message pending while it decides. Then `display` shows it, `later` keeps it pending (`showNext()` offers it again) and `discard` drops this occurrence. If a higher-priority message is pending too, the SDK offers that one first. `setInAppMessageHandler(null)` shows every message.

## Errors

Calls throw a `PlatformException` only in these cases:

| Call | Platform | When |
|---|---|---|
| `configure` | iOS | `endpoint` isn't a URL (`bad_args`). Android accepts any string. |
| `setPushToken` | iOS | The token isn't hex (`bad_args`). Android accepts any string. |
| `requestPushAuthorization` | Android | No activity is attached (`no_activity`) |

`requestPushAuthorization` on iOS waits until the person answers the permission prompt. Other invalid input is logged by the native SDK and the call is skipped, as in the native SDKs.

## What the plugin doesn't wrap

Live Activities, push stories, geofences, subscription states, consent, location, pushes your app sends, custom in-app presenters and themes, and the native card feed views. They work from the native side of a Flutter app: call the iOS or Android SDK from Swift or Kotlin. The Android modules are on your app's classpath through the plugin.

## Next

- [Platform support](/docs/overview/platform-support)
- [Content cards](/docs/content-cards/overview)
- [In-app messages](/docs/in-app-messages/overview)
