### Setup and Build Sample App (SPM) Source: https://github.com/customerio/customerio-flutter/blob/main/apps/README.md Steps to set up environment files, install dependencies, and build the iOS and Android versions of the SPM sample app. Requires running scripts for environment setup. ```bash # 1. Setup environment files (creates .env + ios/Env.swift with dummy values) ./apps/scripts/setup_env.sh apps/flutter_sample_spm # 2. Install dependencies cd apps/flutter_sample_spm flutter pub get # 3. Build flutter build ios --no-codesign # iOS flutter build apk # Android ``` -------------------------------- ### Interactive Setup Script Source: https://github.com/customerio/customerio-flutter/blob/main/apps/README.md Executes a setup script for guided interactive walkthrough of the SPM sample app setup. This script automates parts of the environment and dependency configuration. ```bash ./apps/scripts/setup.sh apps/flutter_sample_spm ``` -------------------------------- ### Manual Location Tracking Setup Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/feature-guides.md Request location permissions, get the current GPS coordinates, and set them in Customer.io for user tracking. Also includes an option to request an immediate location update. ```dart import 'geolocator/geolocator.dart'; import 'package:customer_io/customer_io.dart'; void setupLocationTracking() async { // Request permissions LocationPermission permission = await Geolocator.requestPermission(); if (permission == LocationPermission.whileInUse || permission == LocationPermission.always) { // Get current location final position = await Geolocator.getCurrentPosition(); // Set in Customer.io CustomerIO.location.setLastKnownLocation( latitude: position.latitude, longitude: position.longitude, ); } } // Request location update on demand void updateLocationNow() { CustomerIO.location.requestLocationUpdate(); } ``` -------------------------------- ### InlineInAppMessageView Usage Example Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/inline_in_app_message_view.md Example of how to use the InlineInAppMessageView widget, including handling action clicks and navigation. ```dart InlineInAppMessageView( elementId: 'banner-top', onActionClick: (message, actionValue, actionName) { print('Action: $actionName with value: $actionValue'); print('Message ID: ${message.messageId}'); if (actionName == 'view_details') { // Navigate to details page Navigator.push(context, MaterialPageRoute(...)); } }, ) ``` -------------------------------- ### InAppMessage Example Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/inline_in_app_message_view.md Example of creating an InAppMessage object with essential details. ```dart final message = InAppMessage( messageId: 'msg-123', deliveryId: 'delivery-456', elementId: 'banner-top', ); ``` -------------------------------- ### Configure Push Notifications Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/configuration.md Example of setting up `PushConfig` within the main `CustomerIOConfig`. This demonstrates configuring Android-specific push behaviors. ```dart final config = CustomerIOConfig( cdpApiKey: 'your-key', pushConfig: PushConfig( android: PushConfigAndroid( pushClickBehavior: PushClickBehaviorAndroid.resetTaskStack, ), ), ); ``` -------------------------------- ### Initialize Customer.io SDK Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/configuration.md Example of initializing the Customer.io SDK with a comprehensive set of configuration options. Ensure all required parameters like `cdpApiKey` are provided. ```dart import 'package:customer_io/customer_io.dart'; void main() async { await CustomerIO.initialize( config: CustomerIOConfig( cdpApiKey: 'eeee1234567890abcdef', region: Region.us, logLevel: CioLogLevel.debug, autoTrackDeviceAttributes: true, trackApplicationLifecycleEvents: true, screenViewUse: ScreenView.all, inAppConfig: InAppConfig(siteId: 'abc123def'), pushConfig: PushConfig( android: PushConfigAndroid( pushClickBehavior: PushClickBehaviorAndroid.activityPreventRestart, ), ), locationConfig: LocationConfig( trackingMode: LocationTrackingMode.manual, ), ), ); runApp(MyApp()); } ``` -------------------------------- ### InAppMessageActionClickCallback Usage Example Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/inline_in_app_message_view.md Example of defining and using the InAppMessageActionClickCallback to handle different message actions. ```dart void handleMessageAction(InAppMessage message, String actionValue, String actionName) { if (actionName == 'cta_button') { launchUrl(Uri.parse(actionValue)); } else if (actionName == 'dismiss') { // Handle dismissal } } InlineInAppMessageView( elementId: 'banner', onActionClick: handleMessageAction, ) ``` -------------------------------- ### Create InAppMessage Instance Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/types.md Example of creating an InAppMessage instance for use with InAppEvent. Ensure messageId is provided. ```dart final event = InAppEvent( eventType: EventType.messageShown, message: InAppMessage(messageId: 'msg-123', deliveryId: 'delivery-456'), ); ``` -------------------------------- ### Configure In-App Messaging Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/configuration.md Example of setting up `InAppConfig` within the main `CustomerIOConfig`. The `siteId` is mandatory for in-app messaging to function. ```dart final config = CustomerIOConfig( cdpApiKey: 'your-key', inAppConfig: InAppConfig(siteId: 'abc123def'), ); ``` -------------------------------- ### Complete Customer.io Flutter SDK Initialization Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/configuration.md Initialize the Customer.io SDK with comprehensive configuration, including API keys, regions, logging, and feature flags. This example also shows device registration, user identification, and app startup. ```dart import 'package:customer_io/customer_io.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // Initialize Customer.io SDK await CustomerIO.initialize( config: CustomerIOConfig( cdpApiKey: 'cdp_eeee1234567890abcdef', migrationSiteId: null, region: Region.us, logLevel: CioLogLevel.debug, autoTrackDeviceAttributes: true, trackApplicationLifecycleEvents: true, apiHost: null, cdnHost: null, flushAt: 10, flushInterval: 10000, screenViewUse: ScreenView.all, inAppConfig: InAppConfig(siteId: 'site_abc123'), pushConfig: PushConfig( android: PushConfigAndroid( pushClickBehavior: PushClickBehaviorAndroid.activityPreventRestart, ), ), locationConfig: LocationConfig( trackingMode: LocationTrackingMode.manual, ), ), ); // Get Firebase token and register with Customer.io final token = await FirebaseMessaging.instance.getToken(); if (token != null) { CustomerIO.instance.registerDeviceToken(deviceToken: token); } // Identify user CustomerIO.instance.identify( userId: 'user@example.com', traits: { 'firstName': 'John', 'lastName': 'Doe', 'plan': 'premium', }, ); runApp(const MyApp()); } ``` -------------------------------- ### Initialization Flow Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/quick-reference.md Demonstrates the complete initialization flow for the CustomerIO Flutter SDK, including SDK initialization, device token registration, user identification, and event listener setup. ```APIDOC ## Initialization Flow ```dart import 'package:customer_io/customer_io.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // 1. Initialize SDK await CustomerIO.initialize( config: CustomerIOConfig( cdpApiKey: 'your-api-key', region: Region.us, inAppConfig: InAppConfig(siteId: 'your-site-id'), ), ); // 2. Register push token final token = await FirebaseMessaging.instance.getToken(); if (token != null) { CustomerIO.instance.registerDeviceToken(deviceToken: token); } // 3. Identify user CustomerIO.instance.identify( userId: 'user@example.com', traits: {'firstName': 'John'}, ); // 4. Listen to events CustomerIO.inAppMessaging.subscribeToEventsListener((event) { print('Event: ${event.eventType}'); }); runApp(const MyApp()); } ``` ``` -------------------------------- ### Usage of PushConfigAndroid Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/configuration.md Example of how to use PushConfigAndroid to set a specific push click behavior. This is useful for customizing notification interaction. ```dart PushConfig( android: PushConfigAndroid( pushClickBehavior: PushClickBehaviorAndroid.resetTaskStack, ), ) ``` -------------------------------- ### Usage of LocationConfig Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/configuration.md Example of how to instantiate LocationConfig with a specific tracking mode. This allows you to control location data capture. ```dart LocationConfig( trackingMode: LocationTrackingMode.manual, ) ``` -------------------------------- ### InAppEvent Example for messageShown Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/message-schema.md Illustrates the creation of an InAppEvent object specifically for the 'messageShown' event type, including the associated InAppMessage. ```dart InAppEvent( eventType: EventType.messageShown, message: InAppMessage( messageId: 'msg-123', deliveryId: 'delivery-456', ), actionValue: null, actionName: null, ) ``` -------------------------------- ### Get registered token Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/quick-reference.md Handles push notification registration and message reception. ```APIDOC ## Push Notifications ### Get registered token Handles push notification registration and message reception. ```dart // Get registered token final token = await CustomerIO.pushMessaging.getRegisteredDeviceToken(); // Handle incoming message final handled = await CustomerIO.pushMessaging.onMessageReceived( message, handleNotificationTrigger: true, ); // Handle background message final handled = await CustomerIO.pushMessaging.onBackgroundMessageReceived(message); ``` ``` -------------------------------- ### InboxMessage Example Usage Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/message-schema.md Demonstrates how to create an InboxMessage instance, mark it as opened, track a click interaction, and mark it as deleted using the inbox object. ```dart final message = InboxMessage( queueId: 'queue-123', deliveryId: 'delivery-456', sentAt: DateTime.now().subtract(Duration(hours: 2)), expiry: DateTime.now().add(Duration(days: 7)), topics: ['promotions', 'featured'], type: 'promotional_banner', opened: false, priority: 5, properties: { 'title': 'Summer Sale', 'discount': 0.20, 'expiresAt': '2024-08-31', 'productId': 'prod-123', 'imageUrl': 'https://example.com/summer.jpg', }, ); // Mark as read await inbox.markMessageOpened(message); // Track interaction inbox.trackMessageClicked(message, actionName: 'cta_clicked'); // Delete await inbox.markMessageDeleted(message); ``` -------------------------------- ### Access Push Messaging Platform Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/customer_io.md Gets the platform instance for handling push notifications. Use this to interact with push messaging features. ```dart final token = await CustomerIO.pushMessaging.getRegisteredDeviceToken(); ``` -------------------------------- ### Access Location Platform Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/customer_io.md Gets the platform instance for managing location tracking. Use this to set or retrieve location data. ```dart CustomerIO.location.setLastKnownLocation(latitude: 37.7749, longitude: -122.4194); ``` -------------------------------- ### Retrieve and Display Inbox Messages Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/types.md Example of fetching inbox messages and iterating through them to print details. This demonstrates how to access and display message metadata. ```dart final messages = await CustomerIO.inAppMessaging.getMessages(); for (final msg in messages) { print('Message: ${msg.type}'); print('Sent: ${msg.sentAt}'); print('Read: ${msg.opened}'); print('Topics: ${msg.topics.join(", ")} '); } ``` -------------------------------- ### Example: Tracking Message Updates with Equality Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/message-schema.md Demonstrates how to use InboxMessage equality to check if a message still exists after a refresh and access its updated state. ```dart final messages = await CustomerIO.inAppMessaging.getMessages(); final originalMessage = messages[0]; // Later, after refresh final updatedMessages = await CustomerIO.inAppMessaging.getMessages(); final sameMessage = updatedMessages.firstWhere( (m) => m == originalMessage, orElse: () => null, ); if (sameMessage != null) { print('Message still exists'); print('Now opened: ${sameMessage.opened}'); } else { print('Message was deleted'); } ``` -------------------------------- ### Message Priority Example Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/message-schema.md Illustrates how to set the `priority` field for `InboxMessage` to control message ordering, where lower numerical values indicate higher priority. ```dart // Lower priority value = higher priority final urgent = InboxMessage( // ... other fields priority: 1, // Shown first ); final normal = InboxMessage( // ... other fields priority: 50, // Shown second ); final lowPriority = InboxMessage( // ... other fields priority: 100, // Shown last ); final noPriority = InboxMessage( // ... other fields priority: null, // No specific priority ); ``` -------------------------------- ### Subscribe to InApp Events Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/types.md Example of subscribing to in-app message events and logging details. This listener is invoked when in-app messages are shown or actions are taken. ```dart CustomerIO.inAppMessaging.subscribeToEventsListener((event) { print('Message: ${event.message.messageId}'); print('Type: ${event.eventType}'); if (event.actionName != null) { print('Action: ${event.actionName}'); } }); ``` -------------------------------- ### Implement InAppEventListener Callbacks Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/types.md Example implementation of the InAppEventListener abstract class to handle in-app message events. Override methods to define custom behavior for message display, dismissal, errors, and actions. ```dart class MyInAppListener extends InAppEventListener { @override void messageShown(InAppMessage message) { print('Message shown: ${message.messageId}'); } @override void messageDismissed(InAppMessage message) { print('Message dismissed'); } @override void errorWithMessage(InAppMessage message) { print('Error with message'); } @override void messageActionTaken(InAppMessage message, String actionValue, String actionName) { print('Action: $actionName = $actionValue'); } } ``` -------------------------------- ### Custom Properties Example Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/message-schema.md Shows how to use the `properties` field in `InboxMessage` to store flexible custom data, including nested maps and lists. Demonstrates accessing these properties. ```dart final message = InboxMessage( // ... other fields properties: { 'customTitle': 'My Message', 'customData': { 'nested': 'value', 'count': 42, }, 'tags': ['tag1', 'tag2'], }, ); // Access custom properties final title = message.properties['customTitle']; final nested = message.properties['customData']['nested']; ``` -------------------------------- ### Configure Automatic Location Tracking Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/feature-guides.md Enable automatic location tracking to begin as soon as the application starts by configuring the `LocationConfig` during SDK initialization. ```dart // Enable automatic location tracking on app start await CustomerIO.initialize( config: CustomerIOConfig( cdpApiKey: 'your-key', locationConfig: LocationConfig( trackingMode: LocationTrackingMode.onAppStart, ), ), ); ``` -------------------------------- ### Integrate Firebase Cloud Messaging for Push Notifications Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/feature-guides.md Set up Firebase Cloud Messaging to receive push notifications. This involves getting the FCM token, registering it with Customer.io, and handling foreground and background messages. ```dart import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:customer_io/customer_io.dart'; void setupPushNotifications() async { final messaging = FirebaseMessaging.instance; // Get FCM token and register final token = await messaging.getToken(); if (token != null) { CustomerIO.instance.registerDeviceToken(deviceToken: token); } // Listen for token refresh messaging.onTokenRefresh.listen((newToken) { CustomerIO.instance.registerDeviceToken(deviceToken: newToken); }); // Handle foreground messages FirebaseMessaging.onMessage.listen((RemoteMessage message) { final handled = await CustomerIO.pushMessaging.onMessageReceived( message.data, handleNotificationTrigger: true, ); if (!handled) { // Handle in your own way } }); // Handle background messages FirebaseMessaging.onBackgroundMessage((RemoteMessage message) { return CustomerIO.pushMessaging.onBackgroundMessageReceived(message.data); }); } // Unregister on logout void cleanup() { CustomerIO.instance.deleteDeviceToken(); } ``` -------------------------------- ### Initialize CustomerIO SDK and Services Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/quick-reference.md Initialize the SDK with configuration, register the push token, identify the user, and subscribe to events. ```dart import 'package:customer_io/customer_io.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // 1. Initialize SDK await CustomerIO.initialize( config: CustomerIOConfig( cdpApiKey: 'your-api-key', region: Region.us, inAppConfig: InAppConfig(siteId: 'your-site-id'), ), ); // 2. Register push token final token = await FirebaseMessaging.instance.getToken(); if (token != null) { CustomerIO.instance.registerDeviceToken(deviceToken: token); } // 3. Identify user CustomerIO.instance.identify( userId: 'user@example.com', traits: {'firstName': 'John'}, ); // 4. Listen to events CustomerIO.inAppMessaging.subscribeToEventsListener((event) { print('Event: ${event.eventType}'); }); runApp(const MyApp()); } ``` -------------------------------- ### Initialize the SDK Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/README.md Initialize the Customer.io SDK with your workspace configuration. This is a required first step before using any other SDK features. ```dart await CustomerIO.initialize( config: CustomerIOConfig( cdpApiKey: 'your-key', region: Region.us, inAppConfig: InAppConfig(siteId: 'your-site-id'), ), ); ``` -------------------------------- ### CustomerIO.initialize Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/customer_io.md Initializes the Customer.io SDK with the provided configuration. This method must be called before any other SDK functionality can be accessed. Subsequent calls after the first one are ignored. ```APIDOC ## initialize ### Description Initializes the Customer.io SDK with the provided configuration. Must be called before accessing any other SDK functionality. If called multiple times, subsequent calls are ignored. ### Method Signature `static Future initialize({required CustomerIOConfig config})` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config** (CustomerIOConfig) - Required - Configuration object containing SDK settings ### Request Example ```dart await CustomerIO.initialize( config: CustomerIOConfig( cdpApiKey: 'your-cdp-api-key', region: Region.us, logLevel: CioLogLevel.debug, inAppConfig: InAppConfig(siteId: 'your-site-id'), ), ); ``` ### Response #### Success Response `Future` #### Response Example None (asynchronous operation) ERROR HANDLING: Logs warning if already initialized ``` -------------------------------- ### Dynamic Element ID Update Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/inline_in_app_message_view.md Example demonstrating how to dynamically update the elementId for the InlineInAppMessageView based on widget properties. ```dart // Widget will automatically notify native side of element ID change InlineInAppMessageView( elementId: isPromotion ? 'banner-promo' : 'banner-default', onActionClick: _handleAction, ) ``` -------------------------------- ### Initialize Customer.io SDK Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/feature-guides.md Initialize the Customer.io SDK with your API key and region. This is a required first step before using other SDK features. ```dart import 'package:customer_io/customer_io.dart'; // Initialize await CustomerIO.initialize( config: CustomerIOConfig( cdpApiKey: 'your-cdp-api-key', region: Region.us, ), ); // Identify user CustomerIO.instance.identify( userId: 'user@example.com', traits: { 'firstName': 'John', 'lastName': 'Doe', 'createdAt': DateTime.now().toIso8601String(), }, ); ``` -------------------------------- ### Get Messages Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/notification_inbox.md Retrieves inbox messages asynchronously for the currently identified user. Supports filtering by a specific topic. ```APIDOC ## Get Messages ```dart Future> getMessages({String? topic}) ``` ### Description Retrieves inbox messages asynchronously for the currently identified user. ### Method GET (Conceptual - SDK method) ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters - **topic** (String?) - Optional - Optional topic filter. Returns only messages with this topic. Case-insensitive. #### Request Body None ### Request Example ```dart final inbox = CustomerIO.inAppMessaging.inbox; final allMessages = await inbox.getMessages(); print('Total: ${allMessages.length} messages'); final promotions = await inbox.getMessages(topic: 'promotions'); print('Promotions: ${promotions.length} messages'); ``` ### Response #### Success Response - **List** - A list of inbox messages. #### Response Example (Example not provided in source, returns a list of InboxMessage objects) ``` -------------------------------- ### Initialization Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/API-INDEX.md Methods for initializing and accessing the Customer.io Flutter SDK instance. The `initialize` method must be called first to set up the SDK with the necessary configuration. ```APIDOC ## Initialization **Module**: `package:customer_io/customer_io.dart` **Main Class**: `CustomerIO` ### Static Methods | Method | Returns | Description | |--------|---------|-------------| | `initialize({required CustomerIOConfig config})` | `Future` | Initialize SDK with configuration. Must be called first. | | `get instance` | `CustomerIO` | Get singleton instance after initialization | | `createInstance(...)` | `CustomerIO` | Create test instance with mock implementations (testing only) | | `reset()` | `void` | Reset singleton (testing only) | | `get pushMessaging` | `CustomerIOMessagingPushPlatform` | Access push notification API | | `get inAppMessaging` | `CustomerIOMessagingInAppPlatform` | Access in-app messaging API | | `get location` | `CustomerIOLocationPlatform` | Access location tracking API | ``` -------------------------------- ### Get All Inbox Messages Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/notification_inbox.md Retrieves all inbox messages for the current user. Use this when you need a snapshot of all available messages. ```dart final inbox = CustomerIO.inAppMessaging.inbox; final allMessages = await inbox.getMessages(); print('Total: ${allMessages.length} messages'); ``` -------------------------------- ### CustomerIO.instance Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/customer_io.md Returns the singleton instance of CustomerIO. This allows access to other SDK functionalities like identify, track, etc. An exception is thrown if the SDK has not been initialized. ```APIDOC ## instance ### Description Returns the singleton instance of CustomerIO. Throws `StateError` if SDK has not been initialized. ### Method Signature `static CustomerIO get instance` ### Parameters None ### Request Example ```dart final customerIO = CustomerIO.instance; customerIO.identify(userId: 'user@example.com'); ``` ### Response #### Success Response `CustomerIO` - The singleton instance of the CustomerIO class. #### Response Example None (returns an object instance) ``` -------------------------------- ### CustomerIOConfig Initialization Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/API-INDEX.md Configure the CustomerIO SDK with your CDP API key and other optional settings like region, logging, and host configurations. ```dart CustomerIOConfig( cdpApiKey: 'string', // Required: CDP API key region: Region.us | Region.eu, // Optional: Data center region logLevel: CioLogLevel, // Optional: Log level autoTrackDeviceAttributes: bool, // Optional: Auto-track device info trackApplicationLifecycleEvents: bool, // Optional: Auto-track app lifecycle apiHost: String, // Optional: Custom API host cdnHost: String, // Optional: Custom CDN host flushAt: int, // Optional: Event batch size flushInterval: int, // Optional: Flush interval (ms) screenViewUse: ScreenView, // Optional: Screen event handling inAppConfig: InAppConfig, // Optional: In-app messaging config pushConfig: PushConfig, // Optional: Push notification config locationConfig: LocationConfig, // Optional: Location tracking config migrationSiteId: String, // Optional: Legacy site ID ) ``` -------------------------------- ### CustomerIO Configuration Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/API-INDEX.md Configuration options for initializing and customizing the CustomerIO SDK. ```APIDOC ## `CustomerIOConfig` ### Description The main configuration object used when initializing the CustomerIO SDK. It allows for setting API keys, region, logging levels, and various tracking and messaging behaviors. ### Parameters - **cdpApiKey** (String) - Required - Your Customer Data Platform API key. - **region** (Region.us | Region.eu) - Optional - Specifies the data center region (US or EU). - **logLevel** (CioLogLevel) - Optional - Sets the verbosity of SDK logs. - **autoTrackDeviceAttributes** (bool) - Optional - Enables automatic tracking of device information. - **trackApplicationLifecycleEvents** (bool) - Optional - Enables automatic tracking of application start, background, and foreground events. - **apiHost** (String) - Optional - Allows specifying a custom API host. - **cdnHost** (String) - Optional - Allows specifying a custom CDN host. - **flushAt** (int) - Optional - Defines the batch size for events before they are sent. - **flushInterval** (int) - Optional - Sets the interval in milliseconds for flushing batched events. - **screenViewUse** (ScreenView) - Optional - Configures how screen view events are handled. - **inAppConfig** (InAppConfig) - Optional - Configuration for in-app messaging features. - **pushConfig** (PushConfig) - Optional - Configuration for push notification features. - **locationConfig** (LocationConfig) - Optional - Configuration for location tracking features. - **migrationSiteId** (String) - Optional - Your legacy Customer.io site ID, used for migration purposes. ``` ```APIDOC ## Related Configs ### `InAppConfig` - **siteId** (String) - Required for in-app messaging. ### `PushConfig` - **android** (PushConfigAndroid) - Configuration specific to Android push notifications. ### `PushConfigAndroid` - **pushClickBehavior** (PushClickBehaviorAndroid) - Defines the behavior when an Android push notification is clicked. ### `LocationConfig` - **trackingMode** (LocationTrackingMode) - Controls how location tracking operates (off, manual, onAppStart). ``` -------------------------------- ### Constructor Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/notification_inbox.md Creates a NotificationInbox instance. You can access the inbox via `CustomerIO.inAppMessaging.inbox` or instantiate it directly, optionally providing a platform instance. ```APIDOC ## Constructor ```dart NotificationInbox({CustomerIOMessagingInAppPlatform? platform}) ``` ### Description Creates a NotificationInbox instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | platform | CustomerIOMessagingInAppPlatform? | No | null | Optional platform instance. If null, uses the default platform singleton. | ### Example ```dart final inbox = NotificationInbox(); // or final inbox = CustomerIO.inAppMessaging.inbox; ``` ``` -------------------------------- ### Get messages from inbox Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/quick-reference.md Retrieves and manages messages from the notification inbox, including filtering, marking as opened/deleted, and tracking clicks. ```APIDOC ## Notification Inbox ### Get messages Retrieves and manages messages from the notification inbox, including filtering, marking as opened/deleted, and tracking clicks. ```dart // Get messages final messages = await CustomerIO.inAppMessaging.getMessages(); // Stream messages CustomerIO.inAppMessaging.messages().listen((messages) { print('Messages: ${${messages.length}}'); }); // Filter by topic final alerts = await CustomerIO.inAppMessaging.getMessages(topic: 'alerts'); // Mark message as opened await CustomerIO.inAppMessaging.markInboxMessageOpened(message: message); // Mark message as deleted await CustomerIO.inAppMessaging.markInboxMessageDeleted(message: message); // Track message click CustomerIO.inAppMessaging.trackInboxMessageClicked( message: message, actionName: 'cta_button', ); ``` ``` -------------------------------- ### Access Singleton Instance Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/README.md Access the main instance of the CustomerIO SDK using the singleton pattern. Ensure `initialize()` is called before using the instance. ```dart CustomerIO.instance ``` -------------------------------- ### Create Mock CustomerIO Instance for Testing Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/feature-guides.md For testing purposes, create a `CustomerIO` instance by injecting mock platform implementations. This allows for isolated unit testing. ```dart // For testing, create instance with mock platforms @visibleForTesting static CustomerIO createInstance({ CustomerIOPlatform? platform, CustomerIOMessagingPushPlatform? pushMessaging, CustomerIOMessagingInAppPlatform? inAppMessaging, CustomerIOLocationPlatform? location, }) { // Allows you to inject mock implementations } ``` -------------------------------- ### Dismiss and Get Token Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/feature-guides.md Dismiss the current in-app message and retrieve the registered device token for push notification targeting. ```dart // Dismiss current message CustomerIO.inAppMessaging.dismissMessage(); // Get registered token for targeting final token = await CustomerIO.pushMessaging.getRegisteredDeviceToken(); ``` -------------------------------- ### Get Inbox Messages Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/README.md Retrieve all available messages from the user's inbox. This can be used to display messages within your application. ```dart // Get inbox messages final messages = await CustomerIO.inAppMessaging.getMessages(); ``` -------------------------------- ### Get Inbox Messages Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/messaging_in_app.md Fetches a list of inbox messages for the currently identified user. Optionally filters messages by a specific topic. ```APIDOC ## Get Inbox Messages ### Description Fetches a list of inbox messages for the currently identified user. Optionally filters by topic. ### Method `Future> getMessages({String? topic})` ### Parameters #### Query Parameters - **topic** (String?) - Optional - Optional topic filter. If provided, only messages with this topic are returned. Case-insensitive matching. ### Returns `Future>` — A list of inbox messages ### Example ```dart final messages = await CustomerIO.inAppMessaging.getMessages(); print('Total messages: ${messages.length}'); // Get messages for a specific topic final promotions = await CustomerIO.inAppMessaging.getMessages(topic: 'promotions'); ``` ``` -------------------------------- ### Custom API and CDN Hosts Configuration Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/feature-guides.md Configure the SDK to use custom API and CDN endpoints by providing their URLs in the `CustomerIOConfig` during initialization. ```dart await CustomerIO.initialize( config: CustomerIOConfig( cdpApiKey: 'your-key', apiHost: 'https://custom-api.example.com', cdnHost: 'https://custom-cdn.example.com', ), ); ``` -------------------------------- ### PushConfig Initialization Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/API-INDEX.md Configure push notification settings, including platform-specific options. ```dart PushConfig(android: PushConfigAndroid) ``` -------------------------------- ### SDK Access Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/quick-reference.md Accesses to the main SDK, push messaging, in-app messaging, inbox, and location services are available through singleton instances after initialization. ```APIDOC ## SDK Access All SDK operations are accessed through the singleton `CustomerIO.instance` after initialization. ```dart // Access main SDK CustomerIO.instance.identify(userId: 'user@example.com'); CustomerIO.instance.track(name: 'purchase'); // Access push messaging await CustomerIO.pushMessaging.getRegisteredDeviceToken(); CustomerIO.pushMessaging.onMessageReceived(message); // Access in-app messaging await CustomerIO.inAppMessaging.getMessages(); CustomerIO.inAppMessaging.dismissMessage(); // Access inbox final inbox = CustomerIO.inAppMessaging.inbox; await inbox.getMessages(); // Access location CustomerIO.location.setLastKnownLocation(latitude: 37.7749, longitude: -122.4194); ``` ``` -------------------------------- ### Get Inbox Messages Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/API-INDEX.md Retrieves a list of in-app messages available for the current user from the inbox. This is used to display messages within the application. ```APIDOC ## Get Inbox Messages ### Description Retrieves a list of in-app messages available for the current user from the inbox. This is used to display messages within the application. ### Method ```dart CustomerIO.inAppMessaging.getMessages ``` ### Returns - A `Future` that resolves to a list of in-app message objects. ``` -------------------------------- ### Get Inbox Messages by Topic Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/notification_inbox.md Retrieves inbox messages filtered by a specific topic. Use this to fetch messages related to a particular category. ```dart final promotions = await inbox.getMessages(topic: 'promotions'); print('Promotions: ${promotions.length} messages'); ``` -------------------------------- ### Core SDK (Data Pipelines) Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/API-INDEX.md Methods for tracking user activity and managing user/device data. This includes identifying users, tracking custom events and screen views, and managing device tokens and attributes. ```APIDOC ## Core SDK (Data Pipelines) **Module**: `package:customer_io/customer_io.dart` **Access**: `CustomerIO.instance` ### User Identification | Method | Parameters | Returns | Description | |--------|-----------|---------|-------------| | `identify()` | userId: String, traits?: Map | void | Identify user and set profile attributes | | `clearIdentify()` | — | void | Stop identifying current user | ### Event Tracking | Method | Parameters | Returns | Description | |--------|-----------|---------|-------------| | `track()` | name: String, properties?: Map | void | Track custom event | | `screen()` | title: String, properties?: Map | void | Track screen view | ### Device Management | Method | Parameters | Returns | Description | |--------|-----------|---------|-------------| | `registerDeviceToken()` | deviceToken: String | void | Register push token for identified user | | `deleteDeviceToken()` | — | void | Unregister push token | | `setDeviceAttributes()` | attributes: Map | void | Set device-level attributes | | `setProfileAttributes()` | attributes: Map | void | Set user profile attributes | ### Metrics | Method | Parameters | Returns | Description | |--------|-----------|---------|-------------| | `trackMetric()` | deliveryID: String, deviceToken: String, event: MetricEvent | void | Track push metric (delivered/opened/converted) | ``` -------------------------------- ### Create NotificationInbox Instance Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/notification_inbox.md Instantiate NotificationInbox using the default platform or by providing a specific platform instance. ```dart final inbox = NotificationInbox(); // or final inbox = CustomerIO.inAppMessaging.inbox; ``` -------------------------------- ### CustomerIOConfig Class Definition Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/configuration.md Defines the main configuration class for the SDK. It holds all settings for initialization, including API keys, regions, logging levels, and feature-specific configurations. ```dart class CustomerIOConfig { final String cdpApiKey; final String? migrationSiteId; final Region? region; final CioLogLevel? logLevel; final bool? trackApplicationLifecycleEvents; final bool? autoTrackDeviceAttributes; final String? apiHost; final String? cdnHost; final int? flushAt; final int? flushInterval; final ScreenView? screenViewUse; final InAppConfig? inAppConfig; final PushConfig pushConfig; final LocationConfig? locationConfig; CustomerIOConfig({ required this.cdpApiKey, this.migrationSiteId, this.region, this.logLevel, this.autoTrackDeviceAttributes, this.trackApplicationLifecycleEvents, this.apiHost, this.cdnHost, this.flushAt, this.flushInterval, this.screenViewUse, this.inAppConfig, PushConfig? pushConfig, this.locationConfig, }) : pushConfig = pushConfig ?? PushConfig(); } ``` -------------------------------- ### Access SDK Instances Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/quick-reference.md Access the main SDK instance, push messaging, in-app messaging, inbox, and location modules after initialization. ```dart // Access main SDK CustomerIO.instance.identify(userId: 'user@example.com'); CustomerIO.instance.track(name: 'purchase'); // Access push messaging await CustomerIO.pushMessaging.getRegisteredDeviceToken(); CustomerIO.pushMessaging.onMessageReceived(message); // Access in-app messaging await CustomerIO.inAppMessaging.getMessages(); CustomerIO.inAppMessaging.dismissMessage(); // Access inbox final inbox = CustomerIO.inAppMessaging.inbox; await inbox.getMessages(); // Access location CustomerIO.location.setLastKnownLocation(latitude: 37.7749, longitude: -122.4194); ``` -------------------------------- ### Get Registered Device Token Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/messaging_push.md Retrieves the current device token registered with the Customer.io SDK for push notifications. Returns null if no token is registered. ```dart final token = await CustomerIO.pushMessaging.getRegisteredDeviceToken(); if (token != null) { print('Registered token: $token'); } else { print('No token registered'); } ``` -------------------------------- ### LocationConfig Initialization Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/API-INDEX.md Configure location tracking settings, specifying the tracking mode. ```dart LocationConfig(trackingMode: LocationTrackingMode) ``` -------------------------------- ### LocationTrackingMode Enum Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/types.md Specifies the location tracking behavior of the SDK. Options include disabling tracking, manual control, or automatic tracking on app start. ```dart enum LocationTrackingMode { off(rawValue: 'OFF'), manual(rawValue: 'MANUAL'), onAppStart(rawValue: 'ON_APP_START'); const LocationTrackingMode({required String rawValue}); final String rawValue; } ``` ```dart LocationConfig( trackingMode: LocationTrackingMode.manual, ) ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/feature-guides.md Configure the SDK to log detailed debug information by setting `logLevel` to `CioLogLevel.debug`. ```dart await CustomerIO.initialize( config: CustomerIOConfig( cdpApiKey: 'your-key', logLevel: CioLogLevel.debug, // See all SDK logs ), ); ``` -------------------------------- ### Get Push Notification Token Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/README.md Retrieve the registered device token for push notifications. The method returns null if an error occurs, adhering to the fire-and-forget design. ```dart final token = await CustomerIO.pushMessaging.getRegisteredDeviceToken(); // token is null if error occurs ``` -------------------------------- ### InAppConfig Initialization Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/API-INDEX.md Configure in-app messaging specific settings, including the site ID. ```dart InAppConfig(siteId: String) ``` -------------------------------- ### Get Registered Device Token Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/messaging_push.md Retrieves the device token currently registered with the Customer.io SDK for push notifications. This is useful for debugging or for sending targeted push notifications. ```APIDOC ## Get Registered Device Token ### Description Retrieves the device token currently registered with the Customer.io SDK for push notifications. ### Method `Future getRegisteredDeviceToken()` ### Returns `Future` — The registered device token, or null if no token is registered. ### Example ```dart final token = await CustomerIO.pushMessaging.getRegisteredDeviceToken(); if (token != null) { print('Registered token: $token'); } else { print('No token registered'); } ``` ``` -------------------------------- ### CustomerIO.pushMessaging Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/customer_io.md Provides access to the push messaging platform instance, enabling handling of push notifications and related functionalities. ```APIDOC ## pushMessaging ### Description Returns the push messaging platform instance for handling push notifications. ### Method Signature `static CustomerIOMessagingPushPlatform get pushMessaging` ### Parameters None ### Request Example ```dart final token = await CustomerIO.pushMessaging.getRegisteredDeviceToken(); ``` ### Response #### Success Response `CustomerIOMessagingPushPlatform` - An instance of the push messaging platform. #### Response Example None (returns an object instance) ``` -------------------------------- ### Date/Time Handling: Sending and Receiving Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/message-schema.md Illustrates how dates are handled, stored as `DateTime` objects internally but transmitted as milliseconds since epoch. Shows conversion for sending and receiving. ```dart // Sending to native final toMap = message.toMap(); final sentTimestamp = toMap['sentAt']; // int: milliseconds since epoch // Receiving from native final fromMap = { 'sentAt': 1716547200000, // milliseconds since epoch }; final message = InboxMessage.fromMap(fromMap); final sentAt = message.sentAt; // DateTime object ``` -------------------------------- ### PushConfigAndroid Initialization Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/API-INDEX.md Configure Android-specific push notification behavior, such as click handling. ```dart PushConfigAndroid(pushClickBehavior: PushClickBehaviorAndroid) ``` -------------------------------- ### CustomerIO.inAppMessaging Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/customer_io.md Provides access to the in-app messaging platform instance, used for managing in-app messages and the user's inbox. ```APIDOC ## inAppMessaging ### Description Returns the in-app messaging platform instance for managing in-app messages and inbox. ### Method Signature `static CustomerIOMessagingInAppPlatform get inAppMessaging` ### Parameters None ### Request Example ```dart final messages = await CustomerIO.inAppMessaging.getMessages(); ``` ### Response #### Success Response `CustomerIOMessagingInAppPlatform` - An instance of the in-app messaging platform. #### Response Example None (returns an object instance) ``` -------------------------------- ### Location Configuration Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/location.md Configure location tracking behavior using LocationConfig during initialization. The default tracking mode is manual. ```dart LocationConfig( trackingMode: LocationTrackingMode.manual, // default ) ``` -------------------------------- ### InAppConfig Class Definition Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/configuration.md Defines the configuration for in-app messaging. Requires a `siteId` to be provided. ```dart class InAppConfig { final String siteId; InAppConfig({required this.siteId}); Map toMap() } ``` -------------------------------- ### Location Tracking Methods Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/API-INDEX.md Methods for managing and capturing the device's location. ```APIDOC ## `setLastKnownLocation()` ### Description Sets the last known geographical location of the device. ### Method `setLastKnownLocation` ### Parameters #### Request Body - **latitude** (double) - Required - The latitude coordinate. - **longitude** (double) - Required - The longitude coordinate. ### Returns void ``` ```APIDOC ## `requestLocationUpdate()` ### Description Initiates a request to capture the device's current geographical location. ### Method `requestLocationUpdate` ### Parameters None ### Returns void ``` -------------------------------- ### Track Events with Customer.io Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/feature-guides.md Track user actions and events, with or without associated properties. This includes simple events, events with detailed properties, and screen views for analytics. ```dart // Simple event CustomerIO.instance.track(name: 'app_opened'); // Event with properties CustomerIO.instance.track( name: 'purchase_completed', properties: { 'orderId': '12345', 'amount': 99.99, 'currency': 'USD', 'items': [ {'id': 'item1', 'quantity': 2}, {'id': 'item2', 'quantity': 1}, ], }, ); // Track screen views for analytics CustomerIO.instance.screen( title: 'HomePage', properties: {'referrer': 'search'}, ); ``` -------------------------------- ### registerDeviceToken Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/customer_io.md Registers a push notification device token with Customer.io for the currently identified user. The user must be identified before registering a token. ```APIDOC ## registerDeviceToken ### Description Registers a push notification device token with Customer.io for the currently identified user. The user must be identified before registering a token. ### Method Signature ```dart void registerDeviceToken({required String deviceToken}) ``` ### Parameters #### Path Parameters - **deviceToken** (String) - Required - FCM registration token (Android) or APNS token (iOS) ### Example ```dart final token = await firebaseMessaging.getToken(); if (token != null) { CustomerIO.instance.registerDeviceToken(deviceToken: token); } ``` ``` -------------------------------- ### Location Module Not Enabled Warning Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/location.md This message is printed in debug builds when the location module is not enabled in the native configuration. ```text Customer.io: Location module is not enabled. To use location features, add the location subspec to your Podfile (iOS) or set customerio_location_enabled=true in gradle.properties (Android). ``` -------------------------------- ### Handle Firebase Push Messages with CustomerIO Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/quick-reference.md Integrate Firebase push message handling with CustomerIO's SDK for incoming and background messages. ```dart FirebaseMessaging.onMessage.listen((RemoteMessage message) { CustomerIO.pushMessaging.onMessageReceived( message.data, handleNotificationTrigger: true, ); }); FirebaseMessaging.onBackgroundMessage((RemoteMessage message) { return CustomerIO.pushMessaging.onBackgroundMessageReceived(message.data); }); ``` -------------------------------- ### Message Topics for Filtering Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/message-schema.md Demonstrates how to assign multiple topics to an `InboxMessage` for organization and filtering. Shows how to retrieve messages by a specific topic. ```dart // Message with multiple topics final message = InboxMessage( // ... other fields topics: ['promotions', 'weekly-digest', 'featured'], ); // Get all promotional messages final promotions = await CustomerIO.inAppMessaging.getMessages(topic: 'promotions'); // This message will be included in both: // - getMessages(topic: 'promotions') // - getMessages(topic: 'weekly-digest') // - getMessages(topic: 'featured') // - getMessages() (all messages) ``` -------------------------------- ### CustomerIO.location Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/customer_io.md Provides access to the location platform instance, enabling management of location tracking features. ```APIDOC ## location ### Description Returns the location platform instance for managing location tracking. ### Method Signature `static CustomerIOLocationPlatform get location` ### Parameters None ### Request Example ```dart CustomerIO.location.setLastKnownLocation(latitude: 37.7749, longitude: -122.4194); ``` ### Response #### Success Response `CustomerIOLocationPlatform` - An instance of the location platform. #### Response Example None (returns an object instance) ``` -------------------------------- ### InAppMessage Constructor Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/api-reference/inline_in_app_message_view.md Represents the metadata for an in-app message. Used to pass message details to callbacks. ```dart const InAppMessage({ required String messageId, String? deliveryId, String? elementId, }) ``` -------------------------------- ### Identify and Track Events Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/feature-guides.md Use `identify` to set user attributes and `track` to record events. These methods operate with fire-and-forget semantics and do not throw errors. ```dart // These methods don't throw or return errors CustomerIO.instance.identify(userId: 'user@example.com'); CustomerIO.instance.track(name: 'event'); ``` -------------------------------- ### Track Custom Events and Screens Source: https://github.com/customerio/customerio-flutter/blob/main/_autodocs/quick-reference.md Track custom events with properties, screen views with titles and properties, or push notification metrics. ```dart // Track a custom event CustomerIO.instance.track( name: 'purchase', properties: {'amount': 99.99, 'itemCount': 3}, ); // Track screen view CustomerIO.instance.screen( title: 'ProductDetailsScreen', properties: {'productId': 'product-123'}, ); // Track push metric CustomerIO.instance.trackMetric( deliveryID: 'delivery-123', deviceToken: 'device-token', event: MetricEvent.opened, ); ```