Instrument and configure Flutter SDK 4

このページはまだあなたの言語に翻訳されていません。 現在取り組んでいますので、後でもう一度確認してください。

After you send a first event, use this guide to track the events and properties your tracking plan needs, manage identity, choose Autocapture events, and control uploads. Every example assumes an amplitude instance created as in Initialize the SDK. For signatures and every option, go to the Flutter SDK 4 reference. For changes between versions, go to the Flutter SDK 4 release notes.

Track events

Track a custom event

Pass a BaseEvent to track(). Add event properties as a map.

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

To set HTTP V2 fields on one event, such as userId or timestamp, pass them to BaseEvent or as a second EventOptions argument. They apply to that event only.

Set user properties

Build an Identify object with one operation per property, then pass it to identify(). The SDK sends it as a $identify event.

dart
final identify = Identify()
  ..set('color', 'green')
  ..setOnce('signup_source', 'ad')
  ..add('karma', 1);
await amplitude.identify(identify);

User property changes apply to events you track afterward. The user's profile shows them right away, but charts reflect them only on events tracked after the identify() call. For details, go to User properties and events.

Clear all user properties

clearAll() removes every user property from the user. You can't undo it. The SDK ignores any other operation in the same Identify object.

dart
await amplitude.identify(Identify()..clearAll());

Assign a user to a group

Groups let you analyze users by an entity they belong to, such as an organization. Each group has a type, such as orgId, and a name, such as 15. For example, if Joe is in orgId 10 and Sue is in orgId 15, you can count an event by organization in Event Segmentation. Groups require the Accounts add-on.

setGroup() assigns the current user to a group and also sets groupType: groupName as a user property, replacing any earlier value for that type. Pass a list to put the user in several groups of one type.

dart
await amplitude.setGroup('orgId', '15');
await amplitude.setGroup('sport', ['tennis', 'soccer']);

To assign a group to one event only, set groups on the event. The group doesn't persist on the user.

dart
await amplitude.track(BaseEvent(
  'Report Exported',
  eventProperties: {'format': 'csv'},
  groups: {'orgId': '15'},
));

Set group properties

groupIdentify() sets properties on a group rather than on a user. The changes apply to events tracked afterward.

dart
await amplitude.groupIdentify(
  'plan',
  'enterprise',
  Identify()..set('seats', 50),
);

Track revenue

Build a Revenue object and pass it to revenue(). The SDK sends a revenue_amount event that Revenue LTV and Event Segmentation charts read. price is required. Without it, the SDK drops the call without logging anything. quantity defaults to 1.

dart
final revenue = Revenue()
  ..productId = 'com.example.coins'
  ..price = 3.99
  ..quantity = 3
  ..revenueType = 'purchase'
  ..revenueCurrency = 'USD'
  ..properties = {'store': 'app_store'};
await amplitude.revenue(revenue);

For revenue verification, also set receipt and receiptSig.

Send events to more than one project

Create one instance per project, and give each a distinct instanceName. Instances with different names keep separate storage, identity, and queues. Requires 4.3.0 or later.

dart
final amplitude = Amplitude(Configuration(
  apiKey: 'AMPLITUDE_API_KEY',
  instanceName: 'secondary',
));
await amplitude.isBuilt;
await amplitude.track(BaseEvent('Song Played'));

Identity and sessions

How the SDK chooses identifiers

Every event needs a user ID or a device ID. The platform SDK sets them as follows:

  • Device ID: the stored value from an earlier launch. On a first launch, the platform SDK generates one. On Android and web, the deviceId option overrides it. On Android, useAdvertisingIdForDeviceId or useAppSetIdForDeviceId can supply it.
  • User ID: null until you call setUserId(). On web, the userId option sets it at startup. The user ID persists across launches.

Amplitude removes an ID shorter than five characters (or minIdLength) from the event. Amplitude rejects an event left with neither ID.

Set the user ID

Call setUserId() when a user signs in. Later events carry the ID.

dart
await amplitude.setUserId('user-12345');
await amplitude.track(BaseEvent('Signed In'));

