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.
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:
pod 'mParticle-Apple-SDK', '~> 8.0'
pod 'mParticle-Rokt','~> 8.0'
SPM
To integrate the SDK using Swift Package Manager:
- Open your project in Xcode, and go to the "Package Dependencies" tab.
- Click the + button under the Packages list.
- Enter the repository URL
https://github.com/mParticle/mparticle-apple-sdk
in the search box on the top right, choosemparticle-apple-sdk
from the list of packages, and change "Dependency Rule" to "Up to Next Major Version". - 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, choosemParticle-Apple-SDK-NoLocation
. - 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 usingimport mParticle_Apple_SDK_NoLocation
instead ofimport mParticle_Apple_SDK
.
- If you choose the
1.2. Initialize the Rokt SDK
To initialize the SDK, insert the following initialization snippet in your AppDelegate file:
- Make sure to replace
your-key
andyour-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.
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';
1.1 Add dependencies
Update your gradle file to include the necessary dependencies for the SDK:
<Tabs queryString="gradleType" className="unique-tabs" defaultValue="build.gradle.kts" values={[ {label: 'build.gradle.kts', value: 'build.gradle.kts'}, {label: 'build.gradle', value: 'build.gradle'}, ]}>
dependencies {
implementation("com.mparticle:android-rokt-kit:5.70.2")
implementation("com.mparticle:android-core:5.70.2")
}
dependencies {
implementation "com.mparticle:android-rokt-kit:5.70.2"
implementation "com.mparticle:android-core:5.70.2"
}
1.2. Configure your Android classes
Ensure your root Android Activity extends FlutterFragmentActivity
import io.flutter.embedding.android.FlutterFragmentActivity
class MainActivity : FlutterFragmentActivity()
1.3. Initialize the SDK in your app
The Android SDK can be configured using an MParticleOptions
object and a builder class in the onCreate()
of the Application
class. The mParticle Android SDK should be initialized before any other SDK API calls are made.
Make sure to replace your-key
and your-secret
in the above code sample with the key and secret provided by your dedicated Rokt account representative.
<Tabs queryString="codeLanguage" className="unique-tabs" defaultValue="Kotlin" values={[ {label: 'Kotlin', value: 'Kotlin'}, {label: 'Java', value: 'Java'}, ]}>
import com.mparticle.MParticle
import com.mparticle.MParticleOptions
class YourApplicationClass : Application() {
override fun onCreate() {
super.onCreate()
val options: MParticleOptions = MParticleOptions.builder(this)
.credentials(
"your-key", // The key provided by your Rokt account representative
"your-secret" // The secret provided by your Rokt account representative
).environment(MParticle.Environment.Development) // 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
.build()
MParticle.start(options)
}
}
import com.mparticle.MParticle;
import com.mparticle.MParticleOptions;
public class YourApplicationClass extends Application {
@Override
public void onCreate() {
super.onCreate();
MParticleOptions options = MParticleOptions.builder(this)
.configuration(kitOptions)
.credentials(
"your-key", // The key provided by your Rokt account representative
"your-secret" // The secret provided by your Rokt account representative
).environment(MParticle.Environment.Production) // 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
.build();
MParticle.start(options);
}
}
Further setup
For more help, see the full Android SDK integration guide.
1.1. Initialize the Rokt SDK
To initialize the SDK, copy and paste the entire SDK initialization script into your site.
Every site is different, but Rokt recommends including the SDK initialization script on every page of your site. This ensures that the SDK always initializes, providing lowest offer delivery latency and the highest user identification accuracy.
- Single-page Applications (SPA): If your website is an SPA, insert the initialization script into the
<head>
of the mainindex.html
page, or the primary location where the rest of your content is rendered. - Multi-page Applications (MPA): If your website is an MPA and you use a template-base rendering system (most common), place the initialization script in the primary shared layout file. If you don’t use a template-based rendering system, place the script in each HTML file of your website.
Note that although each page may include the script, due to browser caching, the SDK will load from cache by default rather than being loaded upon each page load of your website.
SDK Initialization Script
- Replace
"YOUR_API_KEY"
with the API key provided by your dedicated Rokt team. - Set
DOMAIN
to the subdomain you created during your first-party domain configuration. This is optional: if you leave the default DOMAIN setting, requests will be routed throughapps.rokt-api.com
.
<script type="text/javascript">
// Enter your Rokt API key
const API_KEY = "YOUR_API_KEY";
// If you configured a first-party domain, set it as the value of DOMAIN instead of the default apps.rokt-api domain
const ROKT_DOMAIN = "https://apps.rokt-api.com";
// Set your SDK configuration settings
window.mParticle = {
config: {
// Specify the data environment with isDevelopmentMode:
// Set isDevelopmentMode to true if you are still testing your integration.
// Set isDevelopmentMode to false if your integration is ready for production data.
isDevelopmentMode: true,
// Identify the current user:
// If you have the user's email address, include it in an object called `userIdentities` within `identifyRequest` as shown below.
identifyRequest: {
userIdentities: {
// If you're using an un-hashed email address, set it in 'email'.
email: 'j.smith@example.com',
// If you're using a hashed email address, set it in 'other' instead of `email`.
other: 'sha256 hashed email goes here'
},
}
},
};
// Load the SDK
(function(e) { window.mParticle = window.mParticle || {}; window.mParticle.EventType = { Unknown: 0, Navigation: 1, Location: 2, Search: 3, Transaction: 4, UserContent: 5, UserPreference: 6, Social: 7, Other: 8, Media: 9 }; window.mParticle.eCommerce = { Cart: {} }; window.mParticle.Identity = {}; window.mParticle.Rokt = {}; window.mParticle.config = window.mParticle.config || {}; window.mParticle.config.rq = []; window.mParticle.config.snippetVersion = 2.6; window.mParticle.ready = function(e) { window.mParticle.config.rq.push(e); }; ["endSession", "logError", "logBaseEvent", "logEvent", "logForm", "logLink", "logPageView", "setSessionAttribute", "setAppName", "setAppVersion", "setOptOut", "setPosition", "startNewSession", "startTrackingLocation", "stopTrackingLocation"].forEach(function(e) { window.mParticle[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift(e); window.mParticle.config.rq.push(t); }; }); ["setCurrencyCode", "logCheckout"].forEach(function(e) { window.mParticle.eCommerce[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift("eCommerce." + e); window.mParticle.config.rq.push(t); }; }); ["identify", "login", "logout", "modify"].forEach(function(e) { window.mParticle.Identity[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift("Identity." + e); window.mParticle.config.rq.push(t); }; }); ["selectPlacements","hashAttributes","setExtensionData"].forEach(function(e) { window.mParticle.Rokt[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift("Rokt." + e); window.mParticle.config.rq.push(t); }; }); var t = window.mParticle.config.isDevelopmentMode ? 1 : 0, n = "?env=" + t, a = window.mParticle.config.dataPlan; if (a) { var o = a.planId, r = a.planVersion; o && (r && (r < 1 || r > 1e3) && (r = null), n += "&plan_id=" + o + (r ? "&plan_version=" + r : "")); } var i = window.mParticle.config.versions, s = []; i && Object.keys(i).forEach(function(e) { s.push(e + "=" + i[e]); }); var c = document.createElement("script"); c.type = "text/javascript"; c.async = !0; window.ROKT_DOMAIN = ROKT_DOMAIN || 'https://apps.rokt-api.com'; mParticle.config.domain = ROKT_DOMAIN.split('//')[1]; c.src = ROKT_DOMAIN + "/js/v2/" + e + "/app.js" + n + "&" + s.join("&"); var l = document.getElementsByTagName("script")[0]; l.parentNode.insertBefore(c, l); })(API_KEY);
</script>
The initialization script includes the following configuration settings:
isDevelopmentMode
In the example above, isDevelopmentMode
is set to true
. This allows you to test your SDK integration by collecting "development" data. When you are ready to go live with your integration, set isDevelopmentMode
to false
to collect and send production data to Rokt.
identifyRequest
The SDK allows you to identify the current user by including their email address at the time the SDK is initialized. Rokt recommends using your customer's raw (unhashed) email address for the identifier.
Further setup
For more help, see the full Web 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 ");
});
Event | Description | Params |
---|---|---|
ShowLoadingIndicator | Triggered before the SDK calls the Rokt backend | |
HideLoadingIndicator | Triggered when the SDK receives a success or failure from the Rokt backend | |
OfferEngagement | Triggered when the user engages with the offer | placementId: String |
PositiveEngagement | Triggered when the user positively engages with the offer | placementId: String |
FirstPositiveEngagement | Triggered when the user positively engages with the offer for the first time | placementId: String, fulfillmentAttributes: FulfillmentAttributes |
PlacementInteractive | Triggered when a placement has been rendered and is interactable | placementId: String |
PlacementReady | Triggered when a placement is ready to display but has not rendered content yet | placementId: String |
PlacementClosed | Triggered when a placement is closed by the user | placementId: String |
PlacementCompleted | Triggered 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 |
PlacementFailure | Triggered when a placement could not be displayed due to some failure or when no placements are available to show | placementId: String (optional) |
OpenUrl | Triggered when the user presses a URL that is configured to be sent to the partner app | placementId: 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
Value | Description |
---|---|
light | Application is in Light Mode |
dark | Application is in Dark Mode |
system | Application defaults to System Color Mode |
CacheConfig object
CacheConfig
is only relevant for mobile integrations and can be ignored for web.
Parameter | Description |
---|---|
cacheDuration | Optional 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. |
cacheAttributes | Optional 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 appLocation
- Record user location-based interactions and movementsSearch
- Capture search queries and search-related user actionsTransaction
- Log financial transactions and purchase-related activitiesUserContent
- Track user-generated content like reviews, comments, or postsUserPreference
- Record user settings, preferences, and customization choicesSocial
- 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:
- Defining the product or products that are being purchased
- Creating an object to contain a transaction summary
- 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);