# Flutter & Dart

> Track screens, events, signed-in users and paywalls in Flutter apps on iOS, Android, web and desktop, with an offline queue and consent.

Source: https://metricraven.com/docs/flutter  
Markdown: https://metricraven.com/docs/flutter.md  
Section: Installation guides

The `metricraven` package records screen views, goals, identified users and paywall events from Flutter apps. It works on iOS, Android, web, macOS and Windows. Each device shows on the realtime globe as a live visitor, under the person you identified it as, and purchases from RevenueCat, Superwall or Adapty are credited to the campaign that brought that person.

## Set up

1. **Allow your app in Settings**

   In your site's **Settings → General → Site**, add your bundle / package ID under **Mobile apps**, for example `com.example.app`. App events from IDs that aren't listed are rejected. A Flutter web build reports like a website instead: its domain must be one of the site's domains.

2. **Add the package**

   ```bash
   flutter pub add metricraven
   ```

3. **Configure it once at launch**

   ```dart title="lib/main.dart"
   import 'package:flutter/widgets.dart';
   import 'package:metricraven/metricraven.dart';

   Future<void> main() async {
     WidgetsFlutterBinding.ensureInitialized();
     // App ID (your bundle / package ID), version and device are read automatically.
     await MetricRaven.configure(siteId: 'ana_pub_…');
     runApp(const MyApp());
   }
   ```

4. **Track screens**

   ```dart
   // Navigator with named routes: every route name becomes a screen view.
   MaterialApp(
     navigatorObservers: [MetricRavenNavigatorObserver()],
     routes: {
       '/': (_) => const HomeScreen(),
       '/settings': (_) => const SettingsScreen(),
     },
   );

   // go_router: pages are recorded by route pattern (users/:id), never the location.
   final router = GoRouter(
     observers: [MetricRavenNavigatorObserver()],
     routes: [/* … */],
   );

   // Or by hand, from any screen.
   MetricRaven.screen('Settings');
   ```

5. **Send events and identify users**

   ```dart
   // A goal, with up to 10 props.
   MetricRaven.track('signup', {'plan': 'pro', 'seats': 3});

   // After sign-in: the same user ID as your server events, server identify and payments.
   MetricRaven.identify(user.id, {'name': user.name, 'email': user.email});

   // Verified instead: your server signs the user (signIdentity in @metricraven/node).
   MetricRaven.identifyWithToken(tokenFromYourServer);

   // On sign-out.
   MetricRaven.reset();
   ```

> **Verify it works**
>
> Run the app on a device or simulator. It appears as a live visitor in **Traffic**, with the name you identified it with. Screens are listed under **Pages** as paths like `/settings`, and your app ID appears under **Hostnames**.

## API

| Call | Notes |
| --- | --- |
| configure(siteId:, appId:, consent:) | Once at launch, before runApp. appId defaults to the bundle / package ID. Returns false for an app ID that isn't a bundle / package ID. |
| MetricRavenNavigatorObserver() | Records each named page route as a screen view, once per change. Dialogs and sheets keep the screen they cover. Pass screenName: to rename or skip routes. |
| screen(name, props) | A screen view. Names like "Settings" become the path /Settings. |
| track(name, props) | A goal. Names: letters, digits, _ : . -, up to 100 characters. Up to 10 props (strings, numbers, booleans). |
| identify(userId, traits) | Links this device to your user ID, with optional name, email, image (https) and up to 10 custom traits. Self-asserted, so a server identify takes precedence. |
| identifyWithToken(token) | Signed identify with a token your server signed. Verified, like server identify; get a fresh token at sign-in and launch. |
| reset() | On sign-out. Forgets identify state and, with consent, starts a new visitor ID. |
| setConsent(granted) | With consent a random visitor ID is kept on the device; without it the server derives a daily one. |
| openedFrom(uri) | utm_\* campaign parameters from a deep link, attached to the next screen view. |
| visitorId | This device's visitor ID, to pass to your paywall tool or checkout. |
| paywall(provider:, …) | Paywall views, closes, cancels and taps from RevenueCat, Superwall, Adapty or your own paywall. See below. |
| flush() | Sends what is queued now. The package also flushes when the app comes to the foreground and before it goes to the background. |

Each screen view carries the device's language and the screen size in logical pixels (for example `402x874`, like points on iOS). They show under **Language** and **Screen size**. Events and identify calls never carry them.

## Campaigns from deep links

```dart
// app_links (or your router's deep link handler)
// utm_* parameters go on the next screen view.
AppLinks().uriLinkStream.listen(MetricRaven.openedFrom);
```

## Paywall events

The paywall helper has no dependency on any paywall SDK: call it from the paywall SDK's callbacks. Event names and properties are the same as the other SDKs'; see [Paywall events](https://metricraven.com/docs/paywall-events). Identify the signed-in user with the same ID as your paywall tool, so paywall events and purchases belong to the same person.

### RevenueCat (purchases_ui_flutter)

```dart
final paywall = MetricRaven.paywall(
  provider: 'revenuecat',
  offeringId: offering.identifier,
);
paywall.impression();

PaywallView(
  offering: offering,
  onDismiss: paywall.close,
  onPurchaseCancelled: paywall.cancel,
  onInteraction: paywall.interaction,
);
```

### Superwall (superwallkit_flutter)

```dart
class MyDelegate extends SuperwallDelegate {
  final paywall = MetricRaven.paywall(provider: 'superwall');

  @override
  void handleSuperwallEvent(SuperwallEventInfo eventInfo) {
    paywall.superwall(eventInfo.event.type.name, eventInfo.params);
  }
}
```

### Adapty (adapty_flutter)

```dart
class MyObserver extends AdaptyUIFlowsEventsObserver {
  final paywall = MetricRaven.paywall(
    provider: 'adapty',
    placement: 'onboarding',
  );

  @override
  void flowViewDidAppear(AdaptyUIFlowView view) => paywall.impression();

  @override
  void flowViewDidSelectProduct(AdaptyUIFlowView view, String productId) =>
      paywall.productSelected(productId);

  @override
  void flowViewDidPerformAction(AdaptyUIFlowView view, AdaptyUIAction action) {
    if (action is CloseAction) paywall.close();
    super.flowViewDidPerformAction(view, action);
  }

  @override
  void flowViewDidFinishPurchase(
    AdaptyUIFlowView view,
    AdaptyPaywallProduct product,
    AdaptyPurchaseResult result,
  ) {
    if (result is AdaptyPurchaseResultUserCancelled) paywall.cancel();
  }
}
```

## One person across the app and your server

Use the same user ID everywhere: [server events](https://metricraven.com/docs/server-events), [server identify](https://metricraven.com/docs/identify-users), payments and the app's `identify`. For a verified profile on the device, have your server sign a token for the signed-in user and call `identifyWithToken`. An unsigned `identify` is a self-asserted claim and never borrows a verified profile.

## Details

- Events wait in shared_preferences while the device is offline (up to 500, for 7 days) and are delivered in order, with backoff on network errors, rate limits and server errors.
- Without consent nothing is stored on the device. Let people choose in your app and call `setConsent`; consent at launch is `configure(…, consent: true)`.
- It reads the app's version and build (package_info_plus) and the OS version (device_info_plus). It reads no advertising ID or device identifier.
- Native apps: [iOS & Swift](https://metricraven.com/docs/ios-sdk) and [Android & Kotlin](https://metricraven.com/docs/android-sdk). React Native and Expo: [@metricraven/react-native](https://metricraven.com/docs/react-native).