Reset identity when a user signs out

reset() sets the user ID to null and generates a new device ID, so Amplitude treats later events as a new anonymous user. The signed-out user's history stays with their user ID. A typical sign-out flow tracks an event, uploads it, then resets:

dart
await amplitude.track(BaseEvent('User Logged Out'));
await amplitude.flush();
await amplitude.reset();

reset() doesn't clear user properties Amplitude already stored. To remove them, send Identify()..clearAll() before you reset, while the user is still identified.

Set the device ID

setDeviceId() replaces the device ID. Use a value unique to the device, such as a UUID. To use the same device ID for Analytics and Flutter Session Replay, go to Connect Session Replay.

dart
await amplitude.setDeviceId('8f9a1c52-6d1e-4b8e-9e2a-3c7d5f0b1a24');
await amplitude.track(BaseEvent('Device Linked'));

Read the current identity

getUserId(), getDeviceId(), and getSessionId() return the values the platform SDK uses now. getUserId() and getDeviceId() require 4.1.0 or later. getSessionId() requires 4.2.0 or later.

dart
final userId = await amplitude.getUserId();
final deviceId = await amplitude.getDeviceId();
final sessionId = await amplitude.getSessionId();

How sessions work

A session starts with the first event and ends after a period with no events. The session ID is the start time, as a Unix timestamp in milliseconds. The inactivity timeout is 5 minutes on iOS, macOS, and Android, and 30 minutes on web. Set minTimeBetweenSessionsMillis to use one timeout on every platform:

dart
final amplitude = Amplitude(Configuration(
  apiKey: 'AMPLITUDE_API_KEY',
  minTimeBetweenSessionsMillis: 10 * 60 * 1000, // 10 minutes
));

With sessions Autocapture on (the default), the SDK also tracks session start and end events. With it off, events still carry a session ID.

Opt users out of tracking

setOptOut(true) stops tracking and uploads for the instance. setOptOut(false) resumes them. To start opted out, set optOut: true in Configuration. iOS and Android support requires 4.5.0 or later.

dart
await amplitude.setOptOut(true);

Limit the data the SDK collects

Turn off device and location fields with TrackingOptions. For apps directed at children, enableCoppaControl: true turns off the fields COPPA restricts on iOS, macOS, and Android.

dart
import 'package:amplitude_flutter/tracking_options.dart';

final amplitude = Amplitude(Configuration(
  apiKey: 'AMPLITUDE_API_KEY',
  trackingOptions: TrackingOptions(ipAddress: false, city: false, carrier: false),
));
await amplitude.isBuilt;
await amplitude.track(BaseEvent('Song Played'));

On Android, setting latLag: false has no effect in 4.8.2. To stop location collection there, set locationListening: false.

Autocapture

Autocapture tracks events without code. Configure it with the autocapture option.

Choose a starting point

dart
import 'package:amplitude_flutter/autocapture/autocapture.dart';

final amplitude = Amplitude(Configuration(
  apiKey: 'AMPLITUDE_API_KEY',
  autocapture: AutocaptureOptions(
    sessions: true,
    appLifecycles: true,
    deepLinks: true,
    screenViews: true,
  ),
));

AutocaptureEnabled() includes future features

When a later SDK version adds an Autocapture feature, AutocaptureEnabled() turns it on after you upgrade. To keep a fixed set, list features in AutocaptureOptions.

Migrate from defaultTracking

defaultTracking and DefaultTrackingOptions are deprecated since 4.6.0. Existing code keeps working: when you pass defaultTracking and no autocapture, the SDK converts it. When you pass both, autocapture wins. Replace defaultTracking: DefaultTrackingOptions(appLifecycles: true) with autocapture: AutocaptureOptions(appLifecycles: true). For the field mapping, go to DefaultTrackingOptions.

Features and events

screenViews, formInteractions, fileDownloads, elementInteractions, and pageUrlEnrichment require 4.7.0 or later. Before 4.7.0, pageViews was on by default.

App lifecycles

