On this page

Flutter SDK 4

This is the official documentation for the Amplitude Analytics Flutter SDK. The Flutter SDK lets you send events from your Flutter application to Amplitude.

Compatibility

Amplitude Flutter v4 bumps the Kotlin version to v1.9.22 to support the latest Gradle.

The following matrix lists the minimum support for the Amplitude Flutter SDK version.

Install the SDK

Run the following command to get the latest version of amplitude_flutter, add it to your pubspec.yaml, then retrieve dependencies:

bash
flutter pub add amplitude_flutter

iOS installation

Add platform :ios, '13.0' to your Podfile. Run pod install in the ios directory of your Flutter project to update the CocoaPods dependencies.

To enable Bitcode, follow Flutter's documentation.

macOS installation

Add platform :osx, '10.15' to your Podfile. Run pod install in the macos directory of your Flutter project to update the CocoaPods dependencies. Ensure your app has the com.apple.security.network.client entitlement to be able to send requests. Manually edit the macos/Runner/Release.entitlements and macos/Runner/DebugProfile.entitlements files to include:

xml
	<key>com.apple.security.network.client</key>
	<true/>

Refer to Flutter's documentation for more information.

Web installation (optional)

The Flutter SDK uses Dart's JavaScript interoperability to enable Browser SDK 2 for Flutter Web. This requires that you make the SDK available within the global JavaScript scope. Add the following Browser SDK 2 snippet to web/index.html in your Flutter project:

html
<script type="text/javascript">
  !(function () {
    "use strict";
    !(function (e, t) {
      var r = e.amplitude || { _q: [], _iq: {} };
      if (r.invoked)
        e.console &&
          console.error &&
          console.error("Amplitude snippet has been loaded.");
      else {
        var n = function (e, t) {
            e.prototype[t] = function () {
              return (
                this._q.push({
                  name: t,
                  args: Array.prototype.slice.call(arguments, 0),
                }),
                this
              );
            };
          },
          s = function (e, t, r) {
            return function (n) {
              e._q.push({
                name: t,
                args: Array.prototype.slice.call(r, 0),
                resolve: n,
              });
            };
          },
          o = function (e, t, r) {
            e._q.push({ name: t, args: Array.prototype.slice.call(r, 0) });
          },
          i = function (e, t, r) {
            e[t] = function () {
              if (r)
                return {
                  promise: new Promise(
                    s(e, t, Array.prototype.slice.call(arguments)),
                  ),
                };
              o(e, t, Array.prototype.slice.call(arguments));
            };
          },
          a = function (e) {
            for (var t = 0; t < g.length; t++) i(e, g[t], !1);
            for (var r = 0; r < m.length; r++) i(e, m[r], !0);
          };
        r.invoked = !0;
        var c = t.createElement("script");
        ((c.type = "text/javascript"),
          (c.integrity =
            "sha384-R0H1kXlk6r2aEQMtwVcPolpk0NAuIqM/8NlxAv24Gr3/PBJPl+9elu0bc3o/FDjR"),
          (c.crossOrigin = "anonymous"),
          (c.async = !0),
          (c.src =
            "https://cdn.amplitude.com/libs/analytics-browser-2.11.10-min.js.gz"),
          (c.onload = function () {
            e.amplitude.runQueuedFunctions ||
              console.log("[Amplitude] Error: could not load SDK");
          }));
        var l = t.getElementsByTagName("script")[0];
        l.parentNode.insertBefore(c, l);
        for (
          var u = function () {
              return ((this._q = []), this);
            },
            p = [
              "add",
              "append",
              "clearAll",
              "prepend",
              "set",
              "setOnce",
              "unset",
              "preInsert",
              "postInsert",
              "remove",
              "getUserProperties",
            ],
            d = 0;
          d < p.length;
          d++
        )
          n(u, p[d]);
        r.Identify = u;
        for (
          var f = function () {
              return ((this._q = []), this);
            },
            v = [
              "getEventProperties",
              "setProductId",
              "setQuantity",
              "setPrice",
              "setRevenue",
              "setRevenueType",
              "setEventProperties",
            ],
            y = 0;
          y < v.length;
          y++
        )
          n(f, v[y]);
        r.Revenue = f;
        var g = [
            "getDeviceId",
            "setDeviceId",
            "getSessionId",
            "setSessionId",
            "getUserId",
            "setUserId",
            "setOptOut",
            "setTransport",
            "reset",
            "extendSession",
          ],
          m = [
            "init",
            "add",
            "remove",
            "track",
            "logEvent",
            "identify",
            "groupIdentify",
            "setGroup",
            "revenue",
            "flush",
          ];
        (a(r),
          (r.createInstance = function (e) {
            return ((r._iq[e] = { _q: [] }), a(r._iq[e]), r._iq[e]);
          }),
          (e.amplitude = r));
      }
    })(window, document);
  })();
