Developer guide
Getting started
This guide helps integrate the SDK and start running experiments in Flutter applications. This tutorial explains the setup of a simple A/B test to change the number of recommended products based on different variations.Install the Flutter client
To install the Kameleoon Flutter client, declare a dependency in yourpubspec.yaml file:
Initialize the Kameleoon client
After installing the SDK into your application and setting up a server-side experiment in the Kameleoon app, the next step is creating the Kameleoon client. AKameleoonClient is a singleton object (per siteCode) that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you need to run an experiment.
KameleoonClientFactory.create() method initializes the client, but it is not immediately ready for use, as the Kameleoon Client must retrieve the current configuration of feature flags (along with their traffic repartition) from a Kameleoon remote server. This retrieval requires network access, which is not always available. Until the Kameleoon Client is fully ready, you should not attempt to run other methods in the Kameleoon Android SDK. Note that once the first configuration of feature flags is fetched, it is then periodically refreshed, but even if the refresh fails for any reason, the Kameleoon client will continue to function using the previous configuration.
You can use the isReadyAsync() method to check if the Kameleoon client initialization is finished.
Alternatively, a helper callback can encapsulate the logic of feature flag triggering and variation implementation. The best approach (isReadyAsync() or callback) depends on preferences and the exact use case. Use isReadyAsync() when the SDK is expected to be ready for use soon. For example, isReadyAsync() is appropriate when running a feature flag on a dialog that users likely wouldn’t access for the first few seconds or minutes of navigating the app. A callback is recommended when there is a high probability that the SDK is still initializing. For example, a feature flag that appears onscreen at the application’s launch should use a callback that makes the application wait until either the SDK is ready or a specified timeout has expired.
It’s your responsibility as the app developer to ensure the logic of your application code is correct within the context of A/B testing using Kameleoon. A good practice is to always assume that the application user can be left out of the feature flag when the Kameleoon client is not yet ready. This exclusion is easy to implement, as it corresponds to the implementation of the default or reference variation logic. The code samples in the next paragraph show examples of this approach.
Activating a feature flag
Retrieving a flag configuration
To implement a feature flag in your code, you must first create a feature flag in your Kameleoon account. To determine if a feature flag is active for a specific user, you must retrieve its configuration. Use thegetFeatureVariationKey() or isFeatureActive() method to retrieve the configuration based on the featureKey.
Use the isFeatureActive() method if you want to retrieve the configuration of a simple feature flag that has only an ON or OFF state, as opposed to more complex feature flags with multiple variations or targeting options.
The getFeatureVariationKey() method retrieves the configuration of a feature experiment with several feature variations. You can use the method to get a variation key for a given user by providing the visitorCode and featureKey as mandatory arguments.
Feature flags can have associated variables that are used to customize their behavior. To retrieve these variables, use the getFeatureVariationVariables() method after calling getFeatureVariationKey(), as you must obtain the variationKey for the user.
To check if a feature flag is active, you only need to use one method. Choose
isFeatureFlagActive if you want to know if a feature flag is on or off. For more complex scenarios, like dynamically changing the feature’s behavior, use getFeatureFlagVariables.Adding data points to target a user or filter / breakdown visits in reports
To target a user, ensure you’ve added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use theaddData() method to add these data points to the user’s profile.
To retrieve data points collected on other devices or to access past user data (collected client-side when using Kameleoon in Hybrid mode), use the getRemoteVisitorData() method. This method asynchronously fetches data from the servers. Call getRemoteVisitorData() before retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation of a feature flag.
To learn more about available targeting conditions, see the detailed article on the subject.
Additionally, the data points you add to the visitor profile will be available when analyzing your experiments, allowing you to filter and break down your results by factors like device and browser. Remember to call the flush() method to send saved data to the Kameleoon servers.
If you need to track additional data points beyond what’s automatically collected, you can use Kameleoon’s Custom Data feature. Custom Data lets you capture and analyze specific information relevant to your experiments. Don’t forget to call the flush() method to send the collected data to Kameleoon servers for analysis.
Tracking flag exposition and goal conversions
Kameleoon will automatically track visitors’ exposition to flags as soon as you call one of these methods:getFeatureVariationKey()getFeatureVariable()isFeatureActive()
trackConversion() method, and provide the visitorCode and goalId parameters.
Using a custom bucketing key
By default, Kameleoon uses a unique, anonymous visitor ID (visitorCode) to assign users to feature flag variations. This ID is typically generated and stored on the user’s device (in a browser cookie for client-side and server-side SDKs—in persistent storage for mobile SDKs). However, in certain scenarios you may need to ensure all users of the same organization see the same variant of a feature flag.
The Custom Bucketing Key option allows you to override this default behavior by providing your own custom identifier for bucketing. This override ensures that Kameleoon’s assignment logic uses your specified key instead of the default visitorCode.
Use cases
Using a custom bucketing key is essential for maintaining consistency and accuracy in your feature flag assignments, particularly in these situations:- Account-level or organizational experiments: For B2B products or scenarios where you want to assign all users from the same organization to the same variation, you can use an identifier like an
accountId. Custom bucketing keys are crucial for A/B testing features that impact an entire team or company.
Technical details
When you configure a custom bucketing key for a feature flag, you provide Kameleoon with a specific identifier from your application’s data:- Providing the custom key: You provide your custom identifier to the Kameleoon SDK using the
addData()method. In this method, you will pass your chosen custom bucketing key as aCustomDataobject. Here,newVisitorCoderefers to the identifier you wish to use for your bucketing (for example, the newuserIdoraccountId).
- Bucketing logic: Once a custom bucketing key is provided through the
addData()method, all hash calculations for assigning users to variations will use thisnewVisitorCode(your custom key) instead of the defaultvisitorCode. Using thenewVisitorCodemeans that the bucketing decision is tied to your custom identifier, ensuring consistent assignments across various contexts where that identifier is present. - Data tracking and analytics: It’s crucial to note that while the
newVisitorCode(your custom key) is used for bucketing decisions, all subsequent data (tracking events and conversions, for example) is sent and associated with the originalvisitorCode. This separation ensures that your analytics accurately reflect individual user journeys and interactions within your experiment’s broader context, even when bucketing is performed at a higher level (like an account) or across multiple devices/sessions. Your original visitor data remains intact for comprehensive reporting.
Technical requirements
To effectively use a custom bucketing key:- The key must be a
String. - It must be unique for the entity you intend to bucket (for example, if using a
userId, each user’s ID should be unique). - The key must be available to the SDK at the exact moment the feature flag decision is evaluated for that user or request.
Targeting conditions
The Kameleoon SDKs support a variety of predefined targeting conditions that you can use to target users in your campaigns. For the list of conditions this SDK supports, see use visit history to target users. You can also use your own external data to target users.Logging
The SDK generates logs to reflect various internal processes and issues.Log levels
The SDK supports configuring limiting logging by a log level.Custom handling of logs
The SDK writes its logs to the console output by default. This behaviour can be overridden.Logging limiting by a log level is performed apart from the log handling logic.
Error Handling
Handling errors is considered a good practice to make your application more stable and avoid technical issues. MostKameleoonClient methods can throw a KameleoonException error.
Since it can be difficult to patch the SDK version on the Android client side, enclosing every SDK method in a try clause that catches the KameleoonException and the Throwable error type is recommended to prevent other fatal errors.
For example:
Reference
This is a full reference documentation of the Flutter SDK.Initialization
Once you have installed the SDK in your application, you must initialize Kameleoon. All of your application’s interactions with the SDK, such as triggering an experiment, are accomplished using this Kameleoon client object.create()
Call this method before any others to initialize the SDK. This method is inKameleoonClientFactory. Your app conducts all interactions with the SDK using the resulting KameleoonClient object that this method creates.
You can customize the SDK’s behavior (for example, the environment, the credentials, and so on) by providing a configuration object. Otherwise, the SDK tries to find your configuration file and uses it instead.
Parameters
Return value
Exceptions thrown
isReadyAsync()
For mobile SDKs, the Kameleoon Client can’t initialize immediately as it must perform a server call to retrieve the current configuration for the active feature flags. UseisReadyAsync() to check if the SDK is ready by calling this method before triggering any feature flags.
Alternatively, you can use a callback (see the runWhenReady() method for details).
Return value
runWhenReady()
For mobile SDKs, the Kameleoon Client can’t initialize immediately as it must perform a server call to retrieve the current configuration for all active feature flags. Use therunWhenReady() method of the KameleoonClient class to pass a callback that will be executed as soon as the SDK is ready for use. You can also set a timeout.
The callback given as the first argument to this method must be an instance of a type of Function(bool ready). If the ready equals true, the Kameleoon client is ready and should contain code that triggers a feature flag and implements variations. Otherwise, the specified timeout will occur before the client is initialized. The callback should contain code that implements the reference variation, as the user will be excluded from the feature flag if a timeout occurs.
Arguments
Feature flags and variations
isFeatureActive()
- 📨 Sends Tracking Data to Kameleoon
featureKey as a required argument to check if the specified feature will be active for a visitor.
If the visitor has never been associated with this feature flag, the method returns a random boolean value (true if the visitor should be shown this feature, otherwise false). If the visitor is already registered with this feature flag, this method returns the previous feature flag value.
Ensure you set up proper error handling as shown in the example code to catch potential exceptions.
Kameleoon uses tracking to count sessions and visitors when you call certain methods, such as
isFeatureActive(), getVariation() or getVariations().Use the default true value for the track parameter when you expose visitors to a variation and need to count them. Set the track parameter to false only if you call these methods before you expose visitors.For example, if you call getVariations() to retrieve all variations before you expose visitors, set the track parameter to false. This setting prevents Kameleoon from prematurely counting a session. You can then trigger tracking later when you explicitly expose the visitor.Kameleoon sends tracking data every second by default. You can configure this interval up to five seconds using the tracking interval configuration option. Kameleoon groups tracking events into a single session as long as the interval between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate sessions. A visit appears in your reports 30 minutes after the last recorded event in the session.Arguments
Return value
Exceptions thrown
getVariation()
- 📨 Sends Tracking Data to Kameleoon (depending on the
trackparameter)
Variation assigned to a given visitor for a specific feature flag.
This method takes a visitorCode and featureKey as mandatory arguments. The track argument is optional and defaults to true.
It returns the assigned Variation for the visitor. If the visitor is not associated with any feature flag rules, the method returns the default Variation for the given feature flag.
Ensure that proper error handling is implemented in your code to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It’s represented as the variation in the “Then, for everyone else…” section in a management interface.
Parameters
Return value
Exceptions thrown
getVariations()
- 📨 Sends Tracking Data to Kameleoon (depending on the
trackparameter)
Variation objects assigned to a given visitor across all feature flags.
This method iterates over all available feature flags and returns the assigned Variation for each flag associated with the specified visitor. It takes onlyActive and track as optional arguments.
- If
onlyActiveis set totrue, the methodgetVariations()will return feature flags variations provided the user is not bucketed with theoffvariation. - The
trackparameter controls whether or not the method will track the variation assignments. By default, it is set totrue. If set tofalse, the tracking will be disabled.
Variation as values. If no variation is assigned for a feature flag, the method returns the default Variation for that flag.
Proper error handling should be implemented to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It’s represented as the variation in the “Then, for everyone else…” section in a management interface.
Parameters
Return value
Exceptions thrown
getFeatureList()
Returns a list of feature flag keys currently available for the SDK.Return value
getDataFile()
Returns the current SDK configuration as aDataFile object.
Return value
Errors thrown
setForcedVariation()
The method allows you to programmatically assign a specificVariation to a user, bypassing the standard evaluation process. This is especially valuable for controlled experiments where the usual evaluation logic is not required or must be skipped. It can also be helpful in scenarios like debugging or custom testing.
When a forced variation is set, it overrides Kameleoon’s real-time evaluation logic. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set forceTargeting=false instead.
A forced variation is treated the same as an evaluated variation. It is tracked in analytics and stored in the user context like any standard evaluated variation, ensuring consistency in reporting.
The method may throw exceptions under certain conditions (e.g., invalid parameters, user context, or internal issues). Proper exception handling is essential to ensure that your application remains stable and resilient.
Parameters
Errors thrown
In most cases, only the basic error,
KameleoonException, needs to be handled, as demonstrated in the example. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Exception.evaluateAudiences()
- 📨 Sends Tracking Data to Kameleoon
evaluateAudiences() should be called after all relevant visitor data has been set or updated, and just before getting a feature variation or checking a feature flag. This approach ensures that the visitor is evaluated against the most current data available, allowing for accurate audience assignment based on all criteria.
After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.
Errors thrown
In most cases, only the basic error,
KameleoonException, needs to be handled, as demonstrated in the example. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Exception.Goals
trackConversion()
- 📨 Sends Tracking Data to Kameleoon
goalId to track conversion on this particular goal. In addition, this method also accepts revenue, metadata and negative arguments.
The trackConversion() method doesn’t return any value. This method is non-blocking as the server call is made asynchronously.
Parameters
metadata values are accessible through raw data exports and the results page.If the
metadata parameter is provided, Kameleoon will use these specified values for the current conversion instead of what was previously collected using the addData() method. If the parameter is omitted, Kameleoon will use the last tracked values for those CustomData prior to the conversion and within the same visit.Kameleoon will only consider the metadata values that are explicitly passed as parameters to the trackConversion() method.In the example below, Kameleoon will associate the conversion only with the custom data value explicitly provided as a parameter (here: index 5 with the value ‘Amex Credit Card’).Events
onUpdateConfiguration()
This method was previously called
updateConfigurationHandler, which was removed in SDK version 3.0.0 release.onUpdateConfiguration() method allows you to handle the event when configuration has updated data. It takes one input parameter, handler. The handler that will be called when the configuration is updated using a real-time configuration event.
Parameters
Visitor data
getVisitorCode()
Returns unique visitor code used in SDK.Return value
addData()
TheaddData() method adds targeting data to storage so other methods can use the data to decide whether or not to target the current visitor.
The addData() method does not return any value and does not interact with Kameleoon back-end servers on its own. Instead, all the declared data is saved for future transmission using the flush() method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call that is triggered by the flush().
The trackConversion() method also sends out any previously associated data, just like the flush(). The same holds true for getVariation() and getVariations() methods if an experimentation rule is triggered.
Parameters
Exceptions
flush()
- 📨 Sends Tracking Data to Kameleoon
addData() method is not sent immediately to the server. It is stored and accumulated until it is sent automatically by the trackConversion() method, or manually sent by calling the flush() method, giving control over exactly when the data is flushed to the servers. For example, if the addData() method is called a dozen times, sending data to the server after each addData() invocation would waste resources. 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.
Exceptions thrown
getRemoteData()
This method was previously called
retrieveDataFromRemoteSource, which was removed in SDK version 3.0.0 release.siteCode and the key argument (or the active visitorCode if the key is omitted). The visitorCode and siteCode are specified in KameleoonClientFactory.create(). Data can be stored quickly and conveniently on highly scalable remote servers using the Kameleoon Data API. The application can then retrieve the data using this method.
Note that since a server call is required, this mechanism is asynchronous.
Parameters
Return value
getRemoteVisitorData()
getRemoteVisitorData() is an asynchronous method for retrieving Kameleoon Visits Data for the visitorCode from the Kameleoon Data API. This method adds the data to storage for other methods to use when making targeting decisions.
Data obtained using this method plays an important role when you want to:
- use data collected from other devices.
- access a user’s history, such as custom data collected during previous visits.
Parameters
Return value
Exceptions thrown
Using parameters in getRemoteVisitorData()
ThegetRemoteVisitorData() method offers flexibility by letting you define various parameters when retrieving data on visitors. Whether you’re targeting based on goals, experiments, or variations, the same approach applies across all data types.
For example, suppose you want to retrieve data on visitors who completed a goal “Order transaction”. You can specify parameters within the getRemoteVisitorData() method to refine your targeting. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the previousVisitAmount parameter to 5 and conversions to true.
The flexibility shown in this example is not limited to goal data. You can use parameters within the getRemoteVisitorData() method to retrieve data on a variety of visitor behaviors.
Here is the list of available
RemoteVisitorDataFilter options:getVisitorWarehouseAudience()
Retrieves all audience data associated with the visitor in your data warehouse. The optionalwarehouseKey parameter is typically your internal user ID. The customDataIndex parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the warehouse targeting documentation for additional details. The method returns the result as a CustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.
Since a server call is required, this mechanism is asynchronous.
Parameters
Return value
Exceptions thrown
setLegalConsent()
You must use this method to specify whether the visitor has given legal consent to use their personal data. Setting theconsent parameter to false limits the types of data that you can include in tracking requests. This method helps you adhere to legal and regulatory requirements while responsibly managing visitor data. You can find more information on personal data in the consent management policy.
Parameters
Exceptions thrown
Consent revocation behavior
This is applicable only to the Flutter Web SDK.
setLegalConsent() with consent=false, the SDK does not delete the kameleoonVisitorCode cookie. Instead, it stops extending the cookie’s expiration date, allowing the cookie to persist until it naturally expires.
If your compliance requirements demand the immediate removal of the cookie file upon opt-out, you must delete it manually using your framework’s native cookie management methods. The SDK will not remove the file automatically.
Data types
This section lists theData types supported by Kameleoon. Several standard data types are provided, as well as the CustomData type for defining custom data types.
Conversion
TheConversion data set stored here can be used to filter experiment and personalization reports by any goal associated with it.
CustomData
This data type is available for both types of SDKs: Mobile & Web.
CustomData allows any type of data to be easily associated with each visitor. CustomData can then be used as a targeting condition in segments or as a filter/breakdown in experiment reports.
To learn more about custom data, please refer to this article.
- Each visitor is allowed only one
CustomDatafor each uniqueindex. Adding anotherCustomDatawith the sameindexwill replace the existingCustomData. - The custom data
indexcan be found in the Custom Data dashboard under the “INDEX” column. - To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the Use this data only locally for targeting purposes option when creating custom data.
- Adding a
CustomDatainstance created with a name when the SDK instance configuration is not up to date or the name is not registered, will result in the data being ignored.
Device
This data type is available for both types of SDKs: Mobile & Web.
Geolocation
This data type is available for both types of SDKs: Mobile & Web.
Geolocation contains the visitor’s geolocation details.
Browser
The data type is available only for Web SDK
Browser data set stored here can be used to filter experiment and personalization reports by any value associated with it.
PageView
This data type is only available for Web SDKs.
The referrer’s index (ID) is available in the Acquisition channel configuration page of the Kameleoon app. Be careful: this index starts at 0, so the first acquisition channel you create for a given site will have the ID 0, not 1.
OperatingSystem
This data type is only available for Web SDKs.
OperatingSystem contains information about the operating system on the visitor’s device.
Cookie
This data type is only available for Web SDKs.
Cookie contains information about the cookie stored on the visitor’s device.
Returned Types
DataFile
TheDataFile contains the SDK configuration details.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
FeatureFlag
TheFeatureFlag represents a set of properties that define a feature flag itself — for example, its Variations, Rules, environment status, and other related details.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
Rule
TheRule represents a set of properties that define a rule itself — for example, its Variations.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
Variation
Variation contains information about the visitor’s assigned variation (or the default variation, if no specific assignment exists).
- The
Variationobject provides details about the assigned variation and its associated experiment, while theVariableobject contains specific details about each variable within a variation. - Ensure that your code handles the case where
idorexperimentIdmay benull, indicating a default variation. - The
variablesmap might be empty if no variables are associated with the variation.
Variable
Variable contains information about a variable associated with the assigned variation.
Deprecated methods
isReady()
For mobile SDKs, the Kameleoon Client can’t initialize immediately as it must perform a server call to retrieve the current configuration for the active feature flags. UseisReady() to check if the SDK is ready by calling this method before triggering any feature flags.
Alternatively, you can use a callback (see the runWhenReady() method for details).
Return value
getFeatureVariationKey()
- 📨 Sends Tracking Data to Kameleoon
Use
getVariation() instead.featureKey as a required argument to retrieve the variation key for the specified user.
If the visitor has never been associated with this feature flag, the SDK returns a randomly assigned variation key (according to the feature flag rules). If the visitor is already registered with this feature flag, this method returns the previous variation key. If the user does not match any of the rules, the default value will be returned, which is defined in your customer’s account.
Ensure you set up proper error handling as shown in the example code to catch potential exceptions.
Parameters
Return value
Exceptions thrown
getActiveFeatures()
- Use
getVariations()instead. - Previously called
getFeatureListForVisitorCode, which was removed in SDK version4.0.0release.
getActiveFeatures method retrieves information about the active feature flags that are available for the visitor.
Return value
getFeatureVariable()
- 📨 Sends Tracking Data to Kameleoon
- Use
getVariation()instead. - This method was previously called
obtainFeatureVariable, which was removed in SDK version3.0.0.
featureKey and variableKey as required arguments.
If the visitor has never been associated with the featureKey, the SDK returns a randomly assigned variable value for the specified variation key (according to the feature flag rules). If the visitor is already registered with this feature flag, this method returns the variable value for previously registered variation. If the user does not match any of the rules, the default variable value is returned.
Ensure you set up proper error handling as shown in the example code to catch potential exceptions.
Parameters
Return value
Exceptions thrown
getFeatureVariationVariables()
- Use
getVariation()instead. - This method was previously called
getFeatureAllVariables, which was removed in SDK version4.0.0release.
featureKey. It returns the data as a Map<String, Object> type, as defined in the Kameleoon app. It throws an exception (FeatureNotFound) if the requested feature was not found in the SDK’s internal configuration.