With appLifecycles: true, the SDK tracks these events on iOS, macOS, and Android:

  • [Amplitude] Application Installed: the first launch after installation.
  • [Amplitude] Application Updated: the first launch after an update.
  • [Amplitude] Application Opened: a launch, or a return to the foreground.
  • [Amplitude] Application Backgrounded: the app goes to the background.

The events carry [Amplitude] Version, [Amplitude] Build, [Amplitude] Previous Version, [Amplitude] Previous Build, and [Amplitude] From Background.

With deepLinks: true, the SDK tracks [Amplitude] Deep Link Opened on Android, with [Amplitude] Link URL and [Amplitude] Link Referrer. iOS and macOS ignore the option.

Screen views

A Flutter app runs in one native view, so the native SDKs can't see Flutter route changes. To track screens, turn on screenViews and add AmplitudeNavigatorObserver to your navigator. You need both. Requires 4.7.0 or later.

dart
import 'package:flutter/material.dart';
import 'package:amplitude_flutter/autocapture/autocapture.dart';
import 'package:amplitude_flutter/observers/amplitude_navigator_observer.dart';

final amplitude = Amplitude(Configuration(
  apiKey: 'AMPLITUDE_API_KEY',
  autocapture: AutocaptureOptions(screenViews: true),
));

final app = MaterialApp(
  navigatorObservers: [AmplitudeNavigatorObserver(amplitude)],
  routes: {'/': (context) => const Placeholder()},
);

The observer tracks [Amplitude] Screen Viewed with [Amplitude] Screen Name when the navigator pushes or replaces a page route, and when it pops a page route (for the screen underneath). Dialogs and bottom sheets don't count as screens.

Screen names come from RouteSettings.name, so name your routes with named routes, RouteSettings(name: ...), or a router such as go_router. The observer skips routes with no name, and debug builds print why. To derive names another way, pass nameExtractor. To choose which routes count, pass routeFilter.

On web, screen views and pageViews are independent. A Flutter route change doesn't always change the browser URL, so the observer catches navigation that pageViews misses. If you turn on both, a navigation that changes the URL records both events.

Marketing attribution

On web, attribution is on by default. It reads UTM parameters, referrers, and click IDs and sets them as user properties. Configure it with AttributionOptions, or turn it off with AttributionDisabled().

dart
import 'package:amplitude_flutter/autocapture/autocapture.dart';
import 'package:amplitude_flutter/autocapture/attribution.dart';

final amplitude = Amplitude(Configuration(
  apiKey: 'AMPLITUDE_API_KEY',
  autocapture: AutocaptureOptions(
    attribution: AttributionOptions(
      excludeReferrers: ['example.com'],
      initialEmptyValue: 'NONE',
      resetSessionOnNewCampaign: true,
    ),
  ),
));

Page views

On web, pageViews tracks [Amplitude] Page Viewed when the browser URL changes. It's off by default so a navigation doesn't count as both a screen view and a page view. Turn it on with PageViewsOptions.

dart
import 'package:amplitude_flutter/autocapture/autocapture.dart';
import 'package:amplitude_flutter/autocapture/page_views.dart';

final amplitude = Amplitude(Configuration(
  apiKey: 'AMPLITUDE_API_KEY',
  autocapture: AutocaptureOptions(
    pageViews: PageViewsOptions(trackHistoryChanges: 'pathOnly'),
  ),
));
await amplitude.isBuilt;

Flutter web DOM capture

elementInteractions, formInteractions, and fileDownloads rely on the Browser SDK, which sees only real DOM elements. With Flutter's default CanvasKit renderer, Flutter draws your UI on a <canvas>, so the Browser SDK can only see Flutter's accessibility semantics tree.

Semantics has a cost on Flutter web

These options work only when you turn on Flutter's semantics tree for the whole app, for example with SemanticsBinding.instance.ensureSemantics() early in main(). That adds runtime and memory overhead and has side effects that Flutter documents. Don't turn it on only for Amplitude unless you accept that tradeoff. Screen views don't need it.

Element interactions

