Flutter SDK 4.0

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

Install the SDK

  1. Go to the pubspec.yaml file and add Amplitude SDK as a dependency.

    1dependencies:
    2 amplitude_flutter: ^4.0.0-beta.1
  2. Run flutter pub get in the terminal to install the SDK.

iOS installation

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

To enable Bitcode, follow Flutter's documentation.

Initialize the SDK

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

1import 'package:amplitude_flutter/amplitude.dart';
2import 'package:amplitude_flutter/configuration.dart';
3import 'package:amplitude_flutter/events/base_event.dart';
4 
5class YourClass {
6 Future<void> exampleForAmplitude() async {
7 // Create and initailize the instance
8 final Amplitude analytics = Amplitude(Configuration(
9 apiKey: 'YOUR-API-KEY',
10 ));
11 
12 // Wait until the SDK is initialized
13 await amplitude.isBuilt;
14 
15 // Track an event
16 amplitude.track(BaseEvent(
17 eventType: 'BUTTON_CLICKED',
18 eventProperties: {'Hover Time': '100ms'},
19 ));
20 
21 // Send events to the server
22 amplitude.flush()
23 }
24}

Configure the SDK

Name Description Default Value
apiKey String. The apiKey of your project. null
flushQueueSize int. SDK attempts to upload once unsent event count exceeds the event upload threshold or reaches flushIntervalMillis interval. 30
flushIntervalMillis int. The amount of time SDK attempts to upload the unsent events to the server or reaches the flushQueueSize threshold. The value is in milliseconds. 30000
instanceName String. The name of the instance. Instances with the same name shares storage and identity. For isolated storage and identity use a unique instanceName for each instance. $default_instance
optOut bool. Opt the user out of tracking. false
logLevel LogLevel The log level. LogLevel.off, LogLevel.error, LogLevel.warn, LogLevel.log, LogLevel.debug LogLevel.warn
minIdLength int. The minimum length for user id or device id. 5
partnerId int. The partner id for partner integration. null
flushMaxRetries int. Maximum retry times. 5
useBatch bool. Whether to use batch API. false
serverZone ServerZone. ServerZone.us or ServerZone.eu. The server zone to send to. Adjust server URL based on this config. ServerZone.us
serverUrl String. The server URL events upload to. https://api2.amplitude.com/2/httpapi
minTimeBetweenSessionsMillis int. The amount of time for session timeout. The value is in milliseconds. 300000
defaultTracking DefaultTrackingOptions. Options to control the default events tracking. Check Tracking default events.
trackingOptions TrackingOptions. Options to control the values tracked in SDK. enable

Configuration for Android and iOS

Name Description Default Value
enableCoppaControl bool. Whether to enable COPPA control for tracking options. false
flushEventsOnClose bool. Flush unsent events on app close. true
identifyBatchIntervalMillis int. The amount of time SDK attempts to batch intercepted identify events. The value is in milliseconds 30000
migrateLegacyData bool. Whether to migrate maintenance Android SDK and maintenance iOS SDK data (events, user/device ID). Learn more at the configuration section of the underlying Kotlin SDK and Swift SDK. true

Configuration for Android

Name Description Default Value
locationListening bool. Whether to enable Android location service. Learn more here. true
useAdvertisingIdForDeviceId bool. Whether to use advertising id as device id. Check here for required module and permission. false
useAppSetIdForDeviceId bool. Whether to use app set id as device id. Check here for required module and permission. false

Configure batching behavior

To support high-performance environments, the SDK sends events in batches. Every event logged by the track method is queued in memory. Events are flushed in batches in background. You can customize batch behavior with flushQueueSize and flushIntervalMillis. By default, the serverUrl will be https://api2.amplitude.com/2/httpapi. For customers who want to send large batches of data at a time, set useBatch to true to set setServerUrl to 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.

1final Amplitude analytics = Amplitude(Configuration(
2 apiKey: 'YOUR-API-KEY',
3 flushIntervalMillis: 50000,
4 flushQueueSize: 20,
5));

EU data residency

You can configure the server zone when initializing the client for sending data to Amplitude's EU servers. The SDK sends data based on the server zone if it's set.

Note

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.

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

Track

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

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

You can also optionally include event properties.

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

Refer to the BaseEvent interface for all available fields.

Identify

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

Note

If the Identify call is sent after the event, the results of operations will be visible immediately in the dashboard user's profile area, but it will not appear in chart result until another event is sent after the Identify call. So the identify call only affects events going forward. More details here.

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

1final Identify identify = Identify()
2 ..set('color', 'green')
3amplitude.identify(identify)

Track default events

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

  • Sessions
  • App lifecycles
  • Deep links (now only available on Android)
Name Type Default Value Description
config.defaultTracking.sessions Optional. bool true Enables session tracking. If 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.