</script>

Initialize the SDK

Sending events

This SDK uses the HTTP V2 API and follows the same constraints for events. Make sure all events logged in the SDK contain at least one of deviceId (included by default) or userId, and follow the HTTP API's constraints on each of those fields.

To prevent instrumentation issues, device IDs and user IDs must be strings with a length of 5 characters or more. If an event contains a device ID or user ID that's too short, Amplitude removes the ID value from the event. If the event doesn't have a userId or deviceId value, Amplitude may reject the upload with a 400 status. Override the default minimum length of 5 characters by setting the minIdLength config option.

Before you instrument your application, initialize the SDK with your Amplitude project's API key.

dart
import 'package:amplitude_flutter/amplitude.dart';
import 'package:amplitude_flutter/configuration.dart';
import 'package:amplitude_flutter/events/base_event.dart';

class YourClass {
  Future<void> exampleForAmplitude() async {
    // Create and initialize the instance
    final Amplitude amplitude = Amplitude(Configuration(
        apiKey: 'YOUR-API-KEY',
    ));

    // Wait until the SDK is initialized
    await amplitude.isBuilt;

    // Track an event
    amplitude.track(BaseEvent(
        eventType: 'BUTTON_CLICKED',
        eventProperties: {'Hover Time': '100ms'},
    ));

    // Send events to the server
    amplitude.flush()
  }
}

Configure the SDK

Configuration for Android and iOS

Configuration for web and Android

Configuration for Android

Configuration for web

  • appVersion
    • Description: String. Sets an app version for events tracked. This can be the version of your application. For example: "1.0.0".
    • Default Value: null
  • cookieOptions.domain
    • Description: String. Sets the domain property of cookies created.
    • Default Value: null
  • cookieOptions.expiration
    • Description: int. Sets expiration of cookies created in days.
    • Default Value: 365 days
  • cookieOptions.sameSite
    • Description: String. Sets SameSite property of cookies created.
    • Default Value: null
  • cookieOptions.secure
    • Description: bool. Sets Secure property of cookies created.
    • Default Value: null
  • cookieOptions.upgrade
    • Description: bool. Sets upgrading from cookies created by maintenance Browser SDK. If true, new Browser SDK deletes cookies created by maintenance Browser SDK. If false, Browser SDK keeps cookies created by maintenance Browser SDK.
    • Default Value: null
  • identityStorage
    • Description: String. Sets storage API for user identity. Options include cookie for document.cookie, localStorage for localStorage, or none to opt-out of persisting user identity.
    • Default Value: cookie
  • userId
    • Description: String. Sets an identifier for the tracked user. Must have a minimum length of 5 characters unless overridden with the minIdLength option.
    • Default Value: null
  • transport
    • Description: String. Sets request API to use by name. Options include fetch for fetch, xhr for XMLHTTPRequest, or beacon for navigator.sendBeacon.
    • Default Value: fetch
  • fetchRemoteConfig
    • Description: bool. Whether the SDK fetches remote configuration. Review Browser SDK 2 for more information. The default depends on the Browser SDK version used. For Browser SDK 2.16.1+, the default is true.
    • Default Value: false (for Browser SDK = 2.16.1)
  • autocapture
    • Description: Autocapture. Configures autocapture behavior for sessions, page views, and marketing attribution. Use AutocaptureDisabled(), AutocaptureEnabled(), or AutocaptureOptions() for granular control. By default, AutocaptureOptions() with no parameters enables all features. Refer to Autocapture for more information.
    • Default Value: AutocaptureOptions()

Configure batching behavior

