# Flutter SDK (client)

> Install the Ours Privacy Flutter SDK to capture privacy-first analytics in Flutter apps on iOS and Android. Pure Dart, with no IDFA and no ATT prompt on iOS.

Source: https://docs.oursprivacy.com/docs/flutter-sdk

Use the Ours Privacy Flutter SDK to track events, identify users, and collect app opens, sessions, and screens from your iOS and Android apps. It is pure Dart, so one package covers both platforms with no native setup.

* [pub.dev package](https://pub.dev/packages/ours_privacy)
* [GitHub repository](https://github.com/with-ours/ours-privacy-flutter): full README, API reference, and release notes

## Install

```bash
flutter pub add ours_privacy
```

## Quick Start

Create one instance for your app and initialize it with your source's API token before `runApp`:

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

final op = OursPrivacy();

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await op.init('YOUR_API_TOKEN');
  runApp(const MyApp());
}

// Anywhere in your app
op.track('App Opened');

// After login
await op.identify({'externalId': 'user-123', 'email': 'user@example.com'});
```

Events are batched and sent every 10 seconds. Call `await op.flush()` to send them immediately, and `await op.reset()` on logout to start a new visitor. For default properties, a custom server URL, and the rest of the API, see the [README on GitHub](https://github.com/with-ours/ours-privacy-flutter#readme).

### Wait for consent

If your app asks for consent first, start opted out and opt in once the person agrees:

```dart
await op.init('YOUR_API_TOKEN', optOutTrackingByDefault: true);

// When consent is granted
await op.optInTracking();
```

`optOutTrackingByDefault` applies only until a choice is saved, so a returning user keeps the choice they made. While opted out, the SDK sends nothing. `await op.optOutTracking()` also clears unsent events, and the next opt-in starts a new session.

## App lifecycle and screens

Turn on automatic lifecycle tracking to fill in app opens, sessions, and engagement in [Mobile Analytics](https://docs.oursprivacy.com/docs/mobile-analytics). It is off by default. Pass your app's version and build so you can follow release adoption:

```dart
await op.init(
  'YOUR_API_TOKEN',
  trackAutomaticEvents: true,
  appVersion: '2.0.0',
  appBuild: '42',
);
```

| Event                        | When it is sent                                                       | Event-specific properties                                  |
| ---------------------------- | --------------------------------------------------------------------- | ---------------------------------------------------------- |
| `$mobile_first_open`         | First tracked app open for this installation and source               | None                                                       |
| `$mobile_app_open`           | Each tracked foreground entry                                         | None                                                       |
| `$mobile_session_start`      | First tracked open in a new session                                   | None                                                       |
| `$mobile_session_engagement` | A foreground-time checkpoint, screen change, or background transition | `engagement_duration_ms`; `screen_name` when known         |
| `$mobile_session_end`        | When an expired session is observed, when possible                    | None                                                       |
| `$mobile_app_update`         | First tracked open after the app version or build changes             | `previous_app_version` and `previous_app_build` when known |
| `$mobile_screen_view`        | Your app calls `trackScreen()` for a new visible screen               | `screen_name`                                              |

A session continues when the app returns to the foreground within 30 minutes, and counts as engaged after 10 seconds in the foreground. `$mobile_session_end` is best effort, because an app can close without warning.

The SDK follows foreground and background changes on its own, but it does not see your navigator's route changes, so pass them in. With `Navigator` or `MaterialApp` named routes, add a `NavigatorObserver` that calls `trackScreen()` as routes change:

```dart
class OursScreenObserver extends NavigatorObserver {
  static const screenLabels = {'/': 'Home', '/schedule': 'Schedule'};

  void _trackScreen(Route<dynamic>? route) {
    final label = screenLabels[route?.settings.name];
    if (label != null) op.trackScreen(label);
  }

  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) => _trackScreen(route);

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) => _trackScreen(previousRoute);

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) => _trackScreen(newRoute);
}

MaterialApp(navigatorObservers: [OursScreenObserver()], routes: appRoutes);
```

Pass a fixed label from a list in your app, such as `Schedule`: up to 80 characters, starting with a letter, using only letters, numbers, spaces, underscores, and hyphens. `trackScreen()` throws for any other label, so map route names to labels as above rather than passing them through. Never build a label from a URL, route parameter, patient detail, or screen content.

Manual `track()` and `trackScreen()` calls work whether or not lifecycle tracking is on. Send [standard healthcare events](https://docs.oursprivacy.com/docs/standard-healthcare-events) with the same names and properties as your other sources.

Lifecycle and screen events carry device, OS, and app version details, but not your default properties or link attribution. Keep each event under 196 of your own properties and 1 MB; a larger event is still sent, but it doesn't appear in Mobile Analytics.

## Web-to-app identity

When your app is opened by a link carrying `ours_visitor_id`, the SDK sets that visitor ID so later events land on the same visitor profile as their web activity. It also reads supported UTM parameters and ad-platform click IDs from the link, attaches them to the events you track afterward, and sends a `$deep_link_opened` event with those values (not the raw URL).

Hand the URL over with `await op.trackDeepLink(url)`, and await it before your next `track()` so the visitor ID and attribution apply first. If your app already holds the visitor ID, from a WebView or a platform channel, set it directly with `await op.setVisitorId('550e8400-e29b-41d4-a716-446655440000')`. To pass the visitor ID to another SDK, such as a [mobile measurement partner](https://docs.oursprivacy.com/docs/mmp), read it with `op.getVisitorId()`.

The SDK hooks nothing in the operating system, so your app has to hand over the URL it was opened with, on a cold start and on a warm open. With the [app\_links](https://pub.dev/packages/app_links) package:

```dart
import 'package:app_links/app_links.dart';

// Delivers the link that started the app, then each later link
AppLinks().uriLinkStream.listen((uri) async {
  await op.trackDeepLink(uri.toString());
});
```

The UTM parameters and click IDs from a link last until the app quits; only the visitor ID persists across a restart. Pass the link to the SDK before you track an event that needs its attribution. Keep patient details out of the links you send people.

[Mobile app attribution](https://docs.oursprivacy.com/docs/mobile-app-attribution) covers how app attribution works end to end, and when you need a mobile measurement partner alongside it.

## Compatibility

* Flutter 3.13 or later (Dart 3.1 or later)
* iOS and Android apps

Because the SDK is pure Dart, iOS and Android version support follows your Flutter version. No IDFA is collected, so AppTrackingTransparency (ATT) permission is not required on iOS.

## Need Help?

* [GitHub Issues](https://github.com/with-ours/ours-privacy-flutter/issues)
* [support@oursprivacy.com](mailto:support@oursprivacy.com)

## Next Steps

* [Client SDKs overview](https://docs.oursprivacy.com/docs/client-overview): pick the right SDK for each surface.
* [Web SDK (JavaScript)](https://docs.oursprivacy.com/docs/web-sdk-javascript): for browser tracking on your website.
* [iOS SDK](https://docs.oursprivacy.com/docs/ios-sdk), [Android SDK](https://docs.oursprivacy.com/docs/android-sdk), and [React Native SDK](https://docs.oursprivacy.com/docs/react-native-sdk): if you build native or React Native apps instead.
* [Mobile app attribution](https://docs.oursprivacy.com/docs/mobile-app-attribution): how app attribution works, and when you need a mobile measurement partner.
* [Mobile Analytics](https://docs.oursprivacy.com/docs/mobile-analytics): read app opens, sessions, screens, and tracked events in the dashboard.
