Aller au contenu principal

Flutter SDK Integration Guide

Your dedicated account representative will help configure your account for the platforms that you are targeting with your Flutter App. They will provide you with both the key (iOS/Android/Web) and secret (iOS/Android) required to initialize the SDK and additional resources needed to render the most relevant experiences for your customers.

remarque

These instructions require development resources to complete. If you require additional assistance, please reach out to your Rokt account manager. Shopify stores can set up a Rokt placement in seconds using the Rokt Ecommerce app — no coding needed!

1. Flutter setup

Add the Flutter SDK as a dependency to your Flutter application:

flutter pub add mparticle_flutter_sdk

After adding the Rokt Flutter SDK dependency to your application, the following (or similar) lines are added to your package’s pubspec.yaml file:

dependencies:
mparticle_flutter_sdk: ^1.1.0

Import the package into your Dart code and get an instance of mParticle:

import 'package:mparticle_flutter_sdk/mparticle_flutter_sdk.dart';

MparticleFlutterSdk? mpInstance = await MparticleFlutterSdk.getInstance();

After installing the Dart plugin, continue integrating the Rokt SDK into your mobile app or website by following the steps below. Be sure to include the key and secret provided by your account manager where required or you will see errors in your logs when launching your app or site.

import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';

1.1. Add the Rokt SDK to your iOS app

Using either SPM or CocoaPods, include the Rokt SDK in your application:

CocoaPods

To integrate the SDK using CocoaPods, specify it in your Podfile with:

ios/Podfile
pod 'mParticle-Apple-SDK', '~> 8.0'
pod 'mParticle-Rokt','~> 8.0'

SPM

To integrate the SDK using Swift Package Manager:

  1. Open your project in Xcode, and go to the "Package Dependencies" tab.
  2. Click the + button under the Packages list.
  3. Enter the repository URL https://github.com/mParticle/mparticle-apple-sdk in the search box on the top right, choose mparticle-apple-sdk from the list of packages, and change "Dependency Rule" to "Up to Next Major Version".
  4. Click the "Add Package" button on the bottom right, and choose either the "Package Product" called mParticle-Apple-SDK. If you'd like to use a version of the SDK that doesn't include location tracking support, choose mParticle-Apple-SDK-NoLocation.
  5. Repeat steps 3 & 4 for the Rokt Kit repository URL https://github.com/mparticle-integrations/mparticle-apple-integration-rokt.git.
    • If you choose the mParticle-Apple-SDK-NoLocation package product, you will need to import the SDK using import mParticle_Apple_SDK_NoLocation instead of import mParticle_Apple_SDK.

1.2. Initialize the Rokt SDK

To initialize the SDK, insert the following initialization snippet in your AppDelegate file:

attention
  • Make sure to replace your-key and your-secret with the key and secret provided by your dedicated Rokt team.

<Tabs queryString="codeLanguage" className="unique-tabs" defaultValue="Swift" values={[ {label: 'Swift', value: 'Swift'}, {label: 'Objective-C', value: 'Objective-C'}, ]}>

import mParticle_Apple_SDK

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Initialize the SDK
let options = MParticleOptions(key: "your-key",
secret: "your-secret")
// Specify the data environment with environment:
// Set it to .development if you are still testing your integration.
// Set it to .production if your integration is ready for production data.
// The default is .autoDetect which attempts to detect the environment automatically
options.environment = .development
MParticle.sharedInstance().start(with: options)
return true
}
#import <mParticle_Apple_SDK/mParticle.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

// Initialize the SDK
MParticleOptions *options = [MParticleOptions optionsWithKey:@"your-key"
secret:@"your-secret"];
// Specify the data environment with environment:
// Set it to MPEnvironmentDevelopment if you are still testing your integration.
// Set it to MPEnvironmentProduction if your integration is ready for production data.
// The default is MPEnvironmentAutoDetect which attempts to detect the environment automatically
options.environment = MPEnvironmentDevelopment;
[[MParticle sharedInstance] startWithOptions:options];

return YES;
}

Further setup

For further help, see the full iOS SDK Integration Guide.


2. Track User Attributes

You can use the Rokt SDK to collect user attributes separately from events. User attributes are separate from custom attributes when tracking events. The SDK will associate any user attributes collected in a given session with events triggered in the same session.

To collect user attributes, the following code should be run immediately after initializing the Rokt SDK before you log an event.

import 'package:mparticle_flutter_sdk/mparticle_flutter_sdk.dart';

// Retrieve the current user. This will only succeed if you have identified the user during SDK initialization or by calling the identify method.
var currentUser = await mpInstance?.getCurrentUser();

// Once you have successfully set the current user to `currentUser`, you can set user attributes with:
currentUser?.setUserAttribute('custom-attribute-name', 'custom-attribute-value');
// Note: all user attributes (including list attributes and tags) must have distinct names.