To support high-performance environments, the SDK sends events in batches. The track method queues every event in memory, and the SDK flushes events in batches in the background. Customize batch behavior with flushQueueSize and flushIntervalMillis. By default, the serverUrl is https://api2.amplitude.com/2/httpapi.

If you need to send large batches of data at once, set useBatch to true. This sets setServerUrl to the batch event upload API https://api2.amplitude.com/batch. Both the regular mode and the batch mode use the same events upload threshold and flush time intervals.

dart
final Amplitude analytics = Amplitude(Configuration(
    apiKey: 'YOUR-API-KEY',
    flushIntervalMillis: 50000,
    flushQueueSize: 20,
));

EU data residency

Configure the server zone when you initialize the client to send data to Amplitude's EU servers. The SDK sends data based on the server zone if you set it.

For EU data residency, the project must be set up inside Amplitude EU. You must initialize the SDK with the API key from Amplitude EU.

dart
final Amplitude analytics = Amplitude(Configuration(
    apiKey: 'YOUR-API-KEY',
    serverZone: ServerZone.eu,
));

Track

Events represent how users interact with your application. For example, "Song Played" can be an action you want to track.

dart
amplitude.track(BaseEvent('Song Played'));

You can also optionally include event properties.

dart
amplitude.track(BaseEvent('Song Played', eventProperties: {'title': 'Happy Birthday'}));

Refer to the BaseEvent interface for all available fields.

Identify

Use Identify to set the user properties of a particular user without sending any event. The SDK supports the set, setOnce, unset, add, append, prepend, preInsert, postInsert, remove, and clearAll operations on individual user properties. Declare the operations with the provided Identify interface. You can chain multiple operations in a single Identify object, then pass the Identify object to the Amplitude client to send to the server.

If you send the Identify call after the event, the results of operations appear immediately in the dashboard user's profile area, but they don't appear in chart results until the SDK sends another event after the Identify call. As a result, the Identify call only affects future events. For more information, refer to User Properties and Events.

You can handle a user's identity using the identify methods. Proper use of these methods connects events to the correct user as the user moves across devices, browsers, and other platforms. Send an identify call containing those user property operations to the Amplitude server to tie a user's events to specific user properties.

dart
final Identify identify = Identify()
    ..set('color', 'green')
amplitude.identify(identify)

Clear all user properties

Use clearAll to remove all user properties from a user. Use clearAll with care because the operation is irreversible.

dart
final Identify identify = Identify()
    ..clearAll();
amplitude.identify(identify);

Track default events

The SDK can track more default events. Configure it to track the following events by default:

  • Sessions

  • App lifecycles

  • Deep links (available on Android only)

  • config.defaultTracking.sessions

    • Type: Optional. bool
    • Default Value: true
    • Description:
      • Enables session tracking. If the value is true, Amplitude tracks session start and session end events. Otherwise, Amplitude doesn't track session events. When this setting is false, Amplitude tracks sessionId only.
      • Refer to Track sessions for more information.
  • config.defaultTracking.appLifecycles

    • Type: Optional. bool
    • Default Value: false
    • Description:
      • Enables application lifecycle events tracking. If the value is true, Amplitude tracks application installed, application updated, application opened, and application backgrounded events.
      • Tracked event properties include: [Amplitude] Version, [Amplitude] Build, [Amplitude] Previous Version, [Amplitude] Previous Build, [Amplitude] From Background.
      • Refer to Track application lifecycles for more information.
  • config.defaultTracking.deepLinks

    • Type: Optional. bool
    • Default Value: false
    • Description:
      • Available on Android only. Enables deep link tracking. If the value is true, Amplitude tracks deep link opened events.
      • Tracked event properties include: [Amplitude] Link URL, [Amplitude] Link Referrer.
      • Refer to Track deep links for more information.

To enable Amplitude to start tracking all the events listed, use the following code sample. Otherwise, omit the configuration to keep only session tracking enabled.

dart
Amplitude(
  Configuration(
    apiKey: 'YOUR-API-KEY',
    defaultTracking: DefaultTrackingOptions.all()
  )
);

Amplitude may add more events in a future version, and this configuration also enables tracking for those events.

To prevent Amplitude from tracking default events, use the following code sample:

dart
Amplitude(
  Configuration(
    apiKey: 'YOUR-API-KEY',
    defaultTracking: DefaultTrackingOptions.none()
  )
);

