> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kameleoon.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Flutter SDK

> Integrate the Kameleoon Flutter SDK to run experiments and activate feature flags across all platforms targeted by the Flutter framework.

With the Kameleoon Flutter SDK, experiments can run and feature flags can activate on all platforms targeted by the Flutter application framework. Integrating the SDK into applications is easy, and the footprint (in terms of memory and network usage) is low.

**Getting started**: For help getting started, see the [developer guide](#developer-guide).

**Changelog**: Latest version of the Flutter SDK: 3.7.0 [Changelog](https://github.com/Kameleoon/client-flutter/blob/master/CHANGELOG.md).

**SDK methods**: For the full reference documentation of the Flutter SDK methods, see the [reference](#reference) section.

## 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 your `pubspec.yaml` file:

```ruby theme={null}
kameleoon_client_flutter: ^3.0.0
```

<Warning title="Web only">
  In **release** mode, the JS library loads automatically. However, in **debug** mode, issues (due to the Dart Development Compiler) may occur when importing the JS library. To avoid potential problems, importing the JS library explicitly is strongly recommended.
  Add the following script line to the `<head>` section of your `index.html`:

  ```html theme={null}
  <script type="application/javascript" charset="utf-8" src="assets/packages/kameleoon_client_flutter/assets/kameleoonSDK.js"></script>
  ```
</Warning>

#### 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.

A `KameleoonClient` 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.

```dart theme={null}
import 'package:kameleoon_client_flutter/kameleoon_client_flutter.dart';

class _HomePage extends State<HomePage> {
    KameleoonClient kameleoonClient

    @override
    void initState() {
            super.initState();

            try {
                // pass client configuration and visitorCode as arguments
                final config = KameleoonClientConfig(
                    refreshIntervalMinutes: 15, // 60 minutes by default, optional
                    defaultTimeoutMilliseconds: 10000,  // 10_000 milliseconds by default, optional
                    dataExpirationIntervalMinutes: 1440 * 365, // infinity by default, optional
                    trackingIntervalMilliseconds: 500, // 1000 milliseconds by default, optional
                    environment: "staging",  // optional
                    isUniqueIdentifier: false, // false by default, optional
                    domain: "example.com", // web only option, optional
                    networkDomain: "company.com", //  web only option, optional
                    defaultDataFile: "{...}" // optional
                );

                final visitorCode = "yourVisitorCode";
                final kameleoonClient = KameleoonClientFactory.create(siteCode, visitorCode: visitorCode, config: config);
                // or, if you want, visitor code will be generated automatically
                final kameleoonClient = KameleoonClientFactory.create(siteCode, config: config);
            } on SiteCodeIsEmpty catch (ex) {
                // Exception indicates that the provided siteCode is empty
            } on VisitorCodeInvalid catch (ex) {
                // Exception indicates that the provided visitorCode is invalid
            } on Exception catch (ex) {
                // Any other error
            }
    }
}
```

While executing, the `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()`](#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()`](#isreadyasync) or **callback**) depends on preferences and the exact use case. Use [`isReadyAsync()`](#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.

<Note>
  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.
</Note>

You're now ready to implement feature management and features flags. See the [Reference](#reference) section for details about additional methods.

#### Activating a feature flag

##### Retrieving a flag configuration

To implement a feature flag in your code, you must first create a [feature flag](/user-manual/experimentation/feature-experimentation/create-and-manage-flags/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 the [`getFeatureVariationKey()`](#getfeaturevariationkey) or [`isFeatureActive()`](#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()`](#getfeaturevariationvariables) method after calling `getFeatureVariationKey()`, as you must obtain the `variationKey` for the user.

<Note>
  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`.
</Note>

##### 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 the [`addData()`](#adddata) 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()`](#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](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation).

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](#customdata). 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()`

When a user completes a desired action (for example, making a purchase), it counts as a conversion. To track conversions, you must use the [`trackConversion()`](#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.

By implementing a custom bucketing key, you ensure greater consistency and accuracy in your experiments, leading to more reliable results and a better user experience.

#### 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:

```dart theme={null}
try {
    await kameleoonClient.addData(CustomData.withIndex(index, values: ["newVisitorCode"]))
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
}
```

* **Providing the custom key:** You provide your custom identifier to the Kameleoon SDK using the [`addData()`](#adddata) method. In this method, you will pass your chosen custom bucketing key as a [`CustomData`](#customdata) object. Here, `newVisitorCode` refers to the identifier you wish to use for your bucketing (for example, the new `userId` or `accountId`).

<Warning>
  For the custom bucketing key to function correctly, it must also be defined and configured for the feature flag during the flag creation or editing process. Without this corresponding configuration, the SDK's bucketing will not apply your custom key. For detailed instructions on how to set this up in Kameleoon, refer to this [article](/user-manual/experimentation/feature-experimentation/create-and-manage-flags/create-a-feature-flag#Advanced_Flag_Settings).
</Warning>

* **Bucketing logic:** Once a custom bucketing key is provided through the `addData()` method, all hash calculations for assigning users to variations will use this `newVisitorCode` (your custom key) instead of the default `visitorCode`. Using the `newVisitorCode` means 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 *original* `visitorCode`.** 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](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation).

You can also use your own [external data to target users](/developer-docs/apis/data-api-rest/tutorials/storing-and-retrieving-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.

```dart theme={null}
// The `none` log level does not allow logging.
KameleoonLogger.setLogLevel(LogLevel.none);

// The `error` log level only allows logging issues that may affect the SDK's main behaviour.
KameleoonLogger.setLogLevel(LogLevel.error);

// The `warning` log level allows logging issues which may require additional attention.
// It extends the `error` log level.
// The `warning` log level is a default log level.
KameleoonLogger.setLogLevel(LogLevel.warning);

// The `info` log level allows logging general information on the SDK's internal processes.
// It extends the `warning` log level.
KameleoonLogger.setLogLevel(LogLevel.info);

// The `DEBUG` level logs additional details about the SDK’s internal processes and extends the `INFO` level
// with more granular diagnostic output.
// This information is not intended for end-user interpretation but can be sent to support
// to assist with internal troubleshooting.
KameleoonLogger.setLogLevel(LogLevel.debug);
```

#### Custom handling of logs

The SDK writes its logs to the console output by default. This behaviour can be overridden.

<Note>
  Logging limiting by a log level is performed apart from the log handling logic.
</Note>

```dart theme={null}
import 'package:logging/logging.dart' as logging;

class CustomLogger extends Logger {
  final logger = logging.Logger("CustomLogger");
  // `log` method accepts logs from the SDK
  @override
  void log(LogLevel level, String message) {
    // Custom log handling logic here. For example:
    switch (level) {
      case LogLevel.error:
        logger.severe(message);
        break;
      case LogLevel.warning:
        logger.warning(message);
        break;
      case LogLevel.info:
        logger.info(message);
        break;
      case LogLevel.debug:
        logger.fine(message);
        break;
      default:
        break;
    }
  }
}

// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
KameleoonLogger.setLogLevel(LogLevel.debug); // Optional, defaults to `LogLevel.warning`.
KameleoonLogger.setLogger(CustomLogger());
```

### Error Handling

Handling errors is considered a good practice to make your application more stable and avoid technical issues. Most `KameleoonClient` 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:

```dart theme={null}
try {
    // Calling a method of the SDK
} on KameleoonException {
    // Handling expected exceptions
} on Exception {
    // Any other error
}
```

## Reference

This is a full reference documentation of the Flutter SDK.

### Initialization

Once you have [installed the SDK](#install-the-flutter-client) 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 in `KameleoonClientFactory`. 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](#additional-configuration). Otherwise, the SDK tries to find your configuration file and uses it instead.

```dart theme={null}
import 'package:kameleoon_client_flutter/kameleoon_client_flutter.dart'


final siteCode = "a8st4f59bj";
try {
    // pass client configuration and visitorCode as arguments
    final config = KameleoonClientConfig(
      refreshIntervalMinutes: 15, // 60 minutes by default, optional
      defaultTimeoutMilliseconds: 10000, // 10_000 milliseconds by default, optional
      dataExpirationIntervalMinutes: 1440 * 365, // infinity by default, optional
      trackingIntervalMilliseconds: 500, // 1000 milliseconds by default, optional
      environment: "staging",  // optional
      isUniqueIdentifier: false, // false by default, optional
      domain: "example.com" // web only option, optional
      networkDomain: "company.com", //  web only option, optional
      defaultDataFile: "{...}" // optional
    );
    final visitorCode = "yourVisitorCode";
    final kameleoonClient = KameleoonClientFactory.create(siteCode, visitorCode: visitorCode, config: config);
} on SiteCodeIsEmpty catch (ex) {
     // Exception indicates that the provided siteCode is empty
} on VisitorCodeInvalid catch (ex) {
    // Exception indicates that the provided visitorCode is invalid
} on Exception catch (ex) {
    // Any other error
}

try {
    // generate visitorCode automatically and use default Kameleoon client config
    final kameleoonClient = KameleoonClientFactory.create(siteCode);
} on SiteCodeIsEmpty catch (ex) {
     // Exception indicates that the provided siteCode is empty
} on Exception catch (ex) {
    // Any other error
}
```

##### Parameters

| Name                                                        | Type                    | Description                                                                                                                      | Default |
| ----------------------------------------------------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------- |
| siteCode <Badge color="red" size="sm">required</Badge>      | `String`                | A [unique key](/user-manual/faq#how-do-i-find-my-sitecode) identifying the Kameleoon project used with the SDK.                  |         |
| visitorCode <Badge color="green" size="sm">optional</Badge> | `String`                | An optional visitor identifier. If available, use your internal **user ID**; otherwise, the SDK will generate one automatically. | `nil`   |
| config <Badge color="green" size="sm">optional</Badge>      | `KameleoonClientConfig` | If the SDK configuration is not provided, the SDK will automatically use the default settings.                                   | `nil`   |

##### Return value

| Type              | Description                                                                                                         |
| ----------------- | ------------------------------------------------------------------------------------------------------------------- |
| `KameleoonClient` | An instance of the `KameleoonClient` class that your app can then use to manage your experiments and feature flags. |

##### Exceptions thrown

| Type                 | Description                                                                                                         |
| -------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid` | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters. |
| `SiteCodeIsEmpty`    | Exception indicating that the specified site code is empty string which is invalid value.                           |

#### 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. Use `isReadyAsync()` 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()`](#runwhenready) method for details).

```dart theme={null}
final ready = kameleoonClient.isReadyAsync();
```

##### Return value

| Name  | Type | Description                                                                                |
| ----- | ---- | ------------------------------------------------------------------------------------------ |
| ready | bool | Boolean representing the SDK's status (properly initialized, or not yet ready to be used). |

#### 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 the [`runWhenReady()`](#runwhenready) 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.

```dart theme={null}
kameleoonClient.runWhenReady((ready) async {
    final defaultProductsNumber = 5;
    if (ready) {
        late int recommendedProductsNumber;
        try {
            recommendedProductsNumber = await kameleoonClient.getFeatureVariable("feature_key", "product_number");
        } on Exception {
            recommendedProductsNumber = defaultProductsNumber;
        }
    } else {
        recommendedProductsNumber = defaultProductsNumber;
    }

    setState(() {
        _recommendedProductsNumber = recommendedProductsNumber;
    });
}, 2000);
```

##### Arguments

| Name                                                   | Type             | Description                                                                                                                                            |
| ------------------------------------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| callback <Badge color="red" size="sm">required</Badge> | `Function(bool)` | Callback object with `ready` flag.                                                                                                                     |
| timeout (*optional)*                                   | `Duration`       | Timeout (in milliseconds). If not provided, it will use the default value of `defaultTimeoutMilliseconds` (from `KameleoonClientConfig`) milliseconds. |

### Feature flags and variations

#### isFeatureActive()

* 📨 *Sends Tracking Data to Kameleoon*

To activate a feature toggle, call this method. This method accepts a `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.

<Note>
  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.
</Note>

```dart theme={null}
String featureKey = "new_checkout";
bool hasNewCheckout = false;

try {
  hasNewCheckout = await kameleoonClient.isFeatureActive(featureKey);
} on SDKNotReady {
  // Exception indicates that the SDK has not completed its initialization yet.
} on FeatureNotFound {
  // The error has occurred; feature flag isn't found in current configuration.
} on KameleoonException {
  // Generic exception in native plugin integration occurred.
} on Exception {
  // Any other error
}
if (hasNewCheckout) {
  // Implement new checkout code here
}
```

<Warning>
  The `isFeatureActive()` method evaluates the served variant, not the master flag state. If you exclude rules, the method uses the **Then, for everyone else serve** default state. If you select **Off** for this default state, the method always returns `false` even when the master feature flag is **On**.
</Warning>

##### Arguments

| Name       | Type     | Description                                                                                        |
| ---------- | -------- | -------------------------------------------------------------------------------------------------- |
| featureKey | `String` | Unique key of the feature you want to expose to a user. This field is required.                    |
| track      | `bool`   | An optional parameter to enable or disable tracking of the feature evaluation (`true` by default). |

##### Return value

| Type           | Description                                            |
| -------------- | ------------------------------------------------------ |
| `Future<bool>` | Value of the feature that is registered for a visitor. |

##### Exceptions thrown

| Type              | Description                                                                                                                                                                                                                                                                       |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| SDKNotReady       | Exception indicating that the SDK has not completed its initialization.                                                                                                                                                                                                           |
| FeatureNotFound   | Exception indicating that the requested feature ID was not found in the SDK's internal configuration. This exception usually means that the feature flag has not been activated on the Kameleoon side (but code implementing the feature is already deployed in the application). |
| PlatformException | Exception indicating that the native plugin integration works incorrectly.                                                                                                                                                                                                        |

#### getVariation()

* 📨 *Sends Tracking Data to Kameleoon (depending on the `track` parameter)*

Retrieves the [`Variation`](#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.

<Note>
  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.
</Note>

```dart theme={null}
final String featureKey = "featureKey";
Variation? variation;
try {
    variation = await client.getVariation(featureKey);
    // disabling tracking
    variation = await client.getVariation(featureKey, track: false);
} on SDKNotReady {
    // Exception indicating that the SDK has not completed its initialization yet.
} on FeatureNotFound {
    // The feature key is not in the configuration file that has been fetched by the SDK.
} on FeatureEnvironmentDisabled {
    // The feature flag is disabled for the environment.
}

String? title = variation?.variables['title']?.value;

switch (variation?.key) {
    case "on":
        // Main variation key is selected for visitorCode
        break;
    case "alternative_variation":
        // Alternative variation key
        break;
    default:
        // Default variation key
        break;
}
```

##### Parameters

| Name                                                        | Type     | Description                                                                    | Default |
| ----------------------------------------------------------- | -------- | ------------------------------------------------------------------------------ | ------- |
| `visitorCode` <Badge color="red" size="sm">required</Badge> | `String` | Unique identifier of the visitor.                                              |         |
| `featureKey` <Badge color="red" size="sm">required</Badge>  | `String` | Key of the feature you want to expose to a visitor.                            |         |
| `track` <Badge color="green" size="sm">optional</Badge>     | `bool`   | An optional parameter to enable or disable tracking of the feature evaluation. | `true`  |

##### Return value

| Type                | Description                                                                           |
| ------------------- | ------------------------------------------------------------------------------------- |
| `Future<Variation>` | An assigned [`Variation`](#variation) to a given visitor for a specific feature flag. |

##### Exceptions thrown

| Type                         | Description                                                                                                                                                                                                                                                           |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `VisitorCodeInvalid`         | Exception indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.                                                                                                                                                   |
| `FeatureNotFound`            | Exception indicating that the requested feature key wasn't found in the internal configuration of the SDK. This usually means that the feature flag is not activated in the Kameleoon app (but code implementing the feature is already deployed in the application). |
| `FeatureEnvironmentDisabled` | Exception indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).                                                                                                                          |

#### getVariations()

* 📨 *Sends Tracking Data to Kameleoon (depending on the `track` parameter)*

Retrieves a map of [`Variation`](#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 `onlyActive` is set to `true`, the method `getVariations()` will return feature flags variations provided the user is not bucketed with the `off` variation.
* The `track` parameter controls whether or not the method will track the variation assignments. By default, it is set to `true`. If set to `false`, the tracking will be disabled.

The returned map consists of feature flag keys as keys and their corresponding `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.

<Note>
  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.
</Note>

```dart theme={null}
try {
    Map<String, Variation> variations = await kameleoonClient.getVariations();
    // only active variations
    Map<String, Variation> variations = await kameleoonClient.getVariations(onlyActive: true);
    // disable tracking
    Map<String, Variation> variations = await kameleoonClient.getVariations(onlyActive: false, track: false);
} on SDKNotReady {
    // Exception indicating that the SDK has not completed its initialization yet.
}
```

##### Parameters

| Name                                                         | Type   | Description                                                                                                       | Default |
| ------------------------------------------------------------ | ------ | ----------------------------------------------------------------------------------------------------------------- | ------- |
| `onlyActive` <Badge color="green" size="sm">optional</Badge> | `bool` | An optional parameter indicating whether to return variations for active (`true`) or all (`false`) feature flags. | `false` |
| `track` <Badge color="green" size="sm">optional</Badge>      | `bool` | An optional parameter to enable or disable tracking of the feature evaluation.                                    | `true`  |

##### Return value

| Type                             | Description                                                                                                                         |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `Future<Map<String, Variation>>` | Map that contains the assigned [`Variation`](#variation) objects of the feature flags using the keys of the corresponding features. |

##### Exceptions thrown

| Type          | Description                                          |
| ------------- | ---------------------------------------------------- |
| `SDKNotReady` | Indicates that the SDK is not yet fully initialized. |

#### getFeatureList()

Returns a list of feature flag keys currently available for the SDK.

```dart theme={null}
try {
    final allFeatureFlagKeys = await kameleoonClient.getFeatureList();
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
}
```

##### Return value

| Type                   | Description               |
| ---------------------- | ------------------------- |
| `Future<List<String>>` | List of feature flag keys |

#### getDataFile()

<Tip>
  To evaluate all feature flags, use [`getVariations()`](#getvariations). This method is more efficient than calling `DataFile` and iterating through flags with [`getVariation()`](#getvariation).
</Tip>

Returns the current SDK configuration as a [`DataFile`](#datafile) object.

```dart theme={null}
try {
    final dataFile = await kameleoonClient.getDataFile();
    final dateModified = dataFile.dateModified;
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
}
```

##### Return value

| Type       | Description                                                  |
| ---------- | ------------------------------------------------------------ |
| `DataFile` | The [`DataFile`](#datafile) containing the SDK configuration |

##### Errors thrown

| Type          | Description                                          |
| ------------- | ---------------------------------------------------- |
| `SDKNotReady` | Indicates that the SDK is not yet fully initialized. |

#### setForcedVariation()

The method allows you to programmatically assign a specific [`Variation`](#variation) 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.

```dart theme={null}
final experimentId = 9516;
try {
    // Forcing the variation "on" for the experiment 9516 for the visitor
    await kameleoonClient.setForcedVariation(experimentId, "on")

    // Forcing the variation "on" while preserving segmentation and targeting conditions during the experiment
    await kameleoonClient.setForcedVariation(experimentId, "on", forceTargeting: false)

    // Resetting the forced variation for the experiment 9516 for the visitor
    await kameleoonClient.setForcedVariation(experimentId, null);
} on KameleoonException {
  // Handling the exception
}
```

##### Parameters

| Name                                                             | Type     | Description                                                                                                                                                                  | Default |
| ---------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `experimentId` <Badge color="red" size="sm">required</Badge>     | `int`    | **Experiment Id** that will be targeted and selected during the evaluation process.                                                                                          |         |
| `variationKey` <Badge color="red" size="sm">required</Badge>     | `String` | **Variation Key** corresponding to a `Variation` that should be forced as the returned value for the experiment. If the value is `null`, the forced variation will be reset. |         |
| `forceTargeting` <Badge color="green" size="sm">optional</Badge> | `bool`   | Indicates whether targeting for the experiment should be forced and skipped (`true`) or applied as in the standard evaluation process (`false`).                             | `true`  |

##### Errors thrown

| Type                        | Description                                                                                                                                                                                                                                           |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SDKNotReady`               | Indicates that the SDK is not yet fully initialized.                                                                                                                                                                                                  |
| `FeatureExperimentNotFound` | Exception indicating that the requested experiment id has not been found in the SDK's internal configuration. This is usually normal and means that the rule's corresponding experiment has not yet been activated on Kameleoon's side.               |
| `FeatureVariationNotFound`  | Exception indicating that the requested variation key(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. |

<Info>
  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`.
</Info>

#### evaluateAudiences()

* 📨 *Sends Tracking Data to Kameleoon*

This method evaluates visitors against all available Audiences Explorer segments and tracks those who match.

`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.

```dart theme={null}
try {
    await kameleoonClient.evaluateAudiences();
} on KameleoonException {
  // Handling the exception
}
```

##### Errors thrown

| Type          | Description                                          |
| ------------- | ---------------------------------------------------- |
| `SDKNotReady` | Indicates that the SDK is not yet fully initialized. |

<Info>
  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`.
</Info>

### Goals

#### trackConversion()

* 📨 *Sends Tracking Data to Kameleoon*

Use this method to track conversions. This method requires `goalId` to track conversion on this particular [goal](/user-manual/assets/goals/create-a-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.

```dart theme={null}
kameleoonClient.trackConversion(goalId); // default revenue
kameleoonClient.trackConversion(goalId, 10); // provided revenue == 10

// Add metadata
kameleoonClient.trackConversionWithOptParams(goalId, metadata: [CustomData.withIndex(1, values: ["true"])]);
kameleoonClient.trackConversionWithOptParams(goalId, revenue: 10, metadata: [CustomData.withIndex(1, values: ["true"])]);
```

##### Parameters

| Name                                                       | Type               | Description                                                                                                                      | Default |
| ---------------------------------------------------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `goalId` <Badge color="red" size="sm">required</Badge>     | `int`              | ID of the goal.                                                                                                                  |         |
| `revenue` <Badge color="green" size="sm">optional</Badge>  | `double`           | Revenue of the conversion.                                                                                                       | `0`     |
| `negative` <Badge color="green" size="sm">optional</Badge> | `bool`             | Defines if the revenue is positive or negative.                                                                                  | `false` |
| `metadata` <Badge color="green" size="sm">optional</Badge> | `List<CustomData>` | Metadata of the conversion. [Must be defined beforehand in the Kameleoon App](/user-manual/assets/goals/create-a-goal#metadata). | `[]`    |

<Note>
  metadata values are accessible through [raw data exports](/user-manual/experiment-analytics/analyze-results/results-page-actions#Export) and [the results page](/user-manual/experiment-analytics/analyze-results/goal-metadata).

  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()`](#adddata) method. If the parameter is omitted, Kameleoon will use the last tracked values for those [`CustomData`](#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').

  ```dart theme={null}
  kameleoonClient.addData([
      CustomData.withIndex(5, values: ["Credit Card"]),
      CustomData.withIndex(9, values: ["Express Delivery"])
  ]);
  kameleoonClient.trackConversionWithOptParams(1000, metadata: [CustomData.withIndex(5, values: ["Amex Credit Card"])]);
  ```
</Note>

### Events

#### onUpdateConfiguration()

<Note>
  This method was previously called `updateConfigurationHandler`, which was removed in SDK version `3.0.0` release.
</Note>

The `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.

```dart theme={null}
kameleoonClient.onUpdateConfiguration((timestamp) {
    // timestamp value contains the value of Unix time (number of seconds elapsed since January 1, 1970) when configuration was updated.
});
```

##### Parameters

| Name      | Type             | Description                                                                                              |
| --------- | ---------------- | -------------------------------------------------------------------------------------------------------- |
| `handler` | `Function(int)?` | The handler that will be called when the configuration is updated using a real-time configuration event. |

### Visitor data

#### getVisitorCode()

Returns unique visitor code used in SDK.

```dart theme={null}
final visitorCode = await kameleoonClient.getVisitorCode();
```

##### Return value

| Type             | Description                                            |
| ---------------- | ------------------------------------------------------ |
| `Future<String>` | String representing a unique visitor code used in SDK. |

#### addData()

The `addData()` method adds [targeting data](#data-types) 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()`](#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()`](#trackconversion) method also sends out any previously associated data, just like the `flush()`. The same holds true for [`getVariation()`](#getvariation) and [`getVariations()`](#getvariations) methods if an experimentation rule is triggered.

<Tip>
  Each visitor can only have one instance of associated data for most data types. However, [`CustomData`](#customdata) is an exception. Visitors can have one instance of associated `CustomData` per index.
</Tip>

```dart theme={null}
try {
    await kameleoonClient.addData([
        Device(Devices.phone),
        CustomData.withIndex(1, values: ["some custom value"]),
        Conversion(32, 10f, false),
    ]);
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
}
```

##### Parameters

| Name                                                    | Type         | Description                                                                                                                                                                                  | Default value |
| ------------------------------------------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| `track` <Badge color="green" size="sm">optional</Badge> | `bool`       | Specifies whether the added data is eligible for tracking. When set to `false`, the data is stored locally and used only for targeting evaluation; it is not sent to the Kameleoon Data API. | `true`        |
| `data` <Badge color="red" size="sm">required</Badge>    | `List<Data>` | Collection of Kameleoon data types.                                                                                                                                                          |               |

##### Exceptions

| Type                | Description                                                                |
| ------------------- | -------------------------------------------------------------------------- |
| `PlatformException` | Exception indicating that the native plugin integration works incorrectly. |

#### flush()

* 📨 *Sends Tracking Data to Kameleoon*

Data associated with the current user via the `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.

```dart theme={null}
kameleoonClient.flush(); // Interval tracking (most performant tracking method)

kameleoonClient.flush(instant: true); // Instant tracking
```

##### Exceptions thrown

| Type              | Description                                                                     |
| ----------------- | ------------------------------------------------------------------------------- |
| PlatformException | Exception indicating that the native plugin integration doesn't work correctly. |

#### getRemoteData()

<Note>
  This method was previously called `retrieveDataFromRemoteSource`, which was removed in SDK version `3.0.0` release.
</Note>

Use this method to retrieve data from a remote Kameleoon server based on the active `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.

```dart theme={null}
try {
    final data = await kameleoonClient.getRemoteData("test");
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
} on Exception {
    // Any other error (including network issues).
}
```

##### Parameters

| Name | Type   | Description                                                                      |
| ---- | ------ | -------------------------------------------------------------------------------- |
| key  | String | The key that the data you try to get is associated with. This field is optional. |

##### Return value

| Type              | Description                                                                            |
| ----------------- | -------------------------------------------------------------------------------------- |
| `Future<dynamic>` | Future with retrieving data for specific `key` (or `visitorCode` if `key` is omitted). |

| Type              | Description                                                                     |
| ----------------- | ------------------------------------------------------------------------------- |
| PlatformException | Exception indicating that the native plugin integration works incorrectly.      |
| Exception         | Exception indicating that the request timed out or any other reason of failure. |

#### 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.

Read [this article](/developer-docs/feature-experimentation/targeting-and-segmentation/native-segmentation) for a better understanding of possible use cases.

<Warning>
  By default, `getRemoteVisitorData()` automatically retrieves the latest stored custom data with `scope=Visitor` and attaches them to the visitor without having to call `addData()`. It is particularly useful for [synchronizing custom data between multiple devices](/developer-docs/sdks/web-sdks/nodejs-sdk#synchronizing-custom-data-across-devices).
</Warning>

```dart theme={null}
// Visitor data will be fetched and automatically added for `visitorCode`.
try {
    final visitorData = await kameleoonClient.getRemoteVisitorData();
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
} on Exception {
    // Any other error (including network issues).
}

// If you only want to fetch data and add it yourself manually, set addData == `false`.
try {
    final visitorData = await kameleoonClient.getRemoteVisitorData(addData: false);
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
} on Exception {
    // Any other error (including network issues).
}

// If you want to fetch custom list of data types
final filter = RemoteVisitorDataFilter.withValues(
    previousVisitAmount: 25,
    currentVisit: true,
    conversions: true,
);
try {
    final visitorData = await kameleoonClient.getRemoteVisitorData(filter: filter, addData: false);
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
} on Exception {
    // Any other error (including network issues).
}
```

##### Parameters

| Name    | Type                      | Description                                                                                                                                                                                                                                                                         |
| ------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| filter  | `RemoteVisitorDataFilter` | Filter that selects which data should be retrieved from visit history. By default, `getRemoteVisitorData` retrieves `CustomData` from the current and latest previous visit (`RemoteVisitorDataFilter()`). All other filters parameters default to `false`. This field is optional. |
| addData | boolean                   | A boolean indicating whether the method should automatically add retrieved data for a visitor. If unspecified, the default value is **true**. This field is optional.                                                                                                               |

##### Return value

| Type                 | Description                                           |
| -------------------- | ----------------------------------------------------- |
| `Future<List<Data>>` | An array containing the fetched data for the visitor. |

##### Exceptions thrown

| Type              | Description                                                                     |
| ----------------- | ------------------------------------------------------------------------------- |
| PlatformException | Exception indicating that the native plugin integration doesn't work correctly. |
| Exception         | Exception indicating that the request timed out or any other reason of failure. |

##### Using parameters in getRemoteVisitorData()

The `getRemoteVisitorData()` 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.

<Note>
  Here is the list of available `RemoteVisitorDataFilter` options:

  | Name                                                                | Type      | Description                                                                                                                                                                                                                                                                                                                                     | Default |
  | ------------------------------------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
  | previousVisitAmount <Badge color="green" size="sm">optional</Badge> | `int`     | Number of previous visits to retrieve data from. Number between `1` and `25`                                                                                                                                                                                                                                                                    | `1`     |
  | currentVisit <Badge color="green" size="sm">optional</Badge>        | `boolean` | If true, current visit data will be retrieved.                                                                                                                                                                                                                                                                                                  | `true`  |
  | customData <Badge color="green" size="sm">optional</Badge>          | `boolean` | If true, custom data will be retrieved.                                                                                                                                                                                                                                                                                                         | `true`  |
  | geolocation <Badge color="green" size="sm">optional</Badge>         | `boolean` | If true, geolocation data will be retrieved.                                                                                                                                                                                                                                                                                                    | `false` |
  | conversions <Badge color="green" size="sm">optional</Badge>         | `boolean` | If true, conversion data will be retrieved.                                                                                                                                                                                                                                                                                                     | `false` |
  | experiments <Badge color="green" size="sm">optional</Badge>         | `boolean` | If true, experiment data will be retrieved.                                                                                                                                                                                                                                                                                                     | `false` |
  | pageViews (*optional*, *web only*)                                  | `boolean` | If true, page data will be retrieved.                                                                                                                                                                                                                                                                                                           | `false` |
  | device (*optional*, *web only*)                                     | `boolean` | If true, device data will be retrieved.                                                                                                                                                                                                                                                                                                         | `false` |
  | browser (*optional*, *web only*)                                    | `boolean` | If true, browser data will be retrieved.                                                                                                                                                                                                                                                                                                        | `false` |
  | operatingSystem (*optional*, *web only*)                            | `boolean` | If true, operating system data will be retrieved.                                                                                                                                                                                                                                                                                               | `false` |
  | kcs <Badge color="green" size="sm">optional</Badge>                 | `boolean` | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the [AI Predictive Targeting add-on](/user-manual/assets/segments/target-users-based-on-likelihood-to-convert)                                                                                                                                                            | `false` |
  | visitorCode <Badge color="green" size="sm">optional</Badge>         | `boolean` | If true, Kameleoon will retrieve the `visitorCode` from the most recent visit and use it for the current visit. This is necessary if you want to ensure that the visitor, identified by their `visitorCode`, always receives the same variation across visits for [Cross-device experimentation](/developer-docs/cross-device-experimentation). | `true`  |
  | cbs <Badge color="green" size="sm">optional</Badge>                 | `boolean` | If true, Contextual Bandit score data will be retrieved.                                                                                                                                                                                                                                                                                        | `false` |
</Note>

#### getVisitorWarehouseAudience()

Retrieves all audience data associated with the visitor in your data warehouse. The optional `warehouseKey` 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](/user-manual/integrations/data-warehouses/bigquery/use-bigquery-as-a-source-audience-targeting) 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.

<Note>
  Since a server call is required, this mechanism is asynchronous.
</Note>

```dart theme={null}
try {
    final customData = await kameleoonClient.getVisitorWarehouseAudience(customDataIndex);
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
} on Exception {
    // Any other error (including network issues).
}

// If you need to specify warehouse key
try {
    final customData = await kameleoonClient.getVisitorWarehouseAudience(customDataIndex, "warehouseKey");
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
} on Exception {
    // Any other error (including network issues).
}
```

##### Parameters

| Name            | Type   | Description                                                                                             |
| --------------- | ------ | ------------------------------------------------------------------------------------------------------- |
| visitorCode     | string | A unique visitor identification string, can't exceed 255 characters.                                    |
| customDataIndex | int    | An integer representing the index of the custom data you want to use to target your BigQuery Audiences. |
| warehouseKey    | string | A unique key to identify the warehouse data (usually, your internal user ID). This field is optional.   |

##### Return value

| Type                 | Description                                                                     |
| -------------------- | ------------------------------------------------------------------------------- |
| `Future<CustomData>` | A `CustomData` instance confirming that the data has been added to the visitor. |

##### Exceptions thrown

| Type              | Description                                                                     |
| ----------------- | ------------------------------------------------------------------------------- |
| PlatformException | Exception indicating that the native plugin integration doesn't work correctly. |
| Exception         | Exception indicating that the request timed out or any other reason of failure. |

#### setLegalConsent()

You must use this method to specify whether the visitor has given legal consent to use their personal data. Setting the `consent` 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](/user-manual/project-management/consent-management-policy).

```dart theme={null}
try {
    final customData = await kameleoonClient.setLegalConsent(true);
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
} on Exception {
    // Any other error (including network issues).
}
```

##### Parameters

| Name    | Type    | Description                                                                                                                                                                                                             |
| ------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| consent | boolean | A boolean value representing the legal consent status. `true` indicates the visitor has given legal consent, `false` indicates the visitor has never provided, or has withdrawn, legal consent. This field is required. |

##### Exceptions thrown

| Type              | Description                                                                |
| ----------------- | -------------------------------------------------------------------------- |
| PlatformException | Exception indicating that the native plugin integration works incorrectly. |

##### Consent revocation behavior

<Note>
  This is applicable only to the Flutter Web SDK.
</Note>

When you call `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 the `Data` types supported by Kameleoon. Several standard data types are provided, as well as the `CustomData` type for defining custom data types.

#### Conversion

The `Conversion` data set stored here can be used to filter experiment and personalization reports by any goal associated with it.

<Tip>
  * Each visitor can have multiple `Conversion` objects.
  * You can find the `goalId` in the Kameleoon app.
</Tip>

| Name                                                       | Type               | Description                                     | Default |
| ---------------------------------------------------------- | ------------------ | ----------------------------------------------- | ------- |
| `goalId` <Badge color="red" size="sm">required</Badge>     | `int`              | ID of the goal.                                 |         |
| `revenue` <Badge color="green" size="sm">optional</Badge>  | `double`           | Revenue of the conversion                       | `0`     |
| `negative` <Badge color="green" size="sm">optional</Badge> | `bool`             | Defines if the revenue is positive or negative. | `false` |
| `metadata` <Badge color="green" size="sm">optional</Badge> | `List<CustomData>` | Metadata of the conversion.                     | `[]`    |

```dart theme={null}
try {
    final conversion = Conversion(32, 10);
    final conversionMetadata = Conversion(32, 10, false, [CustomData.withIndex(1, values: ["true"])]);
    final conversionOptParams = Conversion.withOptParams(32, metadata: [CustomData.withIndex(1, values: ["true"])]);

    await kameleoonClient.addData([conversion, conversionMetadata, conversionOptParams]);
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
}
```

#### CustomData

<Note>
  This data type is available for both types of SDKs: Mobile & Web.
</Note>

`CustomData` allows any type of data to be easily associated with each visitor. `CustomData` can then be used as a targeting condition in [segments](/user-manual/assets/segments/create-a-segment/) or as a filter/breakdown in experiment reports.

To learn more about custom data, please refer to this [article](/developer-docs/custom-data).

| Name                                                      | Type           | Description                                                                                                                                                                             |        |
| --------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ |
| index/name <Badge color="red" size="sm">required</Badge>  | `int`/`String` | Index or Name of the custom data. **Either `index` or `name` must be provided** to identify the data.                                                                                   |        |
| overwrite <Badge color="green" size="sm">optional</Badge> | `bool`         | Flag to explicitly control how the values are stored and how they appear in reports. [See more](/developer-docs/custom-data#default-logic-when-overwrite-parameter-is-false-or-omitted) | `true` |
| values <Badge color="green" size="sm">optional</Badge>    | `List<String>` | Values of the custom data to be stored.                                                                                                                                                 |        |

<Note>
  * Each visitor is allowed only one `CustomData` for each unique `index`. Adding another `CustomData` with the same `index` will replace the existing `CustomData`.
  * The custom data `index` can be found in the [Custom Data dashboard](/user-manual/assets/custom-data/manage-custom-data) 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 `CustomData` instance 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.
</Note>

```dart theme={null}
try {
    await kameleoonClient.addData([CustomData.withIndex(1, values: ["some custom value"])]);

    // With several values
    await kameleoonClient.addData(CustomData.withIndex(1, values: ["value 1", "value 2"]))

    // To set the 'overwrite' flag to false
    await kameleoonClient.addData(CustomData.withIndex(1, overwrite: false, values: ["first value", "second value"]))

    // To use a name instead of the index
    await kameleoonClient.addData(CustomData.withName("my-custom-data", values: ["value"]))
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
}
```

#### Device

<Note>
  This data type is available for both types of SDKs: Mobile & Web.
</Note>

Store information about the user's device.

| Name   | Type    | Description                                                             |
| ------ | ------- | ----------------------------------------------------------------------- |
| device | Devices | List of devices: `phone`, `tablet`, `desktop`. This field is mandatory. |

```dart theme={null}
try {
    await kameleoonClient.addData([Device(Devices.phone)]);
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
}
```

#### Geolocation

<Note>
  This data type is available for both types of SDKs: Mobile & Web.
</Note>

`Geolocation` contains the visitor's geolocation details.

| Name                                                         | Type                   | Description                                                                                                      |
| ------------------------------------------------------------ | ---------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `country` <Badge color="red" size="sm">required</Badge>      | `String`               | The country of the visitor.                                                                                      |
| `region` <Badge color="green" size="sm">optional</Badge>     | <nobr>`String?`</nobr> | The region of the visitor.                                                                                       |
| `city` <Badge color="green" size="sm">optional</Badge>       | <nobr>`String?`</nobr> | The city of the visitor.                                                                                         |
| `postalCode` <Badge color="green" size="sm">optional</Badge> | <nobr>`String?`</nobr> | The postal code of the visitor.                                                                                  |
| `latitude` <Badge color="green" size="sm">optional</Badge>   | `double?`              | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees.  |
| `longitude` <Badge color="green" size="sm">optional</Badge>  | `double?`              | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |

<Tip>
  * Each visitor can have only one `Geolocation`. Adding a second `Geolocation` overwrites the first one.
</Tip>

```dart theme={null}
try {
    await kameleoonClient.addData([Geolocation("France", region: "Île-de-France", city: "Paris")]);
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
}
```

#### Browser

<Note>
  The data type is available only for Web SDK
</Note>

The `Browser` data set stored here can be used to filter experiment and personalization reports by any value associated with it.

| Name                                                      | Type       | Description                                                                                     |
| --------------------------------------------------------- | ---------- | ----------------------------------------------------------------------------------------------- |
| `browser` <Badge color="red" size="sm">required</Badge>   | `Browsers` | List of browsers: `chrome`, `internetExplorer`, `firefox`, `safari`, `opera`, `other`.          |
| `version` <Badge color="green" size="sm">optional</Badge> | `double?`  | Version of the browser, floating point number represents major and minor version of the browser |

```dart theme={null}
try {
    await kameleoonClient.addData([Browser(Browsers.chrome)]);

    await kameleoonClient.addData([Browser(Browsers.chrome, 10.0)]);
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
}
```

#### PageView

<Note>
  This data type is only available for Web SDKs.
</Note>

| Name      | Type        | Description                                        |
| --------- | ----------- | -------------------------------------------------- |
| url       | String      | URL of the page viewed. This field is mandatory.   |
| title     | String      | Title of the page viewed. This field is mandatory. |
| referrers | `List<int>` | Referrers of viewed pages. This field is optional. |

<Note>
  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](/user-manual/assets/advanced-targeting-tools/create-an-acquisition-channel) you create for a given site will have the ID 0, not 1.
</Note>

```dart theme={null}
try {
    await kameleoonClient.addData([PageView("https://url.com", "title", [3])]);
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
}
```

#### OperatingSystem

<Note>
  This data type is only available for Web SDKs.
</Note>

`OperatingSystem` contains information about the operating system on the visitor's device.

<Tip>
  Each visitor can only have one `OperatingSystem`. Adding a second `OperatingSystem` overwrites the first one.
</Tip>

| Name | Type               | Description                                                                                                      |
| ---- | ------------------ | ---------------------------------------------------------------------------------------------------------------- |
| type | `OperatingSystems` | List of operating systems: `windows`, `mac`, `ios`, `linux`, `android`, `windowsPhone` . This field is required. |

```dart theme={null}
try {
    await kameleoonClient.addData([OperatingSystem(OperatingSystem.linux)]);
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
}
```

#### Cookie

<Note>
  This data type is only available for Web SDKs.
</Note>

`Cookie` contains information about the cookie stored on the visitor's device.

| Name    | Type                  | Description                                                                       |
| ------- | --------------------- | --------------------------------------------------------------------------------- |
| cookies | `Map<String, String>` | A string object map consisting of cookie keys and values. This field is required. |

<Tip>
  Each visitor can only have one `Cookie`. Adding second `Cookie` overwrites the first one.
</Tip>

```dart theme={null}
try {
    await kameleoonClient.addData([Cookie({
        "my_key1": "my_value1",
        "my_key2": "my_value2"
    })]);
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
}
```

### Returned Types

#### DataFile

The `DataFile` 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.

| Name           | Type                       | Description                                                                       |
| -------------- | -------------------------- | --------------------------------------------------------------------------------- |
| `featureFlags` | `Map<String, FeatureFlag>` | A map of [`FeatureFlag`](#featureflag) objects, keyed by feature flag keys.       |
| `dateModified` | `int`                      | The timestamp (in milliseconds) indicating when the `DataFile` was last modified. |

```dart theme={null}
// Retrieves the map of feature flags from the DataFile.
// The map is keyed by feature flag identifiers, with each value being a FeatureFlag object.
final featureFlags = dataFile.featureFlags;

// Retrieves the last modification timestamp of the DataFile.
// The value is an int representing milliseconds since the Unix epoch.
final dateModified = dataFile.dateModified;
```

#### FeatureFlag

The `FeatureFlag` represents a set of properties that define a feature flag itself — for example, its [`Variations`](#variation), [`Rules`](#rule), 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.

| Name                  | Type                     | Description                                                                |
| --------------------- | ------------------------ | -------------------------------------------------------------------------- |
| `environmentEnabled`  | `bool`                   | Indicating whether the feature flag is enabled in the current environment. |
| `defaultVariationKey` | `String`                 | The key of the default variation associated with the feature flag.         |
| `variations`          | `Map<String, Variation>` | A map of `Variation` objects, keyed by variation keys.                     |
| `rules`               | `List<Rule>`             | A list of `Rule` objects                                                   |

```dart theme={null}
// Check whether the feature flag is enabled in the current environment
final isEnvironmentEnabled = featureFlag.environmentEnabled

// Retrieve the key of the default variation
final defaultVariationKey = featureFlag.defaultVariationKey

// Retrieve the default variation object
final defaultVariation = featureFlag.defaultVariation

// Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object)
final variations = featureFlag.variations

// Retrieve all targeting rules associated with the feature flag
final rules = featureFlag.rules
```

#### Rule

The `Rule` represents a set of properties that define a rule itself — for example, its [`Variations`](#variation).

It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.

| Name         | Type                     | Description                                            |
| ------------ | ------------------------ | ------------------------------------------------------ |
| `variations` | `Map<String, Variation>` | A map of `Variation` objects, keyed by variation keys. |

```dart theme={null}
// Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
final variations = rule.variations
```

#### Variation

`Variation` contains information about the visitor's assigned variation (or the default variation, if no specific assignment exists).

| Name         | Type                    | Description                                                                                                                                          |
| ------------ | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| name         | `String`                | The name of the variation.                                                                                                                           |
| key          | `String`                | The unique key identifying the variation.                                                                                                            |
| id           | `int?`                  | The ID of the assigned variation (or `null` if it's the default variation).                                                                          |
| experimentId | `int?`                  | The ID of the experiment associated with the variation (or `null` if default).                                                                       |
| variables    | `Map<String, Variable>` | A map containing the variables of the assigned variation, keyed by variable names. This could be an empty collection if no variables are associated. |

<Note>
  * The `Variation` object provides details about the assigned variation and its associated experiment, while the [`Variable`](#variable) object contains specific details about each variable within a variation.
  * Ensure that your code handles the case where `id` or `experimentId` may be `null`, indicating a default variation.
  * The `variables` map might be empty if no variables are associated with the variation.
</Note>

```dart theme={null}
// Retrieving the variation name
var variationName = variation.name

// Retrieving the variation key
var variationKey = variation.key;

// Retrieving the variation id
var variationId = variation.id;

// Retrieving the experiment id
var experimentId = variation.experimentId;

// Retrieving the variables map
var variables = variation.variables;
```

#### Variable

`Variable` contains information about a variable associated with the assigned variation.

| Name  | Type      | Description                                                                                                                                                                      |
| ----- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| key   | `String`  | The unique key identifying the variable.                                                                                                                                         |
| type  | `String`  | The type of the variable. Possible values: **BOOLEAN**, **NUMBER**, **STRING**, **JSON**.                                                                                        |
| value | `dynamic` | The value of the variable, which can be of the following types: **bool**, **int**, **double**, **String**, **Map\<String, dynamic>** (json object), **\[dynamic]** (json array). |

```swift theme={null}
// Retrieving the variables map
var variables = variation.variables;

// Variable type can be retrieved for further processing
var type = variables["isDiscount"]?.type ?? "";

// Retrieving the variable value by key
var isDiscount = variables["isDiscount"]?.value as bool? ?? false;

// Variable value can be of different types
var title = variables["title"]?.value as String? ?? "";
```

### Deprecated methods

<Warning>
  These methods are deprecated and will be removed in SDK version `4.0.0`.
</Warning>

#### isReady()

<Warning>
  Use [`isReadyAsync()`](#isreadyasync) instead. On iOS and Android, [`isReady()`](#isready) may return incorrect (`false`) results even if the SDK has already been initialized with [`defaultDataFile`](#initialize-the-kameleoon-client).
</Warning>

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. Use `isReady()` 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()`](#runwhenready) method for details).

```dart theme={null}
final ready = kameleoonClient.isReady();
```

##### Return value

| Name  | Type | Description                                                                                |
| ----- | ---- | ------------------------------------------------------------------------------------------ |
| ready | bool | Boolean representing the SDK's status (properly initialized, or not yet ready to be used). |

#### getFeatureVariationKey()

* 📨 *Sends Tracking Data to Kameleoon*

<Note>
  Use [`getVariation()`](#getvariation) instead.
</Note>

Use this method to get the feature variation key for a visitor. This method takes `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.

```dart theme={null}
String featureKey = "new_checkout";
String variationKey = "";

try {
    variationKey = await kameleoonClient.getFeatureVariationKey(featureKey);
} on SDKNotReady {
    // Exception indicates that the SDK has not completed its initialization yet.
} on FeatureNotFound {
    // The error has occurred; feature flag isn't found in current configuration.
} on FeatureEnvironmentDisabled {
    // The feature flag is disabled for the environment.
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
} on Exception {
    // Any other error.
}

switch(variationKey) {
    case 'on':
        // Main variation key is selected for visitorCode
        break;
    case 'alternative_variation':
        // Alternative variation key
        break;
    default:
        // Default variation key
        break;
}
```

##### Parameters

| Name       | Type   | Description                                                               |
| ---------- | ------ | ------------------------------------------------------------------------- |
| featureKey | String | Key of the feature you want to expose to a user. This field is mandatory. |

##### Return value

| Type             | Description                                                        |
| ---------------- | ------------------------------------------------------------------ |
| `Future<String>` | Variation key of the feature flag that is registered to a visitor. |

##### Exceptions thrown

| Type              | Description                                                                                                                                                                                                                                                                       |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| SDKNotReady       | Exception indicating that the SDK has not completed its initialization.                                                                                                                                                                                                           |
| FeatureNotFound   | Exception indicating that the requested feature ID was not found in the SDK's internal configuration. This exception usually means that the feature flag has not been activated on the Kameleoon side (but code implementing the feature is already deployed in the application). |
| PlatformException | Exception indicating that the native plugin integration don't work correctly.                                                                                                                                                                                                     |

#### getActiveFeatures()

<Note>
  * Use [`getVariations()`](#getvariations) instead.
  * Previously called `getFeatureListForVisitorCode`, which was removed in SDK version `4.0.0` release.
</Note>

`getActiveFeatures` method retrieves information about the active feature flags that are available for the visitor.

```dart theme={null}
try {
    final activeFeatures = await kameleoonClient.getActiveFeatures();
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
}
```

##### Return value

| Type                             | Description                                                                                                           |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `Future<Map<String, Variation>>` | Map that contains the assigned variations of the active features using the keys of the corresponding active features. |

#### getFeatureVariable()

* 📨 *Sends Tracking Data to Kameleoon*

<Note>
  - Use [`getVariation()`](#getvariation) instead.
  - This method was previously called `obtainFeatureVariable`, which was removed in SDK version `3.0.0`.
</Note>

This method gets a variable value of variation key for a specific user. It takes a `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.

```dart theme={null}
String featureKey = "feature_key";
String variableKey = "product_number";
int recommendedProductsNumber = 5;
try {
  recommendedProductsNumber = await kameleoonClient.getFeatureVariable(featureKey, variableKey);
} on SDKNotReady {
  // Exception indicates that the SDK has not completed its initialization yet.
} on FeatureNotFound {
  // The error has occurred; feature flag isn't found in current configuration.
} on FeatureEnvironmentDisabled {
  // The feature flag is disabled for the environment.
} on FeatureVariableNotFound {
  // Requested variable not defined in Kameleoon.
} on KameleoonException {
  // Generic exception in native plugin integration occurred.
} on Exception {
  // Any other error.
}

setState(() {
    _recommendedProductsNumber = recommendedProductsNumber;
});
```

##### Parameters

| Name        | Type   | Description                                                                      |
| ----------- | ------ | -------------------------------------------------------------------------------- |
| featureKey  | String | Key of the feature you want to expose to a user. This field is mandatory.        |
| variableKey | String | Name of the variable for which you want to get a value. This field is mandatory. |

##### Return value

| Type              | Description                                                                                                                                               |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Future<dynamic>` | Value of the variation's variable that is registered to a visitor for this feature flag. Possible types: `bool`, `int`, `double`, `String`, `List`, `Map` |

##### Exceptions thrown

| Type                       | Description                                                                                                                                                                                                                                                                       |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| SDKNotReady                | Exception indicating that the SDK has not completed its initialization.                                                                                                                                                                                                           |
| FeatureNotFound            | Exception indicating that the requested feature ID was not found in the SDK's internal configuration. This exception usually means that the feature flag has not been activated on the Kameleoon side (but code implementing the feature is already deployed in the application). |
| FeatureEnvironmentDisabled | Exception indicating that the feature flag is disabled for the visitor's current environment (for example, production, staging, or development).                                                                                                                                  |
| FeatureVariableNotFound    | Exception indicating that the specified variable was not found. Check that the variable key in the Kameleoon app matches the key in your code.                                                                                                                                    |
| PlatformException          | Exception indicating that the native plugin integration works incorrectly.                                                                                                                                                                                                        |

#### getFeatureVariationVariables()

<Note>
  * Use [`getVariation()`](#getvariation) instead.
  * This method was previously called `getFeatureAllVariables`, which was removed in SDK version `4.0.0` release.
</Note>

To retrieve all of a feature's variables, call this method. You can modify your feature variables in the Kameleoon app.

This method takes one input parameter: `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.

```dart theme={null}
final featureKey = "featureKey";
final variationKey = "variationKey";

try {
    final allVariables = await client.getFeatureVariationVariables(featureKey, variationKey);
} on SDKNotReady {
  // Exception indicates that the SDK has not completed its initialization yet.
} on FeatureNotFound {
    // The error has occurred; feature flag isn't found in current configuration.
} on FeatureEnvironmentDisabled {
    // The feature flag is disabled for the environment.
} on KameleoonException {
    // Generic exception in native plugin integration occurred.
} on Exception {
    // Any other error.
}
```

##### Parameters

| Name                                                       | Type   | Description                                       |
| ---------------------------------------------------------- | ------ | ------------------------------------------------- |
| featureKey <Badge color="red" size="sm">required</Badge>   | String | Identifier key of the feature you want to obtain. |
| variationKey <Badge color="red" size="sm">required</Badge> | String | The key of the variation you want to obtain.      |

##### Return value

| Type                           | Description                                                                                                                                                  |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Future<Map<String, dynamic>>` | Data associated with this feature flag. The values of can be an int, double, bool, String, List or Map (depending on the type defined on the web interface). |

##### Exceptions thrown

| Type                       | Description                                                                                                                                                                                                                                       |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| FeatureNotFound            | Exception indicating that the requested feature has not been found in the SDK's internal configuration. This exception is usually normal and means that the feature flag has not been activated on Kameleoon's side.                              |
| FeatureEnvironmentDisabled | Exception indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).                                                                                                      |
| FeatureVariationNotFound   | Exception indicating that the requested variation ID has not been found in the SDK's internal configuration. This exception is usually normal and means that the variation's corresponding experiment has not been activated on Kameleoon's side. |
| PlatformException          | Exception indicating that the native plugin integration doesn't work correctly.                                                                                                                                                                   |