// Rokt recommends setting as many of the following user attributes as possible:
currentUser?.setUserAttribute(key: 'firstname', value: 'John');
currentUser?.setUserAttribute(key: 'lastname', value: 'Doe');
// Phone numbers can be formatted either as '1234567890', or '+1 (234) 567-8901'
currentUser?.setUserAttribute(key: 'mobile', value: '3125551515');
currentUser?.setUserAttribute(key: 'age', value: '33');
currentUser?.setUserAttribute(key: 'gender', value: 'M');
currentUser?.setUserAttribute(key: 'city', value: 'Brooklyn');
currentUser?.setUserAttribute(key: 'state', value: 'NY');
currentUser?.setUserAttribute(key: 'zip', value: '123456');
currentUser?.setUserAttribute(key: 'dob', value: 'yyyymmdd');
currentUser?.setUserAttribute(key: 'title', value: 'Mr');
currentUser?.setUserAttribute(key: 'language', value: 'en');
currentUser?.setUserAttribute(key: 'value', value: '52.25');
currentUser?.setUserAttribute(key: 'predictedltv', value: '136.23');

// You can create a user attribute to contain a list of values
var attributeList = <String>[];
attributeList.add('documentary');
attributeList.add('comedy');
attributeList.add('romance');
attributeList.add('drama');
currentUser?.setUserAttributeArray(key: 'favorite-genres', value: attributeList);

// To remove a user attribute, call removeUserAttribute and pass in the attribute name. All user attributes share the same key space.
currentUser?.removeUserAttribute(key: 'attribute-to-remove');

3. Capture Funnel Events

The Rokt SDK allows you to implement event tracking to collect data describing your users' journeys through your app. You can then use this data to optimize your users' experience.

There are three primary event types you can record with the SDK:

  • Screen View Events: These are events you can trigger when a screen of your app is loaded.
  • Custom Events: These are freeform events you create to track information specific to your app.
  • Commerce Events: These are events specific to ecommerce that can describe the different stages of the shopping experience, including adding items to a cart and making a final purchase.

When first integrating with the Rokt SDK, start by implementing screen view tracking. To learn about tracking custom and commerce events, see the Appendix.

Track screen views

One of the most basic event types you can track is the screen view. To log a screen view, call the mpInstance?.logScreenEvent() method as soon as the screen loads, passing in the name of the screen as a string and an optional hash map containing any descriptive attributes.

The name you pass in should be one of a limited set of screens, like 'homepage' or 'product detail page'.

import 'package:mparticle_flutter_sdk/events/screen_event.dart';

var screenInfo = {
'rating': '5',
'property_type': 'hotel'
};

ScreenEvent screenEvent = ScreenEvent(eventName: 'Details')
..customAttributes = screenInfo;
mpInstance?.logScreenEvent(screenEvent);

4. Show a Placement

The main value of the Rokt SDK is unlocked through the selectPlacements method, which serves a placement (or layout) that is hyper-relevant to your customers based on attributes you provide.

Once the Rokt integration has been initialized, you can call the selectPlacements method from the page where your layout will be rendered. It should be called as early as possible, and once all required attributes are available, to ensure the best experience for your users.

When calling selectPlacements you must provide at least the email, firstname, lastname, billingzipcode and confirmationref attributes.

final attributes = {
"email": "j.smith@example.com",
"firstname": "Jenny",
"lastname": "Smith",
"mobile": "(555)867-5309",
"postcode": "90210",
"country": "US"
};

// If you want to use custom fonts for your placement, create a fontTypefaces map
final fontTypefaces = {"Arial-Bold": "fonts/Arial-Bold.ttf"};

// You may also want to pass optional parameters such as `RoktConfig` which will allow you to customize the placement UI, primarily on whether or not the app is in dark or light mode. Additional optional parameters such as embedded views and events are shown lower.
final roktConfig = RoktConfig(
colorMode: ColorMode.light
);

mpInstance?.rokt.selectPlacements(
identifier: "RoktExperience",
attributes: attributes,
fontFilePathMap: fontTypefaces,
roktConfig: roktConfig
);

Optional functions

Embedded placements

Embedded placements share all of the same recommendations and requirements as overlay placements above but allow you to embed the placement views in your UI.

RoktLayout has a callback to notify when widget is created which could be utilized.

import 'package:mparticle_flutter_sdk/mparticle_flutter_sdk.dart';

const RoktLayout(
placeholderName: "RoktEmbedded1",
onLayoutCreated: () {
// Layout created
}
);

Events

The SDK also provides the events on each page as a stream through the MPRoktEvents EventChannel.