Customize the tracking with DefaultTrackingOptions.

dart
Amplitude(
  Configuration(
    apiKey: 'YOUR-API-KEY',
    defaultTracking: DefaultTrackingOptions(
      sessions: false,
      appLifecycles: true,
      deepLinks: true,
    )
  )
);

Track sessions

When you set configuration.defaultTracking.sessions: true, Amplitude tracks session events.

dart
Amplitude(
  Configuration(
    apiKey: 'YOUR-API-KEY',
    defaultTracking: DefaultTrackingOptions(
      sessions: true,
    )
  )
);

Track application lifecycles

When you set configuration.defaultTracking.appLifecycles to true, Amplitude tracks application lifecycle events.

dart
Amplitude(
  Configuration(
    apiKey: 'YOUR-API-KEY',
    defaultTracking: DefaultTrackingOptions(
      appLifecycles: true,
    )
  )
);

After enabling this setting, Amplitude tracks the following events:

  • [Amplitude] Application Installed: fires when a user opens the application for the first time right after installation.
  • [Amplitude] Application Updated: fires when a user opens the application after updating it.
  • [Amplitude] Application Opened: fires when a user launches or foregrounds the application after the first open.
  • [Amplitude] Application Backgrounded: fires when a user backgrounds the application.

Deep link tracking is available on Android only.

When you set configuration.defaultTracking.deepLinks to true, Amplitude tracks events related to deep links in your application.

dart
Amplitude(
  Configuration(
    apiKey: 'YOUR-API-KEY',
    defaultTracking: DefaultTrackingOptions(
      deepLinks: true,
    )
  )
);

After enabling this setting, Amplitude tracks the [Amplitude] Deep Link Opened event with the URL and referrer information.

Autocapture

Autocapture is available on Web only.

Autocapture tracks user interactions and events automatically, without manual instrumentation. The SDK supports the following autocapture features on Web:

  • Sessions: Track session start and end events automatically.
  • Page views: Track page view events automatically when the URL changes.
  • Attribution: Track attribution parameters automatically from URL query parameters.

Enable autocapture

By default, all autocapture features are enabled (sessions, page views, and attribution). You can also enable all features explicitly with AutocaptureEnabled():

dart
Amplitude(
  Configuration(
    apiKey: 'YOUR-API-KEY',
    autocapture: AutocaptureEnabled(),
  )
);

Disable autocapture

To disable all autocapture features, use AutocaptureDisabled():

dart
Amplitude(
  Configuration(
    apiKey: 'YOUR-API-KEY',
    autocapture: AutocaptureDisabled(),
  )
);

Configure autocapture

Use AutocaptureOptions for granular control over autocapture features:

dart
Amplitude(
  Configuration(
    apiKey: 'YOUR-API-KEY',
    autocapture: AutocaptureOptions(
      sessions: true,
      pageViews: PageViewsOptions(
        trackHistoryChanges: 'pathOnly',
        eventType: '[Amplitude] Page Viewed',
      ),
      attribution: AttributionOptions(
        excludeReferrers: ['example.com'],
        initialEmptyValue: 'NONE',
        resetSessionOnNewCampaign: true,
      ),
    ),
  )
);

Sessions

Set sessions to true to track session start and end events automatically. Set sessions to false to disable session tracking.

dart
autocapture: AutocaptureOptions(
  sessions: true,
)

Page views

Configure page view tracking with PageViewsOptions:

dart
autocapture: AutocaptureOptions(
  pageViews: PageViewsOptions(
    trackHistoryChanges: 'pathOnly',
    eventType: 'Page View',
  ),
)

To disable page view tracking, use PageViewsDisabled():

dart
autocapture: AutocaptureOptions(
  pageViews: PageViewsDisabled(),
)

Attribution

Configure marketing attribution tracking with AttributionOptions:

dart
autocapture: AutocaptureOptions(
  attribution: AttributionOptions(
    excludeReferrers: ['example.com', 'internal.com'],
    initialEmptyValue: 'NONE',
    resetSessionOnNewCampaign: true,
  ),
)

To disable attribution tracking, use AttributionDisabled():

dart
autocapture: AutocaptureOptions(
  attribution: AttributionDisabled(),
)

