# Flutter

> Add Lemu to a Flutter app on Android, iOS, web and desktop with lemu_analytics: events, purchases, known users, screens, app lifecycle and deep links

URL: https://docs.lemuai.com/sdks/flutter

The Flutter SDK (`lemu_analytics`) sends events, purchases, known users, app lifecycle events, deep links and screens from your Flutter app.

- Pure Dart, with no platform channels of its own. Works on Android, iOS, web, macOS, Windows and Linux.
- Events are kept on the device, sent in batches, retried when the network fails, and kept across restarts.
- Meta's standard event names, so ad platforms receive conversions unchanged.
- Consent and opt-out built in. No advertising ids and no hardware ids.

Requires Flutter 3.22 or later (Dart 3.4 or later). You need the write key of an **App** source. See [Get a write key](https://docs.lemuai.com/sdks/overview#get-a-write-key).

## Install
```bash
flutter pub add lemu_analytics
```

Android and iOS need no extra setup. On **macOS**, apps are sandboxed and need permission to make network requests. Add this to `macos/Runner/DebugProfile.entitlements` and `macos/Runner/Release.entitlements`:
```xml
<key>com.apple.security.network.client</key>
<true/>
```

## Set up

Call `setup` once in `main()`, before `runApp()`:
```dart
import 'package:flutter/widgets.dart';
import 'package:lemu_analytics/lemu_analytics.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Lemu.instance.setup('lpk_...');
  runApp(const MyApp());
}
```

The write key is public, so it's safe to ship in the app. Calls made before `setup` are ignored. No method ever throws: a bad argument is ignored and, with `debug: true`, logged.

**Warning:** If the source lists [Allowed apps](https://docs.lemuai.com/website-pixel/overview#allowed-apps), Lemu refuses events from any other app id. On Android the id is your `applicationId`, and on iOS and macOS your bundle identifier. Web and desktop builds send a different id: if you ship them, turn on debug mode, find `namespace` under `app` in a logged request, and add it to the list too.

### Options
```dart
await Lemu.instance.setup(
  'lpk_...',
  options: const LemuOptions(
    debug: false,            // log every call, request and response
    requireConsent: false,   // see "Consent and opt-out"
    flushAt: 20,             // send once this many events are queued (web: 10)
    flushInterval: Duration(seconds: 30), // and at least this often (web: 1 second)
    maxQueueSize: 1000,      // events kept on the device while offline (at most 1,000)
    trackLifecycle: true,    // app_installed, app_updated, app_opened, app_backgrounded
    trackDeepLinks: true,    // deep_link_opened from trackDeepLink()
  ),
);
```

`LemuOptions` also takes `apiHost`. Change it only if your source's setup steps show another host.

## Send events
```dart
Lemu.instance.track(LemuEvent.addToCart, {
  'value': 999,
  'currency': 'INR',
  'content_ids': ['SKU1'],
});

Lemu.instance.track('wishlist_shared', {'list_id': 'summer'});
```

Any event name works. For Meta's standard events, use the `LemuEvent` constants (`viewContent`, `addToCart`, `initiateCheckout`, `purchase` and the rest), spelled exactly as Meta expects. See the [event reference](https://docs.lemuai.com/sdks/events).

Don't put email addresses, phone numbers or other contact details in event properties. Lemu removes them; they belong in `identify()`.

## Purchases
```dart
Lemu.instance.purchase(
  value: 1499.5,
  currency: 'INR',
  orderId: '1042',
  contents: const [
    LemuContent(id: 'SKU1', quantity: 1, itemPrice: 999, title: 'Kurta'),
    LemuContent(id: 'SKU7', quantity: 1, itemPrice: 500.5),
  ],
  properties: {'coupon': 'DIWALI10'},
);
```

`purchase()` sends a `Purchase` event right away instead of waiting for the next batch. `content_ids` and `num_items` are filled in from `contents` when you don't pass them.

**Always pass the order id from your backend.** The same order is often reported by more than one source: the app, your website, your server, Shopify. Lemu counts one conversion per order id, so revenue isn't counted twice and journeys don't fire twice. Without it, every report counts. See [Conversion events](https://docs.lemuai.com/website-pixel/standard-events#conversion-events).

## Identify users

When a user signs in or signs up:
```dart
Lemu.instance.identify(
  userId: 'cust_8812',            // your own id for this user
  traits: {
    'email': 'asha@example.com',
    'phone': '+919812345678',     // international format
    'first_name': 'Asha',
    'last_name': 'Rao',
  },
);
```

The `userId` is kept and sent with every later event, also after the app restarts. On logout:
```dart
Lemu.instance.reset(); // new anonymous id, no user id
```

`Lemu.instance.anonymousId` is the id Lemu uses for this install before the user is known.

## Screens

Add `LemuNavigatorObserver` to your navigator to send a screen each time a named page becomes visible:

**Navigator**

```dart
MaterialApp(
  navigatorObservers: [LemuNavigatorObserver()],
  routes: {...},
);
```

**go_router**

```dart
final router = GoRouter(
  observers: [LemuNavigatorObserver()],
  routes: [
    GoRoute(name: 'product', path: '/product/:id', builder: ...),
  ],
);
```

go_router names each page after the `GoRoute` `name`, or its path pattern (`/product/:id`) when it has none. Routes inside a `ShellRoute` need the observer on that `ShellRoute` too.

Dialogs, bottom sheets and unnamed routes are skipped. To choose names yourself:
```dart
LemuNavigatorObserver(
  nameExtractor: (route) => route.settings.name?.replaceAll('/', ' ').trim(),
)
```

Or send screens yourself:
```dart
Lemu.instance.screen('Checkout', {'step': 2});
```

Screens are stored as `screen_viewed`.

## Deep links and campaigns

Pass each link that opens the app to `trackDeepLink`. It sends `deep_link_opened` and keeps the link's `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`, `gclid` and `fbclid` with every later event in the session, so later events, including the purchase, are credited to the campaign.

**app_links**

The [app_links](https://pub.dev/packages/app_links) stream also delivers the link that launched the app:
```dart
final appLinks = AppLinks();
appLinks.uriLinkStream.listen((uri) => Lemu.instance.trackDeepLink(uri));
```

**go_router**

Track links in the top-level `redirect`. It also runs for in-app navigation, so only track URLs that carry campaign parameters, once each:
```dart
Uri? lastTrackedLink;

final router = GoRouter(
  redirect: (context, state) {
    final uri = state.uri;
    final hasCampaign = uri.queryParameters.keys
        .any((k) => k.startsWith('utm_') || k == 'gclid' || k == 'fbclid');
    if (hasCampaign && uri != lastTrackedLink) {
      lastTrackedLink = uri;
      Lemu.instance.trackDeepLink(uri);
    }
    return null;
  },
  routes: [...],
);
```

`trackDeepLink(uri, referrer: 'com.instagram.android')` records where the link came from, when you know it.

## App lifecycle events

Unless you set `trackLifecycle: false`, the SDK sends:

| Event | When | Properties |
|---|---|---|
| `app_installed` | First launch | `version`, `build` |
| `app_updated` | First launch after the version or build changed | `version`, `build`, `previous_version`, `previous_build` |
| `app_opened` | Launch and every return to the foreground | `from_background` |
| `app_backgrounded` | The app goes to the background | |

Queued events are sent when the app goes to the background, with or without lifecycle events. If you add the SDK to an app people already have, each of them sends `app_installed` once, on their first launch with the SDK.

## Consent and opt-out

If you must ask before tracking, for example under GDPR or the DPDP Act, set `requireConsent: true`. Nothing is sent and nothing is written to the device, not even the anonymous id, until the user agrees. Up to 50 events are held in memory meanwhile.
```dart
await Lemu.instance.setup('lpk_...',
    options: const LemuOptions(requireConsent: true));

// later, from your consent screen
Lemu.instance.setConsent(true);  // sends the held events; remembered across launches
Lemu.instance.setConsent(false); // discards held and queued events
```

To stop all tracking for a user who opts out in your settings screen:
```dart
Lemu.instance.optOut(); // clears the queue, remembered across launches
Lemu.instance.optIn();  // resumes
```

## Flutter web

On the web, the SDK reuses the visitor id of the Lemu [website snippet](https://docs.lemuai.com/sdks/javascript) (the `_lemu_aid` cookie and local storage key) when the Flutter app runs on the same site. A visitor who browses your website and then your Flutter web app is one visitor, and a visitor who opted out on the website stays opted out. Events are sent every second or every 10 events.

## Debugging
```dart
await Lemu.instance.setup('lpk_...',
    options: const LemuOptions(debug: true));
```

Every call, request body and response status is printed with a `[Lemu]` prefix through `debugPrint`. `Lemu.instance.flush()` sends the queue immediately, which helps while testing. To see what Lemu stored, open the source in **Settings → Tracking Sources** and use [Recent events](https://docs.lemuai.com/website-pixel/overview#recent-events).

## How sending works

- Events are kept on the device (in shared_preferences) and survive restarts. At most 1,000 are kept; when full, the oldest event that isn't a `Purchase` is dropped. Events older than 7 days are dropped before sending.
- Each request carries up to 50 events. Apps send every 30 seconds or 20 events, when going to the background, and right after a purchase. The web sends every second or 10 events.
- Network errors, timeouts and server errors are retried with increasing waits, up to 5 minutes apart. A batch that keeps failing is dropped 20 hours after it was queued. Refused batches are dropped and the reason is logged in debug mode.
- Every request has the User-Agent `lemu-flutter/<version> (<os> <os version>; <model>)`, except on the web, where the browser sets its own.

## Privacy and store forms

What the SDK collects:

- A random anonymous id created on first launch and stored in the app's preferences. It isn't derived from the device and is replaced on `reset()` or reinstall.
- The events and properties your code sends, plus the `userId` and traits you pass to `identify()`.
- App name, version, build and package name; device manufacturer, model and type; OS name and version; screen size and pixel density; locale; time zone; campaign parameters from deep links.

It doesn't collect advertising ids (IDFA, GAID), hardware or vendor ids (Android ID, `identifierForVendor`), location, contacts, or anything else you don't send.

Your store answers depend on what your app sends and how your Lemu workspace uses it. The Flutter SDK collects the same data as the native SDKs, so the answers under [Google Play data safety](https://docs.lemuai.com/sdks/android#google-play-data-safety) and [App Privacy answers in App Store Connect](https://docs.lemuai.com/sdks/ios#app-privacy-answers-in-app-store-connect) apply. The Flutter SDK reads no advertising identifier and doesn't need the App Tracking Transparency prompt to work. If your workspace forwards conversions to ad platforms, for example through the Meta Conversions API, both stores count that as tracking or sharing: declare it, and follow Apple's App Tracking Transparency rules for it.