See Tracking sessions for more information.
config.defaultTracking.appLifecycles Optional. bool false Enables application lifecycle events tracking. If value is true, Amplitude tracks application installed, application updated, application opened, and application backgrounded events.

Event properties tracked includes: [Amplitude] Version,
[Amplitude] Build,
[Amplitude] Previous Version, [Amplitude] Previous Build, [Amplitude] From Background

See Tracking application lifecycles for more information.
config.defaultTracking.deepLinks Optional. bool false Only available on Android. It enables deep link tracking. If value is true, Amplitude tracks deep link opened events.

Event properties tracked includes: [Amplitude] Link URL, [Amplitude] Link Referrer

See Tracking deep links for more information.

You can enable Amplitude to start tracking all events mentioned above, use the code sample below. Otherwise, you can omit the configuration to keep only session tracking enabled.

1Amplitude(
2 Configuration(
3 apiKey: 'YOUR-API-KEY',
4 defaultTracking: DefaultTrackingOptions.all()
5 )
6);

Warning

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

Similarly, you can prevent Amplitude from track default events with the following code sample:

1Amplitude(
2 Configuration(
3 apiKey: 'YOUR-API-KEY',
4 defaultTracking: DefaultTrackingOptions.none()
5 )
6);

You can also customize the tracking with DefaultTrackingOptions.

1Amplitude(
2 Configuration(
3 apiKey: 'YOUR-API-KEY',
4 defaultTracking: DefaultTrackingOptions(
5 sessions: false,
6 appLifecycles: true,
7 deepLinks: true,
8 )
9 )
10);

Track sessions

When you set configuration.defaultTracking.sessions: true, you instruct Amplitude to track session events.

1Amplitude(
2 Configuration(
3 apiKey: 'YOUR-API-KEY',
4 defaultTracking: DefaultTrackingOptions(
5 sessions: true,
6 )
7 )
8);

Track application lifecycles

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

1Amplitude(
2 Configuration(
3 apiKey: 'YOUR-API-KEY',
4 defaultTracking: DefaultTrackingOptions(
5 appLifecycles: true,
6 )
7 )
8);

After enabling this setting, Amplitude tracks the following events:

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

Note

Deep link tracking is available on Android.

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

1Amplitude(
2 Configuration(
3 apiKey: 'YOUR-API-KEY',
4 defaultTracking: DefaultTrackingOptions(
5 deepLinks: true,
6 )
7 )
8);

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

User groups

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

For example, you want to group your users based on what organization they're in by 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 set 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 to indicate that a user is in multiple groups.

Example

If Joe is in 'orgId' '15', then the groupName would be '15'.

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

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

1// set group with multiple group names
2amplitude.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 event being logged, and doesn't persist on the user unless you explicitly set it with setGroup.

1amplitude.track(BaseEvent('event type',
2 eventProperties: {'event property': 'event property value'},
3 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 and group name object parameter, and an Identify object that's applied to the group.

1final groupType = 'plan';
2final groupName = 'enterprise';
3 
4final identify = Identify().set('key', 'value');
5amplitude.groupIdentify(groupType, groupName, identify);

Track revenue

Amplitude can track revenue generated by a user. Revenue is tracked through distinct revenue objects, which have special fields that are used in Amplitude's Event Segmentation and Revenue LTV charts. This allows Amplitude to automatically display data relevant to revenue in the platform. Revenue objects support the following special properties, as well as user-defined properties through the eventProperties field.

1final revenue = Revenue()
2 ..productId = 'com.company.productId'
3 ..price = 3.99
4 ..quantity = 3;
5amplitude.revenue(revenue);
Name Description
productId Optional. String. An identifier for the product. Amplitude recommends something like the Google Play Store product ID. Defaults to null.
quantity  Required. Integer. The quantity of products purchased. Note: revenue = quantity * price. Defaults to 1
price  Required. Double. The price of the products purchased, and this can be negative. Note: revenue = quantity * price. Defaults to null.
revenueType Optional, but required for revenue verification. String. The revenue type (for example, tax, refund, income). Defaults to null.
receipt Optional. String. The receipt identifier of the revenue. For example, "123456". Defaults to null.
receiptSignature Optional, but required for revenue verification. String. Defaults to null.

Custom user ID

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

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

Custom device ID

You can assign a new device ID using deviceId. When setting a custom device ID, make sure the value is sufficiently unique. Amplitude recommends using a UUID.

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

Reset when a user logs out

reset is a shortcut to anonymize users after they log out, by:

  • setting userId to null
  • setting deviceId to a new value based on current configuration

With an empty userId and a completely new deviceId, the current user would appear as a brand new user in dashboard.

1amplitude.reset();
Was this page helpful?

Thanks for your feedback!

July 23rd, 2024

Need help? Contact Support

Visit Amplitude.com

Have a look at the Amplitude Blog

Learn more at Amplitude Academy

© 2024 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.