User groups

Amplitude supports assigning users to groups and running queries, such as Count by Distinct, on those groups. If at least one member of the group has performed the specific event, the count includes the group.

For example, group your users by the organization they belong to using an 'orgId'. Joe is in 'orgId' '10', and Sue is in 'orgId' '15'. Sue and Joe both perform a certain event. You can query their organizations in the Event Segmentation Chart.

When setting groups, define a groupType and groupName. In the previous example, 'orgId' is the groupType and '10' and '15' are the values for groupName. Another example of a groupType could be 'sport' with groupName values like 'tennis' and 'baseball'.

Setting a group also sets the groupType:groupName as a user property and overwrites any existing groupName value for that user's groupType and the corresponding user property value. groupType is a string, and groupName can be either a string or an array of strings, where the array indicates that a user is in multiple groups.

If Joe is in 'orgId' '15', the groupName is '15'.

dart
// set group with a single group name
amplitude.setGroup('orgId', '15');

If Joe is in 'sport' 'tennis' and 'soccer', the groupName is '["tennis", "soccer"]'.

dart
// set group with multiple group names
amplitude.setGroup('sport', ['tennis', 'soccer']);

You can also set event-level groups by passing an Event Object with groups to track. With event-level groups, the group designation applies only to the specific logged event and doesn't persist on the user unless you set the group explicitly with setGroup.

dart
amplitude.track(BaseEvent('event type',
    eventProperties: {'event property': 'event property value'},
    groups: {'ordId': '15'}));

Group identify

Use the Group Identify API to set or update the properties of particular groups. Keep these considerations in mind:

  • Updates affect only future events, and don't update historical events.
  • You can track up to 5 unique group types and 10 total groups.

The groupIdentify method accepts a group type string parameter, a group name object parameter, and an Identify object that Amplitude applies to the group.

dart
final groupType = 'plan';
final groupName = 'enterprise';

final identify = Identify().set('key', 'value');
amplitude.groupIdentify(groupType, groupName, identify);

Track revenue

Amplitude can track revenue generated by a user. Amplitude tracks revenue through distinct revenue objects, which have special fields that Amplitude's Event Segmentation and Revenue LTV charts use. Amplitude then displays revenue data in the platform automatically. Revenue objects support the following special properties, and also support user-defined properties through the eventProperties field.

dart
final revenue = Revenue()
  ..productId = 'com.company.productId'
  ..price = 3.99
  ..quantity = 3;
amplitude.revenue(revenue);

Custom user ID

If your app has a login system you want to track users with, call setUserId at any time.

Sending events

This SDK uses the HTTP V2 API and follows the same constraints for events. Make sure all events logged in the SDK contain at least one of deviceId (included by default) or userId, and follow the HTTP API's constraints on each of those fields.

To prevent instrumentation issues, device IDs and user IDs must be strings with a length of 5 characters or more. If an event contains a device ID or user ID that's too short, Amplitude removes the ID value from the event. If the event doesn't have a userId or deviceId value, Amplitude may reject the upload with a 400 status. Override the default minimum length of 5 characters by setting the minIdLength config option.

dart
amplitude.setUserId('user@amplitude.com');

Custom device ID

Assign a new device ID using deviceId. When you set a custom device ID, make sure the value is sufficiently unique. Amplitude recommends using a UUID.

Sending events

This SDK uses the HTTP V2 API and follows the same constraints for events. Make sure all events logged in the SDK contain at least one of deviceId (included by default) or userId, and follow the HTTP API's constraints on each of those fields.

To prevent instrumentation issues, device IDs and user IDs must be strings with a length of 5 characters or more. If an event contains a device ID or user ID that's too short, Amplitude removes the ID value from the event. If the event doesn't have a userId or deviceId value, Amplitude may reject the upload with a 400 status. Override the default minimum length of 5 characters by setting the minIdLength config option.

dart
amplitude.setDeviceId('your-unique-device-id');

Reset when a user logs out

reset is a shortcut to anonymize users after they log out. It does the following:

  • Sets userId to null.
  • Sets deviceId to a new value based on the current configuration.

With an empty userId and a new deviceId, the current user appears as a new user in the dashboard.

dart
amplitude.reset();

Was this helpful?