Flutter SDK
Introduction
Welcome to the developer documentation for the Kameleoon Flutter SDK! Our SDK gives you the possibility of running experiments and activating feature flags on all platforms targeted by the Flutter application framework. Integrating our SDK into your applications is easy, and its footprint (in terms of memory and network usage) is low.
You can refer to the SDK reference
to check out all possible features of the SDK. Also make sure you check out our Getting started tutorial
which we have prepared to walk you through the installation and implementation.
Latest version of the Flutter SDK: 1.0.0.
Getting started
This guide is designed to help you integrate our SDK in a few minutes and start running experiments in your Flutter applications. This tutorial will explain the setup of a simple A/B test to change the number of recommended products based on different variations.
Creating an experiment
First, you must create an experiment in the Kameleoon back-office so that our platform is aware of the new A/B test you're planning to implement on your side. Make sure that mobile application type is chosen as shown below:
Upon successful creation of the experiment, you will need to get its ID to use in the SDK as an argument to the triggerExperiment()
method.
Installing the SDK
Installing the Flutter client
kameleoon_client_flutter: ^1.0.0
To install the Kameleoon Flutter client, declare a dependency on your pubspec.yaml
file:
Initializing the Kameleoon Client
import 'package:kameleoon_client_flutter/kameleoon_client.dart';
import 'package:kameleoon_client_flutter/kameleoon_client_factory.dart';
class _HomePage extends State<HomePage> {
KameleoonClient kameleoonClient
@override
void initState() {
super.initState();
kameleoonClient? = KameleoonClientFactory.create("a8st4f59bj");
}
}
After installing the SDK into your application and setting up an server-side experiment on Kameleoon's back-office, the next step is to create the Kameleoon client.
The code on the right gives a clear example. A Client is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you will need to run an experiment.
While executing the KameleoonClientFactory.create()
method initializes the client, on Android it is not immediately ready for use. This is because the current configuration of experiments and feature flags (along with their traffic repartition) has to be retrieved from a Kameleoon remote server. This requires network access, which is not always available. Until the Kameleoon client is fully ready, you should not try to run any other method in our SDK. Note that once the first configuration of experiments is fetched, it is then periodically refreshed, but even if the refresh fails for any reason, the Kameleoon client will still be ready and working (but on an outdated / previous configuration).
We provide the isReady()
method to check if the Kameleoon client initialization is finished.
Triggering an experiment
Running an A/B experiment on your Flutter application means bucketing your users into several groups (one per variation). The SDK takes care of this bucketing (and the associated reporting) automatically.
Triggering an experiment by calling the triggerExperiment()
method will register a random variation for a given visitorCode. If this visitorCode is already associated with a variation (most likely the user had already been exposed to the experiment previously), then it will return the previous variation associated with a given experiment.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:uuid/uuid.dart';
import 'package:kameleoon_client_flutter/kameleoon_client.dart';
import 'package:kameleoon_client_flutter/kameleoon_client_factory.dart';
import 'package:kameleoon_client_flutter/kameleoon_exception.dart' as KameleoonException;
class HomePage extends StatefulWidget {
@override
_HomePage createState() => _HomePage();
}
class _HomePage extends State<HomePage> {
KameleoonClient? kameleoonClient;
late int _recommendedProductsNumber;
@override
void initState() {
super.initState();
obtainVariationNumber();
}
Future<void> obtainVariationNumber() async {
kameleoonClient = KameleoonClientFactory.create("a8st4f59bj");
int? variationID;
if (kameleoonClient!.isReady() == true) {
try {
String visitorCode = Uuid().v4();
variationID = await kameleoonClient!.triggerExperiment(visitorCode, 75253); // usually, this would be the internal ID of the current user
} on KameleoonException.SDKNotReady {
// The user will not be counted into the experiment, but should see the reference variation
variationID = 0;
} on KameleoonException.ExperimentConfigurationNotFound {
variationID = 0;
} on KameleoonException.NotTargeted {
variationID = 0;
} on PlatformException {
variationID = 0;
}
}
else {
variationID = 0;
}
int recommendedProductsNumber = 5;
if (variationID == 0) {
//This is the default / reference number of products to display
recommendedProductsNumber = 5;
}
else if (variationID == 148382) {
//We are changing number of recommended products for this variation to 10
recommendedProductsNumber = 10;
}
else if (variationID == 187791) {
//We are changing number of recommended products for this variation to 8
recommendedProductsNumber = 8;
}
setState(() {
_recommendedProductsNumber = recommendedProductsNumber;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Kameleoon Example",
theme: ThemeData(),
home: Scaffold(
body: Container(
child: Text(
"Number of recommended products displayed: $_recommendedProductsNumber products."
)
)
),
);
}
}
We provide two code samples to illustrate the triggering of an experiment. The first one uses the isReady()
approach. It's a bit simpler.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:uuid/uuid.dart';
import 'package:kameleoon_client_flutter/kameleoon_client.dart';
import 'package:kameleoon_client_flutter/kameleoon_client_factory.dart';
import 'package:kameleoon_client_flutter/kameleoon_exception.dart' as KameleoonException;
class HomePage extends StatefulWidget {
@override
_HomePage createState() => _HomePage();
}
class _HomePage extends State<HomePage> {
KameleoonClient? kameleoonClient;
late int _recommendedProductsNumber;
@override
void initState() {
super.initState();
obtainVariationNumber();
}
Future<void> obtainVariationNumber() async {
kameleoonClient = KameleoonClientFactory.create("a8st4f59bj");
int? variationID;
int recommendedProductsNumber = 5;
kameleoonClient!.runWhenReady(() async {
try {
String visitorCode = Uuid().v4();
variationID = await kameleoonClient!.triggerExperiment(visitorCode, 75253); // usually, this would be the internal ID of the current user
} on KameleoonException.SDKNotReady {
// The user will not be counted into the experiment, but should see the reference variation
variationID = 0;
} on KameleoonException.ExperimentConfigurationNotFound {
variationID = 0;
} on KameleoonException.NotTargeted {
variationID = 0;
} on PlatformException {
variationID = 0;
}
int recommendedProductsNumber = 5;
if (variationID == 0) {
//This is the default / reference number of products to display
recommendedProductsNumber = 5;
}
else if (variationID == 148382) {
//We are changing number of recommended products for this variation to 10
recommendedProductsNumber = 10;
}
else if (variationID == 187791) {
//We are changing number of recommended products for this variation to 8
recommendedProductsNumber = 8;
}
setState(() {
_recommendedProductsNumber = recommendedProductsNumber;
});
}, () async {
variationID = 0;
recommendedProductsNumber = 5;
setState(() {
_recommendedProductsNumber = recommendedProductsNumber;
});
}, 1000)
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Kameleoon Example",
theme: ThemeData(),
home: Scaffold(
body: Container(
child: Text(
"Number of recommended products displayed: $_recommendedProductsNumber products."
)
)
),
);
}
}
This is a second example with the callback runWhenReady()
approach. Note that here we used a timeout of 1000 milliseconds.
Implementing variation code
late int recommendedProductsNumber;
if (variationID == 0) {
//This is the default / reference number of products to display
recommendedProductsNumber = 5;
}
else if (variationID == 148382) {
//We are changing number of recommended products for this variation to 10
recommendedProductsNumber = 10;
}
else if (variationID == 187791) {
//We are changing number of recommended products for this variation to 8
recommendedProductsNumber = 8;
}
To execute different code paths depending on the variation assigned to the visitor, you will need the list of all the experiment's variation IDs. You can find these variation IDs (as well as the experiment ID) by opening the experiment in the back-office interface. By convention, the reference (original variation) always has an ID equal to 0.
Once you have the IDs of the different variations, you can implement a different action for each variation, and one of the code paths will be executed, based on the associated variationID for the current visitor. Generally, this can be done using a simple if / else or switch mechanism. In our example, we just change the number of recommended products with two different variations.
Tracking conversion
String visitorCode = Uuid().v4();
int goalID = 83023;
await kameleoonClient!.trackConversion(visitorCode, goalID, 10);
After you are done with triggering an experiment, the next step is usually to start tracking conversions. This is done to measure performance characteristics according to the goals that make sense for your business.
For this purpose, use the trackConversion()
method of the SDK as shown in the example. You need to pass the visitorCode and goalID parameters so we can correctly track conversion for this particular user.
Obtaining results
Once your implementation is in place on the mobile app side (experiment triggering, variations handling, and conversion tracking), it is time to launch the experiment on the Kameleoon platform. You do this in the same way as for a front-end test. Basic operations such as starting, pausing and stopping the experiment work exactly in the same way.
After the experiment is launched, first results will be available on our standard results page in the back-office after a duration of 30 minutes. This is because (as is the case with front-end testing) visits are considered over after 30 minutes of inactivity. Inactivity in this context means the absence of calls sent to the Kameleoon back-end servers (such calls are made via triggerExperiment()
, trackConversion()
or flush()
methods).
Reference
This is a full reference documentation of the Flutter SDK.
If this is your first time working with the Flutter SDK, we strongly recommend you go over our Getting started tutorial
to integrate the SDK and start experimenting in a few minutes.
KameleoonClientFactory
create
kameleoonClient = KameleoonClientFactory.create(siteCode);
The starting point for using the SDK is the initialization step. All interaction with the SDK is done through an object named KameleoonClient, therefore you need to create this object.
Arguments
Name | Type | Description |
siteCode | String | Code of the website you want to run experiments on. This unique code id can be found in our platform's back-office. This field is mandatory. |
KameleoonClient
isReady
bool ready = kameleoonClient!.isReady();
For mobile SDKs, the initialization of the Kameleoon Client is not immediate, as it needs to perform a server call to retrieve the current configuration for all active experiments. It is recommended to check if the SDK is ready by calling this method before triggering an experiment. Alternatively, you could setup exception catching around the triggerExperiment()
method to look for the KameleoonException.SDKNotReady exception, or you could use the runWhenReady()
method with a callback as detailed in the next paragraph.
Arguments
Name | Type | Description |
Return value
Name | Type | Description |
ready | bool | Boolean representing the status of the SDK (properly initialized, or not yet ready to be used). |
runWhenReady
kameleoonClient!.runWhenReady(() async {
late int? variationID;
late int recommendedProductsNumber;
try {
variationID = await kameleoonClient!.triggerExperiment(mainApplication.getUserId(), 75253);
} on KameleoonException.SDKNotReady {
// The user will not be counted into the experiment, but should see the reference variation
variationID = 0;
} on KameleoonException.ExperimentConfigurationNotFound {
variationID = 0;
} on KameleoonException.NotTargeted {
variationID = 0;
} on PlatformException {
variationID = 0;
}
if (variationID == 0) {
// This is the default / reference number of products to display
recommendedProductsNumber = 5;
}
else if (variationID == 148382) {
// We are changing number of recommended products for this variation to 10
recommendedProductsNumber = 10;
}
else if (variationID == 187791) {
// We are changing number of recommended products for this variation to 8
recommendedProductsNumber = 8;
}
setState(() {
_recommendedProductsNumber = recommendedProductsNumber;
});
}, () async {
variationID = 0;
recommendedProductsNumber = 5;
setState(() {
_recommendedProductsNumber = recommendedProductsNumber;
});
}, 1000);
For mobile SDKs, the initialization of the Kameleoon Client is not immediate, as it needs to perform a server call to retrieve the current configuration for all active experiments. The runWhenReady()
method of the KameleoonClient class allows to pass a callback that will be executed as soon as the SDK is ready for use. It also allows the use of a timeout.
The first callback will be executed once the Kameleoon client is ready, and should contain code triggering an experiment and implementing variations. The second callback will be executed if the specified timeout happens before the client is initialized. Usually this case should implement the "reference" variation, as the user will be "out of the experiment" if a timeout takes place.
Arguments
Name | Type | Description |
readyCallback | Function | Callback object. This field is mandatory. |
failCallback | Function | Callback object. This field is mandatory. |
timeout | int | Timeout (in milliseconds). This field is optional, if not provided, it will use the default value of 2000 milliseconds. |
triggerExperiment
String visitorCode = Uuid().v4();
int experimentID = 75253;
late int variationID;
try {
variationID = await kameleoonClient!.triggerExperiment(visitorCode, experimentID);
} on KameleoonException.SDKNotReady {
// The user will not be counted into the experiment, but should see the reference variation
variationID = 0;
} on KameleoonException.ExperimentConfigurationNotFound {
// The user will not be counted into the experiment, but should see the reference variation
variationID = 0;
} on KameleoonException.NotTargeted {
// The user did not trigger the experiment, as the associated targeting segment conditions were not fulfilled. He should see the reference variation
variationID = 0;
} on PlatformException {
// This is generic Exception handler which will handle all exceptions.
print("Exception occured");
}
To trigger an experiment, call the triggerExperiment()
method of our SDK.
This method takes visitorCode and experimentID as mandatory arguments to register a variation for a given user. If such a user has never been associated with any variation, the SDK returns a randomly selected variation. In case a user with a given visitorCode is already registered with a variation, it will detect the previously registered variation and return the variationID.
You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.
Arguments
Name | Type | Description |
visitorCode | String | Unique identifier of the user. This field is mandatory. |
experimentID | int | ID of the experiment you want to expose to a user. This field is mandatory. |
Return value
Name | Type | Description |
variationID | int | ID of the variation that is registered for the given visitorCode. By convention, the reference (original variation) always has an ID equal to 0. |
Exceptions Thrown
Type | Description |
KameleoonException.SDKNotReady | Exception indicating that the SDK has not completed its initialization yet. |
KameleoonException.NotTargeted | Exception indicating that the current user did not trigger the required targeting conditions for this experiment. The targeting conditions are defined via Kameleoon's segment builder. |
KameleoonException.NotActivated | Exception indicating that the current user triggered the experiment (met the targeting conditions), but did not activate it. The most common reason for that is that part of the traffic has been excluded from the experiment and should not be tracked. |
KameleoonException.ExperimentConfigurationNotFound | Exception indicating that the request experiment ID has not been found in the internal configuration of the SDK. This is usually normal and means that the experiment has not yet been started on Kameleoon's side (but code triggering / implementing variations is already deployed on the mobile app's side). |
activateFeature
String visitorCode = Uuid().v4();
String featureKey = "new_checkout";
bool hasNewCheckout = false;
try {
hasNewCheckout = await kameleoonClient!.activateFeature(visitorCode, featureKey);
} on KameleoonException.SDKNotReady {
// SDK not initialized or feature toggle not yet activated on Kameleoon's side - we consider the feature inactive
hasNewCheckout = false;
} on KameleoonException.FeatureConfigurationNotFound {
// SDK not initialized or feature toggle not yet activated on Kameleoon's side - we consider the feature inactive
hasNewCheckout = false;
} on KameleoonException.NotTargeted {
// The user did not trigger the feature, as the associated targeting segment conditions were not fulfilled. The feature should be considered inactive
hasNewCheckout = false;
} on PlatformException {
// This is generic Exception handler which will handle all exceptions.
print("Exception occured");
}
if (hasNewCheckout) {
// Implement new checkout code here
}
To activate a feature toggle, call the activateFeature()
method of our SDK.
This method takes a visitorCode and featureKey (or featureID) as mandatory arguments to check if the specified feature will be active for a given user.
If such a user has never been associated with this feature flag, the SDK returns a boolean value randomly (true if the user should have this feature or false if not). If a user with a given visitorCode is already registered with this feature flag, it will detect the previous featureFlag value.
You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.
Arguments
Name | Type | Description |
visitorCode | String | Unique identifier of the user. This field is mandatory. |
featureID or featureKey | int or String | ID or Key of the feature you want to expose to a user. This field is mandatory. |
Return value
Type | Description |
bool | Value of the feature that is registered for a given visitorCode. |
Exceptions Thrown
Type | Description |
KameleoonException.SDKNotReady | Exception indicating that the SDK has not completed its initialization yet. |
KameleoonException.NotTargeted | Exception indicating that the current visitor / user did not trigger the required targeting conditions for this feature. The targeting conditions are defined via Kameleoon's segment builder. |
KameleoonException.FeatureConfigurationNotFound | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side). |
obtainVariationAssociatedData
String visitorCode = Uuid().v4();
int experimentID = 75253;
try {
int variationID = await kameleoonClient!.triggerExperiment(visitorCode, experimentID);
dynamic jsonObject = await kameleoonClient!.obtainVariationAssociatedData(variationID);
String firstName = jsonObject!["firstName"];
} on KameleoonException.VariationConfigurationNotFound {
// The variation is not yet activated on Kameleoon's side, ie the associated experiment is not online
} on PlatformException {
// This is generic Exception handler which will handle all exceptions.
print("Exception occured");
}
To retrieve JSON data associated with a variation, call the obtainVariationAssociatedData()
method of our SDK. The JSON data usually represents some metadata of the variation, and can be configured on our web application interface or via our Automation API.
This method takes the variationID as a parameter and will return the data as a JSON object. It will throw an exception (KameleoonException.VariationConfigurationNotFound
) if the variation ID is wrong or corresponds to an experiment that is not yet online.
Arguments
Name | Type | Description |
variationID | int | ID of the variation you want to obtain associated data for. This field is mandatory. |
Return value
Type | Description |
Map | Data associated with this variationID. |
Exceptions Thrown
Type | Description |
KameleoonException.VariationConfigurationNotFound | Exception indicating that the requested variation ID has not been found in the internal configuration of the SDK. This is usually normal and means that the variation's corresponding experiment has not yet been activated on Kameleoon's side. |
obtainFeatureVariable
String featureKey = "myFeature";
String variableKey = "myVariable";
late String? data;
try {
data = await kameleoonClient!.obtainFeatureVariable(featureKey, variableKey) as String?;
}
on KameleoonException.FeatureConfigurationNotFound {
// The feature is not yet activated on Kameleoon's side
}
on PlatformException {
// This is generic Exception handler which will handle all exceptions.
print("Exception occured");
}
To retrieve a feature variable, call the obtainFeatureVariable()
method of our SDK. A feature variable can be changed easily via our web application.
This method takes two input parameters: featureKey and variableKey. It will return the data as an Object
instance. Usually it should be casted to the expected type (the one defined on the web interface). It will throw an exception (KameleoonException.FeatureConfigurationNotFound
) if the requested feature has not been found in the internal configuration of the SDK.
Arguments
Name | Type | Description |
featureID or featureKey | int or String | ID or Key of the feature you want to obtain to a user. This field is mandatory. |
variableKey | String | Key of the variable. This field is mandatory. |
Return value
Type | Description |
Object | Data associated with this variable for this feature flag. This can be a double, String, bool or Map |
Exceptions Thrown
Type | Description |
KameleoonException.FeatureConfigurationNotFound | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side. |
trackConversion
import 'package:kameleoon_client_flutter/kameleoon_data.dart' as Data;
String visitorCode = Uuid().v4();
int goalID = 83023;
await kameleoonClient!.addData(
visitorCode,
new Data.Interest(2)
);
await kameleoonClient!.addData(visitorCode, new Data.Conversion(32, 0, false));
await kameleoonClient!.trackConversion(visitorCode, goalID);
To track conversion, use the trackConversion()
method. This method requires visitorCode and goalID to track conversion on this particular goal. In addition, this method also accepts revenue as a third optional argument to track revenue. The visitorCode should be identical to the one that was used when triggering the experiment.
The trackConversion()
method doesn't return any value. This method is non-blocking as the server call is made asynchronously.
Arguments
Name | Type | Description |
visitorCode | String | Unique identifier of the user. This field is mandatory. |
goalID | int | ID of the goal. This field is mandatory. |
revenue | double | Revenue of the conversion. This field is optional. |
addData
await kameleoonClient!.addData(
visitorCode,
new Data.Interest(0),
new Data.CustomData(1, "some custom value")
);
await kameleoonClient!.addData(visitorCode, new Data.Conversion(32, 10, false));
To associate various data with the current user, we can use the addData()
method. This method requires the visitorCode as a first parameter, and then accept several additional parameters. Those additional parameters represent the various Data Types allowed in Kameleoon.
Note that the addData()
method doesn't return any value and doesn't interact with the Kameleoon back-end servers by itself. Instead, every data declared is saved for further sending via the flush()
method described in the next paragraph. This allows a minimal number of server calls to be made, as data are usually regrouped in a single server call triggered by the execution of flush()
.
Arguments
Name | Type | Description |
visitorCode | String | Unique identifier of the user. This field is mandatory. |
data | Data | one or more values conforming to the Data protocol which may be passed separated by a comma. |
flush
String visitorCode = Uuid().v4();
await kameleoonClient!.addData(visitorCode, Data.Browser.CHROME);
await kameleoonClient!.addData(
visitorCode,
new Data.PageView("http://url.com", "title", 3),
new Data.Interest(0)
);
await kameleoonClient!.addData(visitorCode, new Data.Conversion(32, 10, false));
await kameleoonClient!.flush(visitorCode);
Data associated with the current user via addData()
method is not sent immediately to the server. It is stored and accumulated until it is sent automatically by the triggerExperiment()
or trackConversion()
methods, or manually by the flush()
method. This allows the developer to exactly control when the data is flushed to our servers. For instance, if you call the addData()
method a dozen times, it would be a waste of ressources to send data to the server after each addData()
invocation. Just call flush()
once at the end.
The flush()
method doesn't return any value. This method is non-blocking as the server call is made asynchronously.
Arguments
Name | Type | Description |
visitorCode | String | Unique identifier of the user. This field is mandatory. |
completionHandler | ((Bool) -> Void)? | Callback object. This field is an optional. It is a lambda expression that will asynchronously get called with a Bool argument representing whether the flush() call succeeded or not. |
Data
Conversion
await kameleoonClient!.addData(visitorCode, new Data.Conversion(32, 10, false));
Name | Type | Description |
goalID | String | ID of the goal. This field is mandatory. |
revenue | double | Conversion revenue. This field is optional. |
negative | bool | Defines if the revenue is positive or negative. This field is optional. |
CustomData
await kameleoonClient!.addData(
visitorCode,
new Data.CustomData(1, "some custom value")
);
Name | Type | Description |
index | int | Index / ID of the custom data to be stored. This field is mandatory. |
value | String | Value of the custom data to be stored. This field is mandatory. |
Interest
await kameleoonClient!.addData(
visitorCode,
new Data.Interest(0)
);
Name | Type | Description |
index | int | Index / ID of the interest. This field is mandatory. |