elementInteractions tracks [Amplitude] Element Clicked and [Amplitude] Element Changed. Flutter renders widgets as <flt-semantics> nodes with ARIA roles, so the Browser SDK's tag-based default selectors don't match them. ElementInteractionsOptions() and ElementInteractionsEnabled() default cssSelectorAllowlist to a list that adds Flutter's roles, such as [role="button"]. Requires Browser SDK 2.10.0 or later.

dart
import 'package:amplitude_flutter/autocapture/autocapture.dart';
import 'package:amplitude_flutter/autocapture/element_interactions.dart';

final amplitude = Amplitude(Configuration(
  apiKey: 'AMPLITUDE_API_KEY',
  autocapture: AutocaptureOptions(
    elementInteractions: ElementInteractionsOptions(
      cssSelectorAllowlist: ['button', '[role="button"]', '[role="link"]'],
      dataAttributePrefix: 'data-amp-track-',
    ),
  ),
));

Form interactions and file downloads

formInteractions: true tracks [Amplitude] Form Started and [Amplitude] Form Submitted. It sees only text fields rendered as real <input> and <form> nodes. fileDownloads: true tracks [Amplitude] File Downloaded for <a download> links, which Flutter web apps rarely render.

Page URL enrichment

On web, pageUrlEnrichment: true adds page URL properties, such as the previous page and page type, to events. Turn it on with screenViews or pageViews to enrich navigation events. Requires Browser SDK 2.29.0 or later. Older versions ignore it.

Data delivery

How the SDK uploads events

track() hands the event to the platform SDK, which stores it and uploads queued events in batches. An upload starts when flushQueueSize events (default 30) are in the queue, or every flushIntervalMillis (default 30 seconds), whichever comes first. On iOS, macOS, and Android, the SDK also uploads when the app goes to the background, unless you set flushEventsOnClose: false. Events the SDK can't upload stay stored and retry later, up to flushMaxRetries (default 5) attempts per cycle.

Flush events now

flush() starts an upload of queued events. It returns after starting the upload, not after Amplitude responds. Call it before a moment that might end the session, such as sign-out.

dart
await amplitude.track(BaseEvent('Checkout Completed'));
await amplitude.flush();

Tune upload batching

Lower flushIntervalMillis to see events sooner during development. Raise flushQueueSize and flushIntervalMillis to send fewer, larger requests.

dart
final amplitude = Amplitude(Configuration(
  apiKey: 'AMPLITUDE_API_KEY',
  flushIntervalMillis: 50000,
  flushQueueSize: 20,
));

Upload large batches

useBatch: true sends events to the Batch Event Upload API (https://api2.amplitude.com/batch) instead of HTTP V2. It accepts larger payloads. Batching thresholds stay the same.

Choose a data region

Projects in Amplitude's EU data center need serverZone: ServerZone.eu and an API key from the EU project. The SDK then sends to api.eu.amplitude.com.

dart
import 'package:amplitude_flutter/constants.dart';

final amplitude = Amplitude(Configuration(
  apiKey: 'AMPLITUDE_API_KEY',
  serverZone: ServerZone.eu,
));
await amplitude.isBuilt;

Send events through a proxy

Set serverUrl to your proxy's URL. It overrides serverZone. Your proxy must forward the request body to Amplitude's HTTP V2 endpoint (or /batch when useBatch is on) unchanged. On iOS, macOS, and Android, the SDK doesn't gzip bodies sent to a custom serverUrl.

dart
final amplitude = Amplitude(Configuration(
  apiKey: 'AMPLITUDE_API_KEY',
  serverUrl: 'https://analytics-proxy.example.com/2/httpapi',
));

Configure web storage and transport

On web, these options pass through to Browser SDK 2:

  • identityStorage: where to keep identity. Default 'cookie'. Use 'localStorage' when the browser blocks cookies.
  • cookieOptions: cookie domain, expiration, SameSite, and Secure. Refer to CookieOptions.
  • transport: 'fetch' (default), 'xhr', or 'beacon'.
  • appVersion: an app version to send with every event.

これは役に立ちましたか?

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.

このページでは