final EventChannel roktEventChannel = EventChannel('MPRoktEvents');
roktEventChannel.receiveBroadcastStream().listen((dynamic event) {
debugPrint("rokt_event: _receiveRoktEvent $event ");
});
EventDescriptionParams
ShowLoadingIndicatorTriggered before the SDK calls the Rokt backend
HideLoadingIndicatorTriggered when the SDK receives a success or failure from the Rokt backend
OfferEngagementTriggered when the user engages with the offerplacementId: String
PositiveEngagementTriggered when the user positively engages with the offerplacementId: String
FirstPositiveEngagementTriggered when the user positively engages with the offer for the first timeplacementId: String, fulfillmentAttributes: FulfillmentAttributes
PlacementInteractiveTriggered when a placement has been rendered and is interactableplacementId: String
PlacementReadyTriggered when a placement is ready to display but has not rendered content yetplacementId: String
PlacementClosedTriggered when a placement is closed by the userplacementId: String
PlacementCompletedTriggered when the offer progression reaches the end and no more offers are available to display.
Also triggered when cache is hit but the retrieved placement will not be displayed as it has previously been dismissed
placementId: String
PlacementFailureTriggered when a placement could not be displayed due to some failure or when no placements are available to showplacementId: String (optional)
OpenUrlTriggered when the user presses a URL that is configured to be sent to the partner appplacementId: String, url: String

Appendix

Using App Configurations

Applications can now pass the configuration settings from their own application environment. This allows Rokt SDK to use application's custom configurations instead of relying solely on system defaults.

ColorMode object
ValueDescription
lightApplication is in Light Mode
darkApplication is in Dark Mode
systemApplication defaults to System Color Mode
CacheConfig object
remarque

CacheConfig is only relevant for mobile integrations and can be ignored for web.

ParameterDescription
cacheDurationOptional duration in seconds for which the Rokt SDK should cache the experience. Maximum allowed value is 90 minutes and the default (if value is not provided or invalid) is 90 minutes.
cacheAttributesOptional attributes to be used as cache key. If null, all the attributes sent in selectPlacements will be used as the cache key.
final roktConfig = RoktConfig(
cacheConfig: CacheConfig(
cacheDurationInSeconds: 100,
cacheAttributes: attributes
)
);

mpInstance?.rokt.selectPlacements(
identifier: "RoktExperience",
attributes: attributes,
roktConfig: roktConfig
);

Track custom events

After implementing placements and screen view tracking by following the instructions above, you may want to implement additional event tracking.

You can define and track custom events by using the MPEvent.Builder object and passing in the event name, event type, and a map of custom attributes.

The supported custom event types for both Kotlin and Java are:

  • Navigation - Track user navigation flows and page transitions within your app
  • Location - Record user location-based interactions and movements
  • Search - Capture search queries and search-related user actions
  • Transaction - Log financial transactions and purchase-related activities
  • UserContent - Track user-generated content like reviews, comments, or posts
  • UserPreference - Record user settings, preferences, and customization choices
  • Social - Capture social media interactions and sharing activities
import 'package:mparticle_flutter_sdk/events/event_type.dart';
import 'package:mparticle_flutter_sdk/events/mp_event.dart';

final customAttributes = {
'category': 'Destination Intro',
'title': 'Paris',
};

MPEvent event = MPEvent(
eventName: 'Video Watched',
eventType: EventType.Navigation)
..customAttributes = customAttributes
mpInstance?.logEvent(event);

Track commerce events

Tracking a commerce event requires three steps:

  1. Defining the product or products that are being purchased
  2. Creating an object to contain a transaction summary
  3. Logging the event, including your product definition and transaction summary
import 'package:mparticle_flutter_sdk/events/commerce_event.dart';
import 'package:mparticle_flutter_sdk/events/product.dart';
import 'package:mparticle_flutter_sdk/events/product_action_type.dart';
import 'package:mparticle_flutter_sdk/events/transaction_attributes.dart';

// 1. Create the products

// Create an optional map of custom attributes for the product as key/value pairs of strings
final customAttributes = {
'ocean-view': 'true',
'balcony': 'false',
};

Product product = Product(
name: 'Double Room - Econ Rate',
sku: 'econ-1',
price: 100.00,
product.quantity = 4;
);

// Include the map of custom attributes created above
product.attributes = customAttributes;

// 2. Summarize the transaction
final TransactionAttributes attributes =
TransactionAttributes(
transactionID: '12345',
revenue: 430.00,
tax: 30.00
);

// 3. Log the purchase event
CommerceEvent event = CommerceEvent.withProduct(
productActionType: ProductActionType.Purchase,
product: product
);
event.transactionAttributes = attributes;

// Optional custom attributes for the purchase event can be added as a map of key/value string pairs
event.customAttributes = {"sale": "true", "phone-booking": "true"};

// You can also create a map that is then passed through to the customAttributes builder method. For example:
// val customTransactionAttributes = mutableMapOf<String, String>()
// customTransactionAttributes["sale"] = "true"
// customTransactionAttributes["phone-booking"] = "true"
// .customAttributes(customTransactionAttributes)
mpInstance?.logCommerceEvent(event);
Cet article vous a-t-il été utile ?