### Initialization and Setup Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/COMPLETION_REPORT.md Guides on initializing the Amplitude SDK, configuring settings, and best practices for different platforms. ```APIDOC ## Quick Start ### Description Provides a minimal setup guide requiring only three lines of code. ### Example Includes a verification example to confirm successful setup. ## Step-by-Step Initialization ### Steps 1. **Imports**: Import necessary Amplitude SDK modules. 2. **Create Configuration**: Instantiate the `Configuration` object with desired settings. 3. **Initialize Instance**: Create an Amplitude client instance using the configuration. 4. **Wait for Initialization**: Ensure the SDK is fully initialized before use. 5. **Use Amplitude**: Begin tracking events and user properties. ## Full Examples ### Patterns - Dependency Injection pattern. - Provider pattern integration. - Service Locator pattern. ## Configuration Presets ### Options - Development configuration. - Production configuration. - EU data residency settings. - High-volume tracking configuration. - Privacy-focused configuration. ## Platform-Specific Setup ### Platforms - iOS/Android setup instructions. - Web setup instructions. ### Requirements - Details on necessary requirements and permissions for each platform. ## Error Handling ### Scenarios - Handling initialization failures. - Managing invalid API keys. - Addressing network issues during initialization. ## Lifecycle Documentation ### Stages - Configuration creation. - Instance creation. - Native platform initialization. - Initialization completion. ## Testing and Debugging ### Tools - Enabling and using debug logging. - Verifying configuration settings. - Confirming successful initialization. ## Best Practices ### Recommendations - Initialize the SDK early in the application lifecycle. - Employ the single instance pattern. - Properly handle asynchronous operations. - Implement robust user ID management. - Ensure a complete logout flow. ## Troubleshooting Table ### Guide Provides solutions for common issues encountered during setup and initialization. ``` -------------------------------- ### Run Flutter Example on Browser Source: https://github.com/amplitude/amplitude-flutter/blob/main/example/README.md Use this command to run the Amplitude Flutter example in a Chrome browser. This command starts the development server. ```shell flutter run -d chrome ``` -------------------------------- ### Complete Identify Example Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/events-and-identify.md A comprehensive example demonstrating various Identify operations including setting, setting once, adding, and appending properties. ```dart final identify = Identify() ..set('email', 'user@company.com') ..set('name', 'John Doe') ..set('plan', 'enterprise') ..setOnce('signup_date', '2024-01-15') ..add('login_count', 1) ..add('purchase_count', 1) ..append('features_used', 'analytics') ..append('features_used', 'dashboard'); amplitude.identify(identify); ``` -------------------------------- ### Complete User Management Example Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/user-and-session-management.md This comprehensive example demonstrates initializing the Amplitude SDK, managing user login/logout, tracking events, and retrieving user/device information. ```dart import 'package:amplitude_flutter/amplitude.dart'; import 'package:uuid/uuid.dart'; import 'package:shared_preferences/shared_preferences.dart'; class AmplitudeService { late Amplitude _amplitude; late SharedPreferences _prefs; Future initialize() async { _prefs = await SharedPreferences.getInstance(); // Get or create device ID String deviceId = _prefs.getString('device_id') ?? ''; if (deviceId.isEmpty) { deviceId = const Uuid().v4(); await _prefs.setString('device_id', deviceId); } // Configure and initialize final config = Configuration( apiKey: 'YOUR_API_KEY', minTimeBetweenSessionsMillis: 300000, // 5 minutes ); _amplitude = Amplitude(config); _amplitude.setDeviceId(deviceId); await _amplitude.isBuilt; } Future onUserLogin(String email, String userId) async { _amplitude.setUserId(userId); // Identify user properties final identify = Identify() ..set('email', email) ..set('last_login', DateTime.now().toString()) ..add('login_count', 1); await _amplitude.identify(identify); // Track login event _amplitude.track(BaseEvent('User Logged In')); } Future onUserLogout() async { // Flush events await _amplitude.flush(); // Reset identity (new device ID, clear user) await _amplitude.reset(); // Track logout _amplitude.track(BaseEvent('User Logged Out')); } Future getCurrentUserId() async { return await _amplitude.getUserId(); } Future getCurrentDeviceId() async { return await _amplitude.getDeviceId(); } Future getCurrentSessionId() async { return await _amplitude.getSessionId(); } void trackEvent(String eventName, Map? properties) { final event = BaseEvent(eventName); if (properties != null) { event.eventProperties = properties; } _amplitude.track(event); } } // Usage void main() async { final service = AmplitudeService(); await service.initialize(); // On login await service.onUserLogin('user@example.com', 'user123'); service.trackEvent('Feature Used', {'feature': 'analytics'}); // On logout await service.onUserLogout(); } ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/configuration.md A comprehensive example demonstrating various configuration options for the Amplitude Flutter SDK, including API key, instance name, flush settings, server zone, session management, tracking options, logging, privacy controls, and autocapture. ```dart final config = Configuration( apiKey: 'YOUR_AMPLITUDE_API_KEY', instanceName: 'main_analytics', flushQueueSize: 50, flushIntervalMillis: 60000, flushMaxRetries: 5, flushEventsOnClose: true, serverZone: ServerZone.eu, useBatch: false, minTimeBetweenSessionsMillis: 300000, minIdLength: 5, trackingOptions: TrackingOptions( ipAddress: true, language: true, platform: true, region: true, city: true, country: true, ), logLevel: LogLevel.warn, enableCoppaControl: false, optOut: false, autocapture: AutocaptureOptions( sessions: true, appLifecycles: false, deepLinks: false, attribution: AttributionDisabled(), pageViews: PageViewsDisabled(), ), ); final amplitude = Amplitude(config); await amplitude.isBuilt; // Now ready to track events amplitude.track(BaseEvent('App Started')); ``` -------------------------------- ### Run Flutter Example on Web Server (Browser) Source: https://github.com/amplitude/amplitude-flutter/blob/main/example/README.md Use this command to run the Amplitude Flutter example on a web server, which can be useful for specific browser configurations or when the standard Chrome run command has issues. Follow the printed link in the console after execution. ```shell flutter run -d web-server --web-port=5000 --web-enable-expression-evaluation ``` -------------------------------- ### Minimal Amplitude Flutter Setup Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/initialization-and-setup.md Provides the most basic setup for initializing the Amplitude SDK in your Flutter application. Ensure you replace 'YOUR_AMPLITUDE_API_KEY' with your actual API key. ```dart import 'package:amplitude_flutter/amplitude.dart'; void main() { final config = Configuration(apiKey: 'YOUR_AMPLITUDE_API_KEY'); final amplitude = Amplitude(config); runApp(MyApp(amplitude: amplitude)); } ``` -------------------------------- ### Run Flutter Example on Android/iOS Source: https://github.com/amplitude/amplitude-flutter/blob/main/example/README.md Use this command to run the Amplitude Flutter example on Android or iOS emulators/devices. Ensure Flutter is set up and the API key is updated in lib/main.dart. ```shell flutter run ``` -------------------------------- ### Track Event Example Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/api-reference.md Example of creating and tracking a BaseEvent using the Amplitude SDK. This demonstrates how to populate event and user properties before sending the event. ```dart final event = BaseEvent('Product Viewed') ..eventProperties = {'product_id': '123', 'category': 'shoes'} ..userProperties = {'user_tier': 'gold'}; amplitude.track(event); ``` -------------------------------- ### Autocapture Configuration Examples Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/api-reference.md Configure autocapture with granular control, enable all features, or disable all features. ```dart autocapture: AutocaptureOptions( sessions: true, appLifecycles: true, deepLinks: true, attribution: AttributionOptions( excludeReferrers: ['internal.com'], resetSessionOnNewCampaign: true, ), pageViews: PageViewsOptions( trackHistoryChanges: 'pathOnly', ), ) ``` ```dart autocapture: AutocaptureEnabled() ``` ```dart autocapture: AutocaptureDisabled() ``` -------------------------------- ### Core SDK Imports Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/README.md Import necessary classes from the Amplitude Flutter SDK to get started with tracking events and managing user data. ```dart import 'package:amplitude_flutter/amplitude.dart'; import 'package:amplitude_flutter/events/base_event.dart'; import 'package:amplitude_flutter/events/identify.dart'; import 'package:amplitude_flutter/events/revenue.dart'; ``` -------------------------------- ### AttributionOptions Example Usage Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/types.md Demonstrates how to instantiate AttributionOptions with custom settings for excluding referrers, defining an initial empty value, and enabling session reset on new campaigns. ```dart AttributionOptions( excludeReferrers: ['internal.company.com'], initialEmptyValue: 'NONE', resetSessionOnNewCampaign: true, ) ``` -------------------------------- ### Full Amplitude Flutter Initialization with Dependency Injection Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/initialization-and-setup.md A comprehensive example demonstrating how to integrate Amplitude SDK initialization into a Flutter app using a service class for dependency injection. It includes configuration, asynchronous initialization, and methods for tracking events and identifying users. ```dart import 'package:amplitude_flutter/amplitude.dart'; import 'package:amplitude_flutter/events/base_event.dart'; import 'package:amplitude_flutter/events/identify.dart'; class AmplitudeService { static late Amplitude _instance; static Future initialize(String apiKey) async { final config = Configuration( apiKey: apiKey, logLevel: LogLevel.warn, flushIntervalMillis: 30000, flushQueueSize: 30, ); _instance = Amplitude(config); // Wait for initialization await _instance.isBuilt; print('Amplitude SDK initialized'); } static Amplitude getInstance() { return _instance; } static void trackEvent(String eventName, {Map? properties}) { final event = BaseEvent(eventName); if (properties != null) { event.eventProperties = properties; } _instance.track(event); } static Future identifyUser(String userId, Map properties) async { await _instance.setUserId(userId); final identify = Identify(); properties.forEach((key, value) { identify.set(key, value); }); await _instance.identify(identify); } } // In main.dart void main() async { WidgetsFlutterBinding.ensureInitialized(); await AmplitudeService.initialize('YOUR_AMPLITUDE_API_KEY'); runApp(const MyApp()); } // Usage in widgets class MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { return ElevatedButton( onPressed: () { AmplitudeService.trackEvent('Button Pressed'); }, child: const Text('Click Me'), ); } } ``` -------------------------------- ### Example Commit Message for a New Feature Source: https://github.com/amplitude/amplitude-flutter/blob/main/CONTRIBUTING.md Follow conventional commit standards for PR titles. This example shows a new feature commit. ```conventionalcommits feat(): ``` -------------------------------- ### Example Commit Message for Refactoring Source: https://github.com/amplitude/amplitude-flutter/blob/main/CONTRIBUTING.md Follow conventional commit standards for PR titles. This example shows a refactoring commit. ```conventionalcommits refactor(): ``` -------------------------------- ### Example Commit Message for Build System Changes Source: https://github.com/amplitude/amplitude-flutter/blob/main/CONTRIBUTING.md Follow conventional commit standards for PR titles. This example shows a commit affecting the build system. ```conventionalcommits build(): ``` -------------------------------- ### Example Commit Message for Documentation Updates Source: https://github.com/amplitude/amplitude-flutter/blob/main/CONTRIBUTING.md Follow conventional commit standards for PR titles. This example shows a documentation update commit. ```conventionalcommits docs(): ``` -------------------------------- ### Initialize Amplitude with Custom Device ID Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/user-and-session-management.md Example of initializing the Amplitude SDK, retrieving a device ID from shared preferences, generating a new one if none exists, and setting it. ```dart import 'package:uuid/uuid.dart'; import 'package:shared_preferences/shared_preferences.dart'; Future initAmplitude() async { final prefs = await SharedPreferences.getInstance(); String deviceId = prefs.getString('amplitude_device_id') ?? ''; if (deviceId.isEmpty) { deviceId = const Uuid().v4(); await prefs.setString('amplitude_device_id', deviceId); } final config = Configuration(apiKey: 'YOUR_API_KEY'); final amplitude = Amplitude(config); amplitude.setDeviceId(deviceId); await amplitude.isBuilt; } ``` -------------------------------- ### Example Commit Message for Performance Improvements Source: https://github.com/amplitude/amplitude-flutter/blob/main/CONTRIBUTING.md Follow conventional commit standards for PR titles. This example shows a performance improvement commit. ```conventionalcommits perf(): ``` -------------------------------- ### Example Commit Message for Test Updates Source: https://github.com/amplitude/amplitude-flutter/blob/main/CONTRIBUTING.md Follow conventional commit standards for PR titles. This example shows a commit that updates tests. ```conventionalcommits test(): ``` -------------------------------- ### iOS Native Code Example for Adding Amplitude Plugin Source: https://github.com/amplitude/amplitude-flutter/blob/main/CONTRIBUTING.md This is an example of how to add an Amplitude plugin to the native Amplitude instance on iOS. It assumes you have obtained the Amplitude instance. ```swift amplitude.add(engagement.getPlugin()) ``` -------------------------------- ### PageViewsOptions Example Usage Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/types.md Demonstrates instantiating PageViewsOptions to track history changes by path only and to set a custom event type for page view tracking. ```dart PageViewsOptions( trackHistoryChanges: 'pathOnly', eventType: 'Custom Page View', ) ``` -------------------------------- ### Example Commit Message for Style Changes Source: https://github.com/amplitude/amplitude-flutter/blob/main/CONTRIBUTING.md Follow conventional commit standards for PR titles. This example shows a commit related to code style. ```conventionalcommits style(): ``` -------------------------------- ### Amplitude Flutter SDK API Overview Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt This documentation covers the Amplitude Flutter SDK, including its core components like sealed classes for event tracking (Autocapture, Attribution, PageViews), numerous data classes with detailed field documentation, and extensive configuration options. It highlights features such as complete API signatures, parameter tables, real-world usage examples, configuration presets, platform-specific behavior, type definitions, sealed class explanations, deprecated API guidance, error handling patterns, best practices, cross-references, source file locations, behavioral matrices, service examples, and lifecycle documentation. ```APIDOC ## Amplitude Flutter SDK Documentation Overview ### Description This document provides a high-level overview of the Amplitude Flutter SDK's documentation. It details the scope, content, and quality of the documentation, ensuring users have a clear understanding of the SDK's capabilities and how to use it effectively across different platforms. ### Key Features - Complete API signatures with parameter types and return types - Parameter tables with constraints and defaults - Real-world usage examples for each major feature - Configuration presets for common scenarios - Platform-specific behavior documentation - Type definitions with field documentation - Sealed class hierarchies explained - Deprecated API guidance and migration paths - Error handling patterns - Best practices throughout - Cross-references between documents - Source file location references for all definitions - Behavioral matrices and flow diagrams - Complete service examples - Lifecycle documentation ### Platform Support - iOS: Full support documented - Android: Full support documented - Web: Full support documented - macOS: Full support documented ### Usage Patterns Documented 1. Initialization (Minimal setup, Dependency injection, Provider pattern, Lifecycle management) 2. Event Tracking (Basic events, Events with properties, Events with user properties, Events with group context, Revenue tracking, Batch operations) 3. User Management (Setting user ID, Setting device ID, Device ID persistence, User login/logout flows, Identity reset) 4. Property Updates (Via Identify, Via EventOptions, Via BaseEvent, List operations) 5. Privacy and Compliance (Opt-out controls, COPPA compliance, Privacy-focused configuration, Consent management) 6. Sessions (Session timeout configuration, Session ID retrieval, Session lifecycle) 7. Configuration (Development setup, Production setup, EU data residency, High-volume tracking, Privacy-focused configuration, Custom endpoints) ### Documentation Statistics - Total Files: 7 markdown documents - Total Lines: 4,683 lines of documentation - Total Size: ~120 KB - Coverage: 100% of public API methods, exported classes, type definitions, configuration options, enums, and sealed class hierarchies. - Examples: 50+ working code examples - Tables: 40+ reference tables - Source References: 50+ file:line references ### Source Analysis - Files Analyzed: 21 Dart source files - Key Modules: lib/amplitude.dart, lib/configuration.dart, lib/events/, lib/autocapture/, lib/amplitude_web.dart, lib/constants.dart - Public API Elements: 40+ classes/functions ### Documentation Quality - Precise type signatures with full parameter documentation - No generic or vague descriptions - Real code examples (not pseudo-code) - Behavioral documentation - Cross-references between related concepts - Platform-specific behavior clearly marked - Deprecated APIs identified with migration guidance - Constraints and limitations documented - Error conditions explained - Best practices section in each major document - Troubleshooting guides - Service examples showing integration patterns ### How to Use This Documentation 1. Start with README.md for overview and navigation. 2. For quick start, see initialization-and-setup.md. ``` -------------------------------- ### Example Commit Message for Chore Tasks Source: https://github.com/amplitude/amplitude-flutter/blob/main/CONTRIBUTING.md Follow conventional commit standards for PR titles. This example shows a commit for general maintenance or chores. ```conventionalcommits chore(): ``` -------------------------------- ### Example Commit Message for CI Configuration Changes Source: https://github.com/amplitude/amplitude-flutter/blob/main/CONTRIBUTING.md Follow conventional commit standards for PR titles. This example shows a commit affecting CI configuration. ```conventionalcommits ci(): ``` -------------------------------- ### Identify API Example Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/api-reference.md Demonstrates constructing an Identify object and chaining multiple operations to set and modify user properties. This is useful for updating user profiles. ```dart final identify = Identify() ..set('email', 'user@example.com') ..setOnce('signup_date', '2024-01-15') ..add('login_count', 1) ..append('tags', 'beta_tester'); amplitude.identify(identify); ``` -------------------------------- ### Set User ID Examples Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/user-and-session-management.md Use consistent identifiers like email or account ID for user IDs. Avoid non-unique or potentially conflicting values. ```dart // ✓ Good amplitude.setUserId('user@company.com'); amplitude.setUserId('acct_abc123def456'); amplitude.setUserId('john_doe_123'); // ✗ Avoid amplitude.setUserId('John Doe'); // Not unique amplitude.setUserId('12345'); // May conflict with device ID amplitude.setUserId('user@personal'); // Personal PII without consent ``` -------------------------------- ### Configure Session Timeout Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/user-and-session-management.md Configures the minimum time between sessions to define new session creation. This example sets a 10-minute timeout for all platforms. ```dart final config = Configuration( apiKey: 'YOUR_API_KEY', minTimeBetweenSessionsMillis: 600000, // 10 minutes for all platforms ); final amplitude = Amplitude(config); ``` -------------------------------- ### Initialize Amplitude Early in App Lifecycle Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/initialization-and-setup.md Ensure Amplitude is initialized as early as possible, ideally before running the main application widget, to capture all user interactions from the start. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); // Initialize before running app await AmplitudeService.initialize('YOUR_API_KEY'); runApp(const MyApp()); } ``` -------------------------------- ### Initialize Amplitude with Provider Package Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/initialization-and-setup.md Integrate Amplitude with the provider package for state management. This example shows how to create a ChangeNotifier class to manage Amplitude initialization and instance, making it accessible throughout your Flutter application. ```dart import 'package:provider/provider.dart'; import 'package:amplitude_flutter/amplitude.dart'; class AmplitudeProvider extends ChangeNotifier { late Amplitude _amplitude; bool _initialized = false; bool get isInitialized => _initialized; Amplitude get instance => _amplitude; Future initialize(String apiKey) async { final config = Configuration(apiKey: apiKey); _amplitude = Amplitude(config); _initialized = await _amplitude.isBuilt; notifyListeners(); } } // In main.dart void main() async { WidgetsFlutterBinding.ensureInitialized(); final amplitudeProvider = AmplitudeProvider(); await amplitudeProvider.initialize('YOUR_API_KEY'); runApp( MultiProvider( providers: [ ChangeNotifierProvider.value(value: amplitudeProvider), ], child: const MyApp(), ), ); } // Usage in widgets class MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { final amplitudeProvider = Provider.of(context); return ElevatedButton( onPressed: { amplitudeProvider.instance.track(BaseEvent('Button Pressed')); }, child: const Text('Click Me'), ); } } ``` -------------------------------- ### Track Event with Event Properties Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/README.md Example of tracking an event with flexible, typed properties. Supported types include String, int, double, bool, List, and Map. DateTime and custom classes are not supported. ```dart Map eventProperties = { 'string_prop': 'value', 'int_prop': 42, 'double_prop': 3.14, 'bool_prop': true, 'list_prop': [1, 2, 3], 'map_prop': {'nested': 'value'}, }; ``` -------------------------------- ### Amplitude Flutter SDK Initialization with Configuration Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/COMPLETION_REPORT.md Demonstrates a more detailed initialization process, including creating a Configuration object. This allows for customization of various SDK settings. ```dart import 'package:amplitude_flutter/amplitude.dart'; import 'package:amplitude_flutter/amplitude_config.dart'; final config = AmplitudeConfig('YOUR_API_KEY'); // Set other configuration options here, e.g.: // config.setServerZone(ServerZone.EU); // config.setUseBatching(true); final amplitude = Amplitude('YOUR_API_KEY'); amplitude.init(config); // Wait for initialization to complete if needed await amplitude.init(); ``` -------------------------------- ### Basic Amplitude Configuration Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/configuration.md Initialize the Amplitude SDK with your API key. Ensure you await the `isBuilt` property before proceeding. ```dart import 'package:amplitude_flutter/amplitude.dart'; final config = Configuration( apiKey: 'YOUR_AMPLITUDE_API_KEY', ); final amplitude = Amplitude(config); await amplitude.isBuilt; ``` -------------------------------- ### Example Commit Message for a Bug Fix Source: https://github.com/amplitude/amplitude-flutter/blob/main/CONTRIBUTING.md Follow conventional commit standards for PR titles. This example shows a bug fix commit. ```conventionalcommits fix(): ``` -------------------------------- ### Example Commit Message for Reverting Commits Source: https://github.com/amplitude/amplitude-flutter/blob/main/CONTRIBUTING.md Follow conventional commit standards for PR titles. This example shows a commit that reverts a previous one. ```conventionalcommits revert(): ``` -------------------------------- ### Configuration Class Constructor Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Details the parameters available for initializing the Configuration class, which controls SDK behavior. ```APIDOC ## Configuration Class Constructor ### Description Initializes the Amplitude SDK with various options to customize tracking and behavior. ### Parameters - **apiKey** (String): Required. Your Amplitude API key. - **flushIntervalMillis** (int): Optional. Interval in milliseconds to automatically flush events. Defaults to 10000. - **flushMaxRetries** (int): Optional. Maximum number of retries for failed event uploads. Defaults to 3. - **instanceName** (String): Optional. Name for the SDK instance if multiple are used. Defaults to 'default'. - **logLevel** (LogLevel): Optional. Sets the verbosity of SDK logs. Defaults to LogLevel.None. - **minIdLength** (int): Optional. Minimum length for device IDs. Defaults to 10. - **optOut** (bool): Optional. Initial opt-out status. Defaults to false. - **plan** (Plan): Optional. Specifies the Amplitude plan type. - **serverZone** (ServerZone): Optional. The Amplitude server zone to use. Defaults to ServerZone.US. - **useBatch**: (bool): Optional. Whether to use batching for event uploads. Defaults to true. - **useLocationInfo**: (bool): Optional. Whether to automatically include location information. Defaults to true. - **useManufacturerId**: (bool): Optional. Whether to use the device manufacturer ID. Defaults to true. - **useCarrier**: (bool): Optional. Whether to include carrier information. Defaults to true. - **useIpAddress**: (bool): Optional. Whether to include the IP address. Defaults to true. - **useIdfv**: (bool): Optional. Whether to use the IDFV (Identifier for Vendors) on iOS. Defaults to true. - **useVendorId**: (bool): Optional. Whether to use the Vendor ID on Android. Defaults to true. - **trackingOptions**: (TrackingOptions): Optional. Advanced tracking options. - **cookieOptions**: (CookieOptions): Optional. Options for cookie management on web. - **ingestionMetadata**: (IngestionMetadata): Optional. Metadata for event ingestion. ### Examples ```dart final config = Configuration( apiKey: 'YOUR_API_KEY', logLevel: LogLevel.Debug, flushIntervalMillis: 5000, serverZone: ServerZone.EU ); Amplitude.init(config); ``` ``` -------------------------------- ### Initialize Amplitude SDK Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/README.md Configure and initialize the Amplitude SDK with your API key and desired settings. Ensure the SDK is ready before tracking events. ```dart final config = Configuration( apiKey: 'YOUR_API_KEY', flushIntervalMillis: 30000, logLevel: LogLevel.warn, ); final amplitude = Amplitude(config); await amplitude.isBuilt; amplitude.track(BaseEvent('App Started')); ``` -------------------------------- ### Configuration Constructor Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/api-reference.md Initializes the Amplitude SDK with project-specific settings. This constructor allows for detailed customization of event tracking, batching intervals, server zones, and other operational parameters. ```APIDOC ## Constructor Configuration ### Description Initializes the Amplitude SDK with project-specific settings. This constructor allows for detailed customization of event tracking, batching intervals, server zones, and other operational parameters. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **apiKey** (String) - Required - **Required.** API key for the Amplitude project * **flushQueueSize** (int) - Optional - Maximum events batched in a single upload. Default: 30 * **flushIntervalMillis** (int) - Optional - Interval for uploading events (milliseconds). Default: 30000 * **instanceName** (String) - Optional - Instance name for storage/identity isolation. Default: '$default_instance' * **optOut** (bool) - Optional - Disable tracking when true. Default: false * **logLevel** (LogLevel) - Optional - SDK logging level. Default: LogLevel.warn * **minIdLength** (int?) - Optional - Minimum length for userId/deviceId values. Default: null * **partnerId** (String?) - Optional - Partner ID for integrations. Default: null * **flushMaxRetries** (int) - Optional - Max retries for failed uploads. Default: 5 * **useBatch** (bool) - Optional - Use Batch API instead of HTTP V2 API. Default: false * **serverZone** (ServerZone) - Optional - Amplitude server zone (us/eu). Default: ServerZone.us * **serverUrl** (String?) - Optional - Custom event upload URL. Default: null * **minTimeBetweenSessionsMillis** (int) - Optional - Session timeout (mobile: 5min, web: 30min). Default: -1 * **enableCoppaControl** (bool) - Optional - Enable COPPA compliance controls. Default: false * **flushEventsOnClose** (bool) - Optional - Flush events when app closes. Default: true * **identifyBatchIntervalMillis** (int) - Optional - Identify event batching interval (mobile). Default: 30000 * **migrateLegacyData** (bool) - Optional - Migrate legacy SDK data. Default: true * **locationListening** (bool) - Optional - Enable location tracking (Android). Default: true * **useAdvertisingIdForDeviceId** (bool) - Optional - Use Google Advertising ID as device ID (Android). Default: false * **useAppSetIdForDeviceId** (bool) - Optional - Use app set ID as device ID (Android). Default: false * **appVersion** (String?) - Optional - App version (Web). Default: null * **deviceId** (String?) - Optional - Custom device ID (Web, Android). Default: null * **identityStorage** (String) - Optional - Storage method for user identity: 'cookie', 'localStorage', or 'none' (Web). Default: 'cookie' * **userId** (String?) - Optional - Custom user identifier (Web). Default: null * **transport** (String?) - Optional - Request API: 'fetch', 'xhr', or 'beacon' (Web). Default: 'fetch' * **fetchRemoteConfig** (bool) - Optional - Fetch remote configuration (Web). Default: false * **autocapture** (Autocapture?) - Optional - Autocapture configuration. Default: null ### Request Example ```dart final config = Configuration( apiKey: 'YOUR_API_KEY', flushQueueSize: 50, flushIntervalMillis: 60000, logLevel: LogLevel.log, serverZone: ServerZone.eu, trackingOptions: TrackingOptions( ipAddress: false, language: true, ), autocapture: AutocaptureOptions( sessions: true, appLifecycles: true, ), ); final amplitude = Amplitude(config); ``` ### Response None ``` -------------------------------- ### Amplitude Flutter SDK Initialization with Development Configuration Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/COMPLETION_REPORT.md Sets up the Amplitude SDK with configuration presets suitable for development environments. This might include enabling debug logging. ```dart import 'package:amplitude_flutter/amplitude.dart'; import 'package:amplitude_flutter/amplitude_config.dart'; final config = AmplitudeConfig('YOUR_DEV_API_KEY'); config.setLogLevel(LogLevel.DEBUG); final amplitude = Amplitude('YOUR_DEV_API_KEY'); amplitude.init(config); ``` -------------------------------- ### Initialize Amplitude Flutter Instance Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/initialization-and-setup.md Demonstrates the creation of an Amplitude instance using the previously defined configuration. The SDK initializes asynchronously in the background. ```dart final amplitude = Amplitude(config); ``` -------------------------------- ### Amplitude Constructor Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/api-reference.md Initializes the Amplitude SDK with a configuration object and an optional MethodChannel. ```APIDOC ## Amplitude Constructor ### Description Initializes the Amplitude SDK with a configuration object and an optional MethodChannel. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Signature ```dart Amplitude(Configuration configuration, [MethodChannel? methodChannel]) ``` ### Parameters - **configuration** (Configuration) - Required - Configuration object specifying SDK settings - **methodChannel** (MethodChannel?) - Optional - Optional custom MethodChannel for platform communication ### Returns `Amplitude` instance ### Example ```dart final amplitude = Amplitude(Configuration(apiKey: 'YOUR_API_KEY')); await amplitude.isBuilt; ``` ``` -------------------------------- ### Verify Amplitude Flutter Initialization Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/initialization-and-setup.md Demonstrates how to verify that the Amplitude SDK has been successfully initialized before tracking events. This ensures that no events are lost during the initialization phase. ```dart final config = Configuration(apiKey: 'YOUR_API_KEY'); final amplitude = Amplitude(config); // Wait for initialization await amplitude.isBuilt; // Now ready to track amplitude.track(BaseEvent('App Started')); ``` -------------------------------- ### Initialize Amplitude SDK for Web Source: https://github.com/amplitude/amplitude-flutter/blob/main/example/web/index.html This snippet initializes the Amplitude SDK for web applications. It ensures the SDK is loaded correctly and makes its core functionalities available for tracking user events and properties. ```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 getSessionId(){ // ... implementation details ... } ``` ```dart final sessionId = await amplitude.getSessionId(); if (sessionId != null) { print('Session ID: $sessionId (${DateTime.fromMillisecondsSinceEpoch(sessionId)})'); } ``` -------------------------------- ### Create Amplitude Flutter Configuration Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/initialization-and-setup.md Shows how to create a Configuration object for the Amplitude SDK, specifying the required API key and other optional settings. ```dart final config = Configuration( apiKey: 'YOUR_AMPLITUDE_API_KEY', // Required ); ``` -------------------------------- ### AttributionOptions Constructor Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/api-reference.md Configure marketing attribution tracking for web. Specify referrers to exclude and whether to reset sessions on new campaigns. ```dart AttributionOptions({ List? excludeReferrers, String? initialEmptyValue = 'EMPTY', bool? resetSessionOnNewCampaign = false, }) ``` -------------------------------- ### Get Session ID Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/api-reference.md Retrieves the current session ID. Returns the current session ID in milliseconds, or null if no session. ```dart final sessionId = await amplitude.getSessionId(); print('Session: $sessionId'); ``` -------------------------------- ### Get Current User ID Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/user-and-session-management.md Retrieves the most recently set user ID. Returns null if no user ID has been set. ```dart final userId = await amplitude.getUserId(); if (userId != null) { print('Current user: $userId'); } else { print('No user ID set'); } ``` -------------------------------- ### Persist Device ID Example Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/user-and-session-management.md Store the device ID in persistent storage like SharedPreferences to maintain it across app launches. ```dart // On first app launch final deviceId = const Uuid().v4(); await prefs.setString('amplitude_device_id', deviceId); amplitude.setDeviceId(deviceId); // On subsequent launches final deviceId = prefs.getString('amplitude_device_id'); if (deviceId != null) { amplitude.setDeviceId(deviceId); } ``` -------------------------------- ### Getting Device ID from Amplitude Flutter SDK Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/COMPLETION_REPORT.md Retrieves the current device ID. This is useful for understanding the device context of events. ```dart String? deviceId = await amplitude.getDeviceId(); ``` -------------------------------- ### Check Initialization Status and IDs Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/initialization-and-setup.md Verify if the Amplitude SDK is ready and retrieve user, device, and session identifiers. This is useful for debugging and ensuring the SDK is correctly set up. ```dart final amplitude = Amplitude(Configuration(apiKey: 'key')); // Check if ready if (await amplitude.isBuilt) { print('Ready'); } else { print('Failed'); } // Check user/device IDs print('User: ${await amplitude.getUserId()}'); print('Device: ${await amplitude.getDeviceId()}'); print('Session: ${await amplitude.getSessionId()}'); ``` -------------------------------- ### Get Current Device ID Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/user-and-session-management.md Retrieves the current device ID. This ID is generated automatically based on the platform or can be set manually. ```dart final deviceId = await amplitude.getDeviceId(); print('Device ID: $deviceId'); ``` -------------------------------- ### Revenue Constructor Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/api-reference.md Initializes a Revenue object for tracking financial transactions. This object can then be populated with transaction details. ```APIDOC ## Revenue Object for tracking revenue transactions. ### Constructor ```dart Revenue() ``` ``` -------------------------------- ### Clone the Amplitude Flutter Repository Source: https://github.com/amplitude/amplitude-flutter/blob/main/CONTRIBUTING.md Use this command to clone the Amplitude Flutter SDK repository to your local machine. ```bash git clone https://github.com/amplitude/Amplitude-Flutter ``` -------------------------------- ### Amplitude Flutter SDK Initialization for High-Volume Tracking Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/COMPLETION_REPORT.md Sets up the Amplitude SDK with configurations optimized for high-volume event tracking, potentially involving batching and efficient data handling. ```dart import 'package:amplitude_flutter/amplitude.dart'; import 'package:amplitude_flutter/amplitude_config.dart'; final config = AmplitudeConfig('YOUR_API_KEY'); config.setUseBatching(true); config.setBatchIntervalMillis(5000); // Batch events every 5 seconds final amplitude = Amplitude('YOUR_API_KEY'); amplitude.init(config); ``` -------------------------------- ### Amplitude Flutter SDK Initialization with Production Configuration Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/COMPLETION_REPORT.md Initializes the Amplitude SDK using configuration presets optimized for production. This typically involves disabling debug logs and potentially enabling batching. ```dart import 'package:amplitude_flutter/amplitude.dart'; import 'package:amplitude_flutter/amplitude_config.dart'; final config = AmplitudeConfig('YOUR_PROD_API_KEY'); config.setUseBatching(true); final amplitude = Amplitude('YOUR_PROD_API_KEY'); amplitude.init(config); ``` -------------------------------- ### Options for Waiting on Amplitude Flutter Initialization Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/initialization-and-setup.md Presents three options for handling Amplitude SDK initialization: awaiting completion, checking status, or proceeding without explicit waiting, as the SDK buffers events. ```dart final config = Configuration(apiKey: 'YOUR_API_KEY'); final amplitude = Amplitude(config); // Option 1: Await initialization await amplitude.isBuilt; // Option 2: Check initialization status if (await amplitude.isBuilt) { print('SDK ready'); } else { print('SDK initialization failed'); } // Option 3: Continue without waiting // (SDK buffers events and sends when ready) amplitude.track(BaseEvent('Event')); // Safe even if not ready yet ``` -------------------------------- ### Getting User ID from Amplitude Flutter SDK Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/COMPLETION_REPORT.md Retrieves the currently set user ID. Useful for verifying the active user or for use in other parts of your application. ```dart String? userId = await amplitude.getUserId(); ``` -------------------------------- ### Handle Asynchronous Initialization Gracefully Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/initialization-and-setup.md Avoid blocking the UI thread while waiting for `amplitude.isBuilt`. Instead, use a fire-and-forget approach for tracking events, allowing the SDK to buffer them internally. ```dart // ✗ Avoid blocking UI await amplitude.isBuilt; // ✓ Recommended: fire-and-forget with buffering amplitude.track(BaseEvent('Event')); // SDK buffers internally ``` -------------------------------- ### Use Batch API for Event Uploads Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/configuration.md Enable the Batch API by setting `useBatch` to true and configure `flushQueueSize` for efficient event uploading. ```dart final config = Configuration( apiKey: 'YOUR_API_KEY', useBatch: true, // Use Batch API endpoint flushQueueSize: 100, ); final amplitude = Amplitude(config); ``` -------------------------------- ### Configure for EU Data Residency Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/configuration.md Use the `serverZone` parameter to direct data to the EU data center for compliance with data residency requirements. ```dart final config = Configuration( apiKey: 'YOUR_API_KEY', serverZone: ServerZone.eu, // Use EU data center ); final amplitude = Amplitude(config); ``` -------------------------------- ### Amplitude Flutter SDK Configuration Constructor Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/api-reference.md Use this constructor to set up your Amplitude project's API key and customize various SDK behaviors like event batching, logging levels, server zones, and tracking options. Ensure you provide a valid API key to initialize the SDK. ```dart Configuration({ required String apiKey, int flushQueueSize = 30, int flushIntervalMillis = 30000, String instanceName = '', bool optOut = false, LogLevel logLevel = LogLevel.warn, int? minIdLength, String? partnerId, int flushMaxRetries = 5, bool useBatch = false, ServerZone serverZone = ServerZone.us, String? serverUrl, int minTimeBetweenSessionsMillis = -1, @Deprecated DefaultTrackingOptions? defaultTracking, TrackingOptions? trackingOptions, bool enableCoppaControl = false, bool flushEventsOnClose = true, int identifyBatchIntervalMillis = 30000, bool migrateLegacyData = true, bool locationListening = true, bool useAdvertisingIdForDeviceId = false, bool useAppSetIdForDeviceId = false, String? appVersion, String? deviceId, CookieOptions? cookieOptions, String identityStorage = 'cookie', String? userId, String? transport = 'fetch', bool fetchRemoteConfig = false, Autocapture? autocapture, }) ``` ```dart final config = Configuration( apiKey: 'YOUR_API_KEY', flushQueueSize: 50, flushIntervalMillis: 60000, logLevel: LogLevel.log, serverZone: ServerZone.eu, trackingOptions: TrackingOptions( ipAddress: false, language: true, ), autocapture: AutocaptureOptions( sessions: true, appLifecycles: true, ), ); final amplitude = Amplitude(config); ``` -------------------------------- ### Revenue Constructor Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/api-reference.md Initializes a Revenue object for tracking financial transactions. This object is used to log details about purchases and revenue events. ```dart Revenue() ``` -------------------------------- ### Amplitude Flutter Configuration Constructor Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/configuration.md Initialize the Amplitude SDK with various configuration options. The configuration is immutable after instantiation, except for the optOut property. ```dart Configuration({ required String apiKey, int flushQueueSize = 30, int flushIntervalMillis = 30000, String instanceName = '', bool optOut = false, LogLevel logLevel = LogLevel.warn, int? minIdLength, String? partnerId, int flushMaxRetries = 5, bool useBatch = false, ServerZone serverZone = ServerZone.us, String? serverUrl, int minTimeBetweenSessionsMillis = -1, @Deprecated DefaultTrackingOptions? defaultTracking, TrackingOptions? trackingOptions, bool enableCoppaControl = false, bool flushEventsOnClose = true, int identifyBatchIntervalMillis = 30000, bool migrateLegacyData = true, bool locationListening = true, bool useAdvertisingIdForDeviceId = false, bool useAppSetIdForDeviceId = false, String? appVersion, String? deviceId, CookieOptions? cookieOptions, String identityStorage = 'cookie', String? userId, String? transport = 'fetch', bool fetchRemoteConfig = false, Autocapture? autocapture, }) ``` -------------------------------- ### Create a Custom Amplitude Instance Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/configuration.md Initialize a custom Amplitude instance with a unique `instanceName` for isolated analytics tracking. ```dart final config = Configuration( apiKey: 'YOUR_API_KEY', instanceName: 'analytics_instance', // Unique identifier ); final amplitude = Amplitude(config); ``` -------------------------------- ### Handle User Consent for Privacy Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/user-and-session-management.md Implement user consent checks and use `setOptOut` to comply with privacy regulations. ```dart // Check consent bool hasConsent = await _checkUserConsent(); // Set opt-out accordingly final config = Configuration( apiKey: 'YOUR_API_KEY', optOut: !hasConsent, ); // Later, if user grants consent if (userGrantsConsent()) { amplitude.setOptOut(false); } ``` -------------------------------- ### Amplitude Flutter SDK Initialization for EU Data Residency Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/COMPLETION_REPORT.md Configures the Amplitude SDK to send data to the EU data center, ensuring compliance with data residency requirements. ```dart import 'package:amplitude_flutter/amplitude.dart'; import 'package:amplitude_flutter/amplitude_config.dart'; final config = AmplitudeConfig('YOUR_API_KEY'); config.setServerZone(ServerZone.EU); final amplitude = Amplitude('YOUR_API_KEY'); amplitude.init(config); ``` -------------------------------- ### Track Revenue with Details Source: https://github.com/amplitude/amplitude-flutter/blob/main/_autodocs/api-reference.md Use the Revenue class to log a revenue event with detailed properties like price, quantity, product ID, currency, and custom properties. Ensure 'price' is set for valid revenue tracking. ```dart final revenue = Revenue() ..price = 9.99 ..quantity = 2 ..productId = 'premium_feature' ..revenueCurrency = 'USD' ..revenueType = 'purchase' ..properties = {'campaign': 'summer_sale'}; amplitude.revenue(revenue); ```