Flutter SDK 4 reference
このページはまだあなたの言語に翻訳されていません。 現在取り組んでいますので、後でもう一度確認してください。
This reference documents every public export of amplitude_flutter and every Configuration option, verified against version 4.8.2. For the release that added or changed a feature, go to the Flutter SDK 4 release notes.
The package has no single entry file. Import each library you use:
import 'package:amplitude_flutter/amplitude.dart';
import 'package:amplitude_flutter/configuration.dart';
import 'package:amplitude_flutter/constants.dart'; // LogLevel, ServerZone
import 'package:amplitude_flutter/events/base_event.dart';
import 'package:amplitude_flutter/events/event_options.dart';
import 'package:amplitude_flutter/events/identify.dart';
import 'package:amplitude_flutter/events/revenue.dart';
import 'package:amplitude_flutter/autocapture/autocapture.dart';
import 'package:amplitude_flutter/observers/amplitude_navigator_observer.dart';
Each Amplitude object is an instance. Instances with the same instanceName share storage and identity on the native side, so create one per project and reuse it.
Return values
Every method returns a Future. The future completes when the native SDK (or the Browser SDK on web) accepts the call, not when Amplitude receives the event. No method returns an upload result. To check delivery, go to Verify events.
Setup
Amplitude
Creates an instance and starts initializing the platform SDK.
Amplitude(Configuration configuration, [MethodChannel? methodChannel])
| Parameter | Type | Description |
|---|---|---|
configuration | Configuration | Refer to Configuration options. You can't change it after construction, except optOut through setOptOut(). |
methodChannel | MethodChannel | Optional. For tests only. Defaults to the amplitude_flutter channel. |
final amplitude = Amplitude(Configuration(apiKey: 'AMPLITUDE_API_KEY'));
await amplitude.isBuilt;
await amplitude.track(BaseEvent('Song Played'));
isBuilt
A Future<bool> that completes when the platform SDK finishes initializing.
late Future<bool> isBuilt;
It resolves to true on success and to false when the platform reports an initialization error. On Android it waits for the native SDK's build. On iOS and macOS it waits for the Swift SDK's setup. On web it waits for the Browser SDK's init() and resolves to false after 10 seconds if that never settles, for example when the SDK script is blocked. Calls you make before it completes still go through. Changed in 4.8.0: earlier versions resolved before the platform finished.
flush
Asks the platform SDK to upload queued events now. It returns after starting the upload, not after the upload finishes.
Future<void> flush()
await amplitude.track(BaseEvent('Checkout Started'));
await amplitude.flush();
Tracking
track
Queues an event.
Future<void> track(BaseEvent event, [EventOptions? options])
| Parameter | Type | Description |
|---|---|---|
event | BaseEvent | The event. Refer to BaseEvent. |
options | EventOptions | Optional. Fields to set on this event. They overwrite the same fields on event. |
import 'package:amplitude_flutter/events/event_options.dart';
await amplitude.track(
BaseEvent('Song Played', eventProperties: {'title': 'Happy Birthday'}),
EventOptions(userId: 'user-12345'),
);
identify
Sends a $identify event that updates user properties. The changes apply to events you track afterward, not to earlier events.
Future<void> identify(Identify identify, [EventOptions? options])
| Parameter | Type | Description |
|---|---|---|
identify | Identify | The user property operations. Refer to Identify. |
options | EventOptions | Optional. If it sets userId or deviceId, the SDK also calls setUserId() or setDeviceId() with them. |
final identify = Identify()
..set('plan', 'pro')
..add('logins', 1);
await amplitude.identify(identify);
setGroup
Assigns the current user to one or more groups, and sets the group as a user property.
Future<void> setGroup(String groupType, dynamic groupName, [EventOptions? options])
| Parameter | Type | Description |
|---|---|---|
groupType | String | The group category, such as orgId. |
groupName | String or List<String> | One group, or a list for a user in several groups. The SDK silently ignores any other type. |
options | EventOptions | Optional. Fields to set on the $identify event. |
await amplitude.setGroup('orgId', '15');
await amplitude.setGroup('sport', ['tennis', 'soccer']);
groupIdentify
Sends a $groupidentify event that updates the properties of one group.
Future<void> groupIdentify(String groupType, String groupName, Identify identify, [EventOptions? options])
| Parameter | Type | Description |
|---|---|---|
groupType | String | The group category, such as plan. |
groupName | String | The group, such as enterprise. |
identify | Identify | The group property operations. |
options | EventOptions | Optional. Fields to set on the event. |
await amplitude.groupIdentify('plan', 'enterprise', Identify()..set('seats', 50));
revenue
Sends a revenue_amount event built from a Revenue object. If price is null, the SDK drops the call without an error.
Future<void> revenue(Revenue revenue, [EventOptions? options])
| Parameter | Type | Description |
|---|---|---|
revenue | Revenue | Refer to Revenue. |
options | EventOptions | Optional. Fields to set on the event. |
final revenue = Revenue()
..productId = 'com.example.coins'
..price = 3.99
..quantity = 3;
await amplitude.revenue(revenue);
Identity
getUserId and setUserId
Read or set the user ID. Pass null to clear it. getUserId() requires 4.1.0 or later.
Future<String?> getUserId()
Future<void> setUserId(String? userId)
await amplitude.setUserId('user-12345');
final userId = await amplitude.getUserId();
getDeviceId and setDeviceId
Read or set the device ID. Use a unique value, such as a UUID. getDeviceId() requires 4.1.0 or later. On Android it waits for the native SDK to finish building before it returns, and returns null if the build fails.
Future<String?> getDeviceId()
Future<void> setDeviceId(String? deviceId)
await amplitude.setDeviceId('8f9a1c52-6d1e-4b8e-9e2a-3c7d5f0b1a24');
final deviceId = await amplitude.getDeviceId();
reset
Sets the user ID to null and generates a new device ID. It doesn't clear user properties that Amplitude already stored.
Future<void> reset()
Sessions
getSessionId
Returns the current session ID, a Unix timestamp in milliseconds. Requires 4.2.0 or later. On Android it waits for the native SDK to restore the stored session first. On a new install, it can return -1 until the first session starts.
Future<int?> getSessionId()
final sessionId = await amplitude.getSessionId();
Privacy
setOptOut
Stops (true) or resumes (false) tracking and uploads for this instance. iOS and Android support requires 4.5.0 or later.
Future<void> setOptOut(bool enabled)
await amplitude.setOptOut(true);
await amplitude.track(BaseEvent('Not Sent'));
BaseEvent
BaseEvent is the event you pass to track(). It extends EventOptions, so it accepts every EventOptions field as a named constructor argument.
BaseEvent(String eventType, {Map<String, dynamic>? eventProperties, Map<String, dynamic>? userProperties, Map<String, dynamic>? groups, Map<String, dynamic>? groupProperties, /* EventOptions fields */})
| Field | Type | Description |
|---|---|---|
eventType | String | Required. The event name. |
eventProperties | Map<String, dynamic> | Properties of this event. |
userProperties | Map<String, dynamic> | User property operations to send with this event. |
groups | Map<String, dynamic> | Groups for this event only. They don't persist on the user. |
groupProperties | Map<String, dynamic> | Group property operations. |
EventOptions
EventOptions holds the event fields of the HTTP V2 API. Every field is optional. Set a field to override the value the platform SDK fills in.
| Field | Type | HTTP V2 key |
|---|---|---|
userId, deviceId | String | user_id, device_id |
timestamp, eventId, sessionId | int | time, event_id, session_id |
insertId | String | insert_id |
locationLat, locationLng | double | location_lat, location_lng |
appVersion, versionName | String | app_version, version_name |
platform, osName, osVersion | String | platform, os_name, os_version |
deviceBrand, deviceManufacturer, deviceModel | String | device_brand, device_manufacturer, device_model |
carrier, country, region, city, dma | String | Same names |
idfa, idfv, adid, appSetId, androidId | String | idfa, idfv, adid, app_set_id, android_id |
language, library, ip, partnerId | String | language, library, ip, partner_id |
revenue, price | double | revenue, price |
quantity | int | quantity |
productId, revenueType, currency | String | product_id, revenue_type, currency |
plan | Plan | plan. Fields: branch, source, version, versionId. |
ingestionMetadata | IngestionMetadata | ingestion_metadata. Fields: sourceName, sourceVersion. |
extra | Map<String, dynamic> | Extra data for plugins. |
Identify class
Identify builds user or group property operations for identify() and groupIdentify(). Each method returns the same object, so calls chain with ... The SDK silently ignores an operation in any of these cases: the property name is empty, the value is null, the property already has an operation in this object, or the object already contains clearAll().
| Method | Operation | Description |
|---|---|---|
set(property, value) | $set | Sets the value. |
setOnce(property, value) | $setOnce | Sets the value if the property has none. |
add(property, value) | $add | Adds a number to a numeric value. |
append(property, value) | $append | Appends to a list. |
prepend(property, value) | $prepend | Prepends to a list. |
preInsert(property, value) | $preInsert | Prepends values not already in the list. |
remove(property, value) | $remove | Removes values from a list. |
unset(property) | $unset | Removes the property. |
clearAll() | $clearAll | Removes every user property. You can't undo it. |
The Flutter SDK has no postInsert() method.
Revenue class
Revenue describes one purchase. revenue() sends it as a revenue_amount event with $-prefixed event properties.
| Field | Type | Default | Event property | Description |
|---|---|---|---|---|
price | double | null | $price | Required. Price of one item. Can be negative. |
quantity | int | 1 | $quantity | Number of items. |
productId | String | null | $productId | Product identifier. |
revenue | double | null | $revenue | Total revenue. When omitted, Amplitude calculates price × quantity. |
revenueCurrency | String | null | $currency | Currency code, such as USD. |
revenueType | String | null | $revenueType | Type, such as purchase or refund. Required for revenue verification. |
receipt | String | null | $receipt | Receipt identifier. |
receiptSig | String | null | $receiptSig | Receipt signature. Required for revenue verification. |
properties | Map<String, dynamic> | null | Same keys | Other event properties to send with the revenue event. |
AmplitudeNavigatorObserver
A NavigatorObserver that tracks [Amplitude] Screen Viewed with the event property [Amplitude] Screen Name when the navigator pushes, replaces, or pops a route. It does nothing unless the instance's autocapture enables screenViews. Requires 4.7.0 or later.
AmplitudeNavigatorObserver(Amplitude amplitude, {ScreenNameExtractor nameExtractor = defaultScreenNameExtractor, bool Function(Route<dynamic>? route) routeFilter = defaultRouteFilter})
| Parameter | Type | Description |
|---|---|---|
amplitude | Amplitude | The instance to track with. |
nameExtractor | String? Function(RouteSettings) | Optional. Returns the screen name. Return null or '' to skip the route. Default: settings.name. |
routeFilter | bool Function(Route<dynamic>?) | Optional. Returns whether to track the route. Default: only PageRoute, so the observer skips dialogs and bottom sheets. |
The library also exports screenViewedEventType ('[Amplitude] Screen Viewed'), screenNameProperty ('[Amplitude] Screen Name'), defaultScreenNameExtractor, and defaultRouteFilter. Exceptions thrown by nameExtractor, routeFilter, or track() never reach the navigator. Debug builds print them.
import 'package:flutter/material.dart';
import 'package:amplitude_flutter/observers/amplitude_navigator_observer.dart';
final observer = AmplitudeNavigatorObserver(
amplitude,
nameExtractor: (settings) => settings.name?.replaceAll('/', ' ').trim(),
);
final app = MaterialApp(navigatorObservers: [observer]);
Configuration options
This section lists every field of Configuration as of Flutter SDK 4.8.2. Only apiKey is required. Each table names the platforms that read the option. Other platforms ignore it.
Configuration({required String apiKey, /* options below */})
General
| Option | Type | Default | Platforms | Description |
|---|---|---|---|---|
apiKey | String | Required | All | Your Amplitude project API key. |
instanceName | String | '$default_instance' | All | Name of this instance. Instances with the same name share storage and identity. Requires 4.3.0 or later. |
logLevel | LogLevel | LogLevel.warn | All | off, error, warn, log, or debug. log maps to INFO on Android and Verbose on web. |
optOut | bool | false | All | When true, the SDK doesn't track or upload events. Change it later with setOptOut(). |
minIdLength | int? | null (Amplitude enforces 5) | All | Minimum length for user_id and device_id. The SDK sends it with each upload, and Amplitude applies it. |
partnerId | String? | null | All | Partner identifier, for partners who build an event ingestion integration. |
minTimeBetweenSessionsMillis | int | 300000 on iOS, macOS, and Android; 1800000 on web | All | Inactivity, in milliseconds, after which the next event starts a new session. Setting it applies the same value on every platform. |
trackingOptions | TrackingOptions | TrackingOptions() (everything on) | All | Which device and location fields the SDK collects. Refer to TrackingOptions. |
autocapture | Autocapture | AutocaptureOptions() | All | Which events the SDK collects without code. Refer to Autocapture options. |
defaultTracking | DefaultTrackingOptions | DefaultTrackingOptions() | All | Deprecated. Use autocapture. Used only when you don't set autocapture. Refer to DefaultTrackingOptions. |
Delivery
| Option | Type | Default | Platforms | Description |
|---|---|---|---|---|
flushQueueSize | int | 30 | All | Maximum number of events in one upload request. |
flushIntervalMillis | int | 30000 | All | Milliseconds between scheduled uploads. |
flushMaxRetries | int | 5 | All | Maximum upload attempts for errors the SDK can retry. |
serverZone | ServerZone | ServerZone.us | All | ServerZone.us or ServerZone.eu. Use eu for projects in Amplitude's EU data center. |
serverUrl | String? | null (chosen from serverZone and useBatch) | All | Upload URL. Set it to send events through a proxy. Overrides serverZone. |
useBatch | bool | false | All | Upload to the Batch Event Upload API instead of HTTP V2. |
flushEventsOnClose | bool | true | iOS, macOS, Android | Upload queued events when the app closes or goes to the background. |
identifyBatchIntervalMillis | int | 30000 | iOS, macOS, Android | Milliseconds the native SDK waits to batch intercepted identify events into one upload. |
transport | String? | 'fetch' | Web | 'fetch', 'xhr', or 'beacon'. |
Identity and privacy
| Option | Type | Default | Platforms | Description |
|---|---|---|---|---|
deviceId | String? | null | Android, web | Device ID to use. When null, the SDK uses the stored ID or generates one. iOS and macOS ignore this option. Call setDeviceId() there. |
userId | String? | null | Web | User ID to use from the start. On other platforms, call setUserId(). |
enableCoppaControl | bool | false | iOS, macOS, Android | Turns off collection of city and IP address on every native platform. Also turns off ADID, latitude, and longitude on Android, and IDFA and IDFV on iOS and macOS. |
migrateLegacyData | bool | true | iOS, macOS, Android | Moves events and identity stored by the maintenance iOS and Android SDKs into this SDK. |
locationListening | bool | true | Android | Collects latitude and longitude when your app has location permission. |
useAdvertisingIdForDeviceId | bool | false | Android | Uses the advertising ID as the device ID. Requires the Google Play Services Ads Identifier module. |
useAppSetIdForDeviceId | bool | false | Android | Uses the app set ID as the device ID. Requires the Google Play Services App Set module. |
identityStorage | String | 'cookie' | Web | Where to store identity: 'cookie', 'localStorage', 'sessionStorage', or 'none'. |
cookieOptions | CookieOptions | CookieOptions() | Web | Refer to CookieOptions. |
appVersion | String? | null | Web | App version to send with every event, such as 1.0.0. |
fetchRemoteConfig | bool | false | Web | Whether the Browser SDK fetches remote configuration. Flutter always passes this value, so the Browser SDK's own default doesn't apply. |
CookieOptions
| Option | Type | Default | Description |
|---|---|---|---|
domain | String | '' | Cookie domain. Empty means the Browser SDK picks the top-level domain. |
expiration | int | 365 | Days until the cookies expire. |
sameSite | String | 'Lax' | The SameSite attribute. |
secure | bool | false | Whether to set the Secure attribute. |
upgrade | bool | true | When true, the Browser SDK deletes cookies the maintenance JavaScript SDK created, after it reads them. |
TrackingOptions
Every field defaults to true. Set a field to false to stop collecting it.
| Field | Platforms |
|---|---|
ipAddress, language, platform | All |
region, dma, country, city, carrier | iOS, macOS, Android |
deviceModel, deviceManufacturer, osVersion, osName, versionName | iOS, macOS, Android |
adid, appSetId, deviceBrand, apiLevel | Android |
latLag | None. Android reads a differently named key, so setting it has no effect in 4.8.2. Use locationListening: false to stop location collection. |
idfv | iOS, macOS |
Autocapture options
autocapture takes one of three classes:
| Value | Result |
|---|---|
AutocaptureOptions() | Default. Pick each feature. Its defaults turn on sessions and web attribution only. |
AutocaptureEnabled() | Every feature the Flutter SDK exposes, including ones added in later versions. |
AutocaptureDisabled() | No autocapture. |
AutocaptureOptions
| Option | Type | Default | Platforms | Description |
|---|---|---|---|---|
sessions | bool | true | All | Session start and end events. |
appLifecycles | bool | false | iOS, macOS, Android | Application installed, updated, opened, and backgrounded events. |
deepLinks | bool | false | Android | [Amplitude] Deep Link Opened events. |
screenViews | bool | false | All | Turns on AmplitudeNavigatorObserver. Requires 4.7.0 or later. |
attribution | Attribution | AttributionOptions() | Web | Marketing attribution. AttributionOptions, AttributionEnabled(), or AttributionDisabled(). |
pageViews | PageViews | PageViewsDisabled() | Web | URL-based page view events. PageViewsOptions, PageViewsEnabled(), or PageViewsDisabled(). Default changed in 4.7.0. |
elementInteractions | ElementInteractions | ElementInteractionsDisabled() | Web | Click tracking. ElementInteractionsOptions, ElementInteractionsEnabled(), or ElementInteractionsDisabled(). Requires 4.7.0 or later. |
formInteractions | bool | false | Web | [Amplitude] Form Started and [Amplitude] Form Submitted events. Requires 4.7.0 or later. |
fileDownloads | bool | false | Web | [Amplitude] File Downloaded events. Requires 4.7.0 or later. |
pageUrlEnrichment | bool | false | Web | Adds page URL properties to events. Needs Browser SDK 2.29.0 or later. Requires 4.7.0 or later. |
AttributionOptions
| Option | Type | Default | Description |
|---|---|---|---|
excludeReferrers | List<String>? | null | Referrer domains that don't count as a traffic source. |
initialEmptyValue | String? | 'EMPTY' | Value for first-touch campaign properties that have no value. |
resetSessionOnNewCampaign | bool? | false | Starts a new session when any campaign parameter changes. |
PageViewsOptions
| Option | Type | Default | Description |
|---|---|---|---|
trackHistoryChanges | String? | 'all' | 'all' tracks every URL change, including the fragment. 'pathOnly' tracks path changes only. |
eventType | String? | '' | Event name for page views. Empty means [Amplitude] Page Viewed. |
PageViewsEnabled() turns on page views with the Browser SDK's defaults.
ElementInteractionsOptions
| Option | Type | Default | Description |
|---|---|---|---|
cssSelectorAllowlist | List<String>? | defaultCssSelectorAllowlist | CSS selectors of elements to track. Pass null to use the Browser SDK's own default, which doesn't match Flutter widgets. |
actionClickAllowlist | List<String>? | null | Selectors whose clicks count when they change the page or the DOM. |
dataAttributePrefix | String? | null (Browser SDK uses 'data-amp-track-') | Prefix of data-* attributes to send as event properties. |
pageUrlAllowlist | List<String>? | null | Page URLs where the SDK tracks clicks. Strings only. Regular expressions can't cross the platform channel. |
ElementInteractionsOptions.defaultCssSelectorAllowlist is a, button, input, select, textarea, label, [role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="switch"], [role="tab"], [role="menuitem"], and [role="textbox"]. ElementInteractionsEnabled() uses the same list.
DefaultTrackingOptions
Deprecated since 4.6.0. Use autocapture. When you pass defaultTracking and no autocapture, the SDK converts it to AutocaptureOptions. When you pass both, autocapture wins.
| Field | Default | Converts to |
|---|---|---|
sessions | true | sessions |
appLifecycles | false | appLifecycles |
deepLinks | false | deepLinks |
attribution | true | attribution: AttributionOptions() or AttributionDisabled() |
pageViews | true | pageViews: PageViewsOptions() or PageViewsDisabled() |
formInteractions | false | formInteractions. Default changed in 4.7.0 |
fileDownloads | false | fileDownloads. Default changed in 4.7.0 |
DefaultTrackingOptions.all() turns every field on. DefaultTrackingOptions.none() turns every field off.
これは役に立ちましたか?
For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.