# Source: https://configcat.com/docs/sdk-reference/dart.md

# Dart (Flutter) SDK Reference

Copy page

[![Star on GitHub](https://img.shields.io/github/stars/configcat/dart-sdk.svg?style=social)](https://github.com/configcat/dart-sdk/stargazers) [![pub package](https://img.shields.io/pub/v/configcat_client.svg)](https://pub.dev/packages/configcat_client) [![Dart CI](https://github.com/configcat/dart-sdk/actions/workflows/dart-ci.yml/badge.svg?branch=main)](https://github.com/configcat/dart-sdk/actions/workflows/dart-ci.yml)

[ConfigCat Dart (Flutter) SDK on GitHub](https://github.com/configcat/dart-sdk)

## Getting Started[​](#getting-started "Direct link to Getting Started")

### 1. Add the ConfigCat SDK to your project[​](#1-add-the-configcat-sdk-to-your-project "Direct link to 1. Add the ConfigCat SDK to your project")

* Dart
* Flutter

```bash
dart pub add configcat_client

```

```bash
flutter pub add configcat_client

```

Or put the following directly to your `pubspec.yml` and run `dart pub get` or `flutter pub get`.

pubspec.yml

```yaml
dependencies:
  configcat_client: ^4.0.0

```

### 2. Import the ConfigCat SDK[​](#2-import-the-configcat-sdk "Direct link to 2. Import the ConfigCat SDK")

```dart
import 'package:configcat_client/configcat_client.dart';

```

### 3. Create the *ConfigCat* client with your *SDK Key*[​](#3-create-the-configcat-client-with-your-sdk-key "Direct link to 3-create-the-configcat-client-with-your-sdk-key")

```dart
final client = ConfigCatClient.get(sdkKey: '#YOUR-SDK-KEY#');

```

### 4. (Optional) Set up Flutter caching[​](#4-optional-set-up-flutter-caching "Direct link to 4. (Optional) Set up Flutter caching")

If you're using the SDK in a Flutter application, it's recommended to use the [Flutter Preferences Cache](https://github.com/configcat/flutter-preferences-cache) implementation for caching. It stores the downloaded `config JSON` using the [shared\_preferences](https://pub.dev/packages/shared_preferences) package.

```dart
import 'package:configcat_preferences_cache/configcat_preferences_cache.dart';

```

```dart
final client = ConfigCatClient.get(
    sdkKey: '#YOUR-SDK-KEY#',
    options: ConfigCatOptions(cache: ConfigCatPreferencesCache()));

```

### 5. Get your setting value[​](#5-get-your-setting-value "Direct link to 5. Get your setting value")

```dart
final isMyAwesomeFeatureEnabled = await client.getValue(key: 'isMyAwesomeFeatureEnabled', defaultValue: false);
if (isMyAwesomeFeatureEnabled) {
    doTheNewThing();
} else {
    doTheOldThing();
}

```

### 6. Close *ConfigCat* client​[​](#6-close-configcat-client "Direct link to 6-close-configcat-client")

You can safely shut down all clients at once or individually and release all associated resources on application exit.

```dart
ConfigCatClient.closeAll(); // closes all clients

client.close(); // closes the specific client

```

## Setting up the *ConfigCat Client*[​](#setting-up-the-configcat-client "Direct link to setting-up-the-configcat-client")

*ConfigCat Client* is responsible for:

* managing the communication between your application and ConfigCat servers.
* caching your setting values and feature flags.
* serving values quickly in a failsafe way.

`ConfigCatClient.get(sdkKey: <sdkKey>)` returns a client with default options.

### Customizing the *ConfigCat Client*[​](#customizing-the-configcat-client "Direct link to customizing-the-configcat-client")

To customize the SDK's behavior, you can pass an additional `ConfigCatOptions` parameter to the `get()` static factory method where the `ConfigCatOptions` class is used to set up the *ConfigCat Client*.

```dart
final client = ConfigCatClient.get(
    sdkKey: '#YOUR-SDK-KEY#',
    options: ConfigCatOptions(
        pollingMode: PollingMode.manualPoll(),
        logger: ConfigCatLogger(level: LogLevel.info)
    )
);

```

These are the available options on the `ConfigCatOptions` class:

| Properties       | Description                                                                                                                                                                                                                                                                                                                   |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `dataGovernance` | Optional, defaults to `global`. Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. [More about Data Governance](https://configcat.com/docs/advanced/data-governance.md). Available options: `global`, `euOnly`. |
| `baseUrl`        | Optional, sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the config JSON.                                                                                                                                                                                                     |
| `connectTimeout` | Optional, sets the underlying [Dio](https://github.com/flutterchina/dio) HTTP client's connect timeout. [More about the HTTP Client](#httpclient).                                                                                                                                                                            |
| `receiveTimeout` | Optional, sets the underlying [Dio](https://github.com/flutterchina/dio) HTTP client's receive timeout. [More about the HTTP Client](#httpclient).                                                                                                                                                                            |
| `sendTimeout`    | Optional, sets the underlying [Dio](https://github.com/flutterchina/dio) HTTP client's send timeout. [More about the HTTP Client](#httpclient).                                                                                                                                                                               |
| `cache`          | Optional, sets a custom cache implementation for the client. [More about cache](#custom-cache).                                                                                                                                                                                                                               |
| `pollingMode`    | Optional, sets the polling mode for the client. [More about polling modes](#polling-modes).                                                                                                                                                                                                                                   |
| `logger`         | Optional, sets the internal logger and log level. [More about logging](#logging).                                                                                                                                                                                                                                             |
| `override`       | Optional, sets local feature flag & setting overrides. [More about feature flag overrides](#flag-overrides).                                                                                                                                                                                                                  |
| `defaultUser`    | Optional, sets the default user. [More about default user](#default-user).                                                                                                                                                                                                                                                    |
| `offline`        | Optional, defaults to `false`. Indicates whether the SDK should be initialized in offline mode. [More about offline mode](#online--offline-mode).                                                                                                                                                                             |
| `hooks`          | Optional, used to subscribe events that the SDK sends in specific scenarios. [More about hooks](#hooks).                                                                                                                                                                                                                      |

caution

We strongly recommend you to use the `ConfigCatClient` as a Singleton object in your application. The `ConfigCatClient.get(sdkKey: <sdkKey>)` static factory method constructs singleton client instances for your SDK keys. These clients can be closed all at once with the `ConfigCatClient.closeAll()` method or individually with `client.close()`.

## Anatomy of `getValue()`[​](#anatomy-of-getvalue "Direct link to anatomy-of-getvalue")

| Parameters     | Description                                                                                                                                       |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`          | **REQUIRED.** The key of a specific setting or feature flag. Set on *ConfigCat Dashboard* for each setting.                                       |
| `defaultValue` | **REQUIRED.** This value will be returned in case of an error.                                                                                    |
| `user`         | Optional, *User Object*. Essential when using Targeting. [Read more about Targeting.](https://configcat.com/docs/targeting/targeting-overview.md) |

```dart
final value = await client.getValue(
    key: 'keyOfMySetting',
    defaultValue: false,
    user: ConfigCatUser(identifier: '#USER-IDENTIFIER#'), // Optional User Object
);

```

caution

It is important to provide an argument for the `defaultValue` parameter, specifically for the `T` generic type parameter, that matches the type of the feature flag or setting you are evaluating. Please refer to the following table for the corresponding types.

### Setting type mapping[​](#setting-type-mapping "Direct link to Setting type mapping")

| Setting Kind   | Type parameter `T` |
| -------------- | ------------------ |
| On/Off Toggle  | `bool`/`bool?`     |
| Text           | `String`/`String?` |
| Whole Number   | `int`/`int?`       |
| Decimal Number | `double`/`double?` |

In addition to the types mentioned above, you also have the option to provide `object`, `object?` or `dynamic` for the type parameter regardless of the setting kind.

It's important to note that providing any other type for the type parameter will result in an `ArgumentError`.

If you specify an allowed type but it mismatches the setting kind, an error message will be logged and `defaultValue` will be returned.

When relying on type inference and not explicitly specifying the type parameter, be mindful of potential type mismatch issues, especially with number types. For example, `client.getValue(key: "keyOfMyDecimalSetting", defaultValue: 0)` will return `defaultValue` (`0`) instead of the actual value of the decimal setting because the compiler infers the type as `int` instead of `double`, that is, the call is equivalent to `client.getValue<int>("keyOfMyDecimalSetting", 0)`, which is a type mismatch.

To correctly evaluate a decimal setting, you should use:

```dart
var value = client.getValue("keyOfMyDecimalSetting", 0.0);
// -or-
var value = client.getValue<double>("keyOfMyDecimalSetting", 0);

```

## Anatomy of `getValueDetails()`[​](#anatomy-of-getvaluedetails "Direct link to anatomy-of-getvaluedetails")

`getValueDetails()` is similar to `getValue()` but instead of returning the evaluated value only, it gives more detailed information about the evaluation result.

| Parameters     | Description                                                                                                                                       |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`          | **REQUIRED.** The key of a specific setting or feature flag. Set on *ConfigCat Dashboard* for each setting.                                       |
| `defaultValue` | **REQUIRED.** This value will be returned in case of an error.                                                                                    |
| `user`         | Optional, *User Object*. Essential when using Targeting. [Read more about Targeting.](https://configcat.com/docs/targeting/targeting-overview.md) |

```dart
final details = await client.getValueDetails(
    key: 'keyOfMySetting',
    defaultValue: false,
    user: ConfigCatUser(identifier: '#USER-IDENTIFIER#'), // Optional User Object
);

```

caution

It is important to provide an argument for the `defaultValue` parameter, specifically for the `T` generic type parameter, that matches the type of the feature flag or setting you are evaluating. Please refer to [this table](#setting-type-mapping) for the corresponding types.

The `details` result contains the following information:

| Field                     | Type                                 | Description                                                                                                |
| ------------------------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------- |
| `value`                   | `bool` / `String` / `int` / `double` | The evaluated value of the feature flag or setting.                                                        |
| `key`                     | `String`                             | The key of the evaluated feature flag or setting.                                                          |
| `isDefaultValue`          | `bool`                               | True when the default value passed to `getValueDetails()` is returned due to an error.                     |
| `error`                   | `String?`                            | In case of an error, this property contains the error message.                                             |
| `user`                    | `ConfigCatUser?`                     | The User Object that was used for evaluation.                                                              |
| `matchedPercentageOption` | `PercentageOption?`                  | The Percentage Option (if any) that was used to select the evaluated value.                                |
| `matchedTargetingRule`    | `TargetingRule?`                     | The Targeting Rule (if any) that matched during the evaluation and was used to return the evaluated value. |
| `fetchTime`               | `DateTime`                           | The last download time of the current config.                                                              |

## User Object[​](#user-object "Direct link to User Object")

The [User Object](https://configcat.com/docs/targeting/user-object.md) is essential if you'd like to use ConfigCat's [Targeting](https://configcat.com/docs/targeting/targeting-overview.md) feature.

```dart
final user = ConfigCatUser(identifier: '#UNIQUE-USER-IDENTIFIER#');

```

```dart
final user = ConfigCatUser(identifier: 'john@example.com');

```

### Customized User Object creation[​](#customized-user-object-creation "Direct link to Customized User Object creation")

| Argument     | Description                                                                                                                     |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| `identifier` | **REQUIRED.** Unique identifier of a user in your application. Can be any value, even an email address.                         |
| `email`      | Optional parameter for easier Targeting Rule definitions.                                                                       |
| `country`    | Optional parameter for easier Targeting Rule definitions.                                                                       |
| `custom`     | Optional dictionary for custom attributes of a user for advanced Targeting Rule definitions. e.g. User role, Subscription type. |

```dart
final user = ConfigCatUser(
    identifier: '#UNIQUE-USER-IDENTIFIER#',
    email: 'john@example.com',
    country: 'United Kingdom',
    custom: {
        'SubscriptionType': 'Pro',
        'UserRole': 'Admin'
    }
);

```

The `custom` map also allows attribute values other than `String` values:

```dart
final user = ConfigCatUser(
    identifier: '#UNIQUE-USER-IDENTIFIER#',
    email: 'john@example.com',
    country: 'United Kingdom',
    custom:  {
      'Rating': 4.5,
      'RegisteredAt': DateTime.parse('2023-11-22 12:34:56 +00:00'),
      'Roles': {"Role1", "Role2"}
    }
);

```

### User Object Attribute Types[​](#user-object-attribute-types "Direct link to User Object Attribute Types")

All comparators support `String` values as User Object attribute (in some cases they need to be provided in a specific format though, see below), but some of them also support other types of values. It depends on the comparator how the values will be handled. The following rules apply:

**Text-based comparators** (EQUALS, IS ONE OF, etc.)

* accept `String` values,
* all other values are automatically converted to `String` (a warning will be logged but evaluation will continue as normal).

**SemVer-based comparators** (IS ONE OF, <, >=, etc.)

* accept `String` values containing a properly formatted, valid semver value,
* all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

**Number-based comparators** (=, <, >=, etc.)

* accept `double` values and all other numeric values which can safely be converted to `double`,
* accept `String` values containing a properly formatted, valid `double` value,
* all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

**Date time-based comparators** (BEFORE / AFTER)

* accept `DateTime` values, which are automatically converted to a second-based Unix timestamp,
* accept `double` values representing a second-based Unix timestamp and all other numeric values which can safely be converted to `Double`,
* accept `String` values containing a properly formatted, valid `double` value,
* all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

**String array-based comparators** (ARRAY CONTAINS ANY OF / ARRAY NOT CONTAINS ANY OF)

* accept lists or sets of `String`,
* accept `String` values containing a valid JSON string which can be deserialized to an array of `String`,
* all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

### Default user[​](#default-user "Direct link to Default user")

There's an option to set a default User Object that will be used at feature flag and setting evaluation. It can be useful when your application has a single user only, or rarely switches users.

You can set the default User Object either on SDK initialization:

```dart
final client = ConfigCatClient.get(
    sdkKey: '#YOUR-SDK-KEY#',
    options: ConfigCatOptions(
        defaultUser: ConfigCatUser(identifier: 'john@example.com')
    )
);

```

or with the `setDefaultUser()` method of the ConfigCat client.

```dart
client.setDefaultUser(ConfigCatUser(identifier: 'john@example.com'));

```

Whenever the `getValue()`, `getValueDetails()`, `getAllValues()`, or `getAllVariationIds()` methods are called without an explicit `user` parameter, the SDK will automatically use the default user as a User Object.

```dart
final user = ConfigCatUser(identifier: 'john@example.com');
client.setDefaultUser(user);

// The default user will be used at the evaluation process.
final value = await client.getValue(key: 'keyOfMySetting', defaultValue: false);

```

When the `user` parameter is specified on the requesting method, it takes precedence over the default user.

```dart
final user = ConfigCatUser(identifier: 'john@example.com');
client.setDefaultUser(user);

final otherUser = ConfigCatUser(identifier: 'brian@example.com');

// otherUser will be used at the evaluation process.
final value = await client.getValue(key: 'keyOfMySetting', defaultValue: false, user: otherUser);

```

For deleting the default user, you can do the following:

```dart
client.clearDefaultUser();

```

## Polling Modes[​](#polling-modes "Direct link to Polling Modes")

The *ConfigCat SDK* supports 3 different polling strategies to fetch feature flags and settings from the ConfigCat CDN. Once the latest data is downloaded, it is stored in the cache, then calls to `getValue()` use the cached data to evaluate feature flags and settings. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle.<br />[More about polling modes.](https://configcat.com/docs/advanced/caching.md)

### Auto polling (default)[​](#auto-polling-default "Direct link to Auto polling (default)")

The *ConfigCat SDK* downloads the latest config data from the ConfigCat CDN automatically every 60 seconds and stores it in the cache.

Use the the `autoPollInterval` option parameter of the `PollingMode.autoPoll()` to change the polling interval.

```dart
final client = ConfigCatClient.get(
    sdkKey: '<PLACE-YOUR-SDK-KEY-HERE>',
    options: ConfigCatOptions(
        pollingMode: PollingMode.autoPoll(
            autoPollInterval: Duration(seconds: 100),
        ),
    )
);

```

Available options:

| Option Parameter   | Description                                                                                         | Default |
| ------------------ | --------------------------------------------------------------------------------------------------- | ------- |
| `autoPollInterval` | Polling interval.                                                                                   | 60      |
| `maxInitWaitTime`  | Maximum waiting time between the client initialization and the first config acquisition in seconds. | 5       |

### Lazy Loading[​](#lazy-loading "Direct link to Lazy Loading")

When calling `getValue()`, the *ConfigCat SDK* downloads the latest config data from the ConfigCat CDN only if it is not already present in the cache, or if the cache has expired. In this case `getValue()` will return the setting value after the cache is updated.

Use the `cacheRefreshInterval` option parameter of the `PollingMode.lazyLoad()` to set cache lifetime.

```dart
final client = ConfigCatClient.get(
    sdkKey: '<PLACE-YOUR-SDK-KEY-HERE>',
    options: ConfigCatOptions(
        pollingMode: PollingMode.lazyLoad(
            // the cache will expire in 100 seconds
            cacheRefreshInterval: Duration(seconds: 100),
        ),
    )
);

```

Available options:

| Parameter              | Description | Default |
| ---------------------- | ----------- | ------- |
| `cacheRefreshInterval` | Cache TTL.  | 60      |

### Manual Polling[​](#manual-polling "Direct link to Manual Polling")

Manual polling gives you full control over when the config data is downloaded from the ConfigCat CDN. The *ConfigCat SDK* will not download it automatically. Calling `forceRefresh()` is your application's responsibility.

```dart
final client = ConfigCatClient.get(
    sdkKey: '<PLACE-YOUR-SDK-KEY-HERE>',
    options: ConfigCatOptions(
        pollingMode: PollingMode.manualPoll(),
    )
);

client.forceRefresh();

```

> `getValue()` returns `defaultValue` if the cache is empty. Call `forceRefresh()` to update the cache.

## Hooks[​](#hooks "Direct link to Hooks")

The SDK provides several hooks (events), by means of which you can get notified of its actions. You can subscribe to the following events emitted by the *ConfigCat* client:

* `onClientReady()`: This event is emitted when the client reaches the ready state, i.e. completes initialization.

  * If Lazy Loading or Manual Polling is used, it's considered ready right after instantiation.

  * If Auto Polling is used, the ready state is reached as soon as

    <!-- -->

    * the initial sync with the external cache yields up-to-date config data,
    * otherwise, if the client is online (i.e. HTTP requests are allowed), the first config fetch operation completes (regardless of success or failure),
    * or the time specified via Auto Polling's `maxInitWaitTime` option has passed.

  Reaching the ready state usually means the client is ready to evaluate feature flags and settings. However, please note that this is not guaranteed. In case of initialization failure or timeout, the internal cache may be empty or expired even after the ready state is reported. Alternatively, in Auto Polling mode, you can wait for the first `onConfigChanged` event to be notified when the internal cache is actually populated with config data.

* `onConfigChanged(Map<string, Setting>)`: This event is emitted first when the client's internal cache gets populated. Afterwards, it is emitted again each time the internally cached config is updated to a newer version, either as a result of synchronization with the external cache, or as a result of fetching a newer version from the ConfigCat CDN.

* `onFlagEvaluated(EvaluationDetails)`: This event is emitted each time the client evaluates a feature flag or setting. The event provides the same evaluation details that you would get from [`getValueDetails()`](#anatomy-of-getvaluedetails).

* `onError(String)`: This event is emitted when an error occurs within the client.

You can subscribe to these events either on SDK initialization:

```dart
final client = ConfigCatClient.get(
    sdkKey: '#YOUR-SDK-KEY#',
    options: ConfigCatOptions(
        pollingMode: PollingMode.manualPoll(),
        hooks: Hooks(
            onFlagEvaluated: (details) => /* handle the event */
        )
    )
);

```

or with the `hooks` property of the ConfigCat client:

```dart
client.hooks.addOnFlagEvaluated((details) => /* handle the event */);

```

## Online / Offline mode[​](#online--offline-mode "Direct link to Online / Offline mode")

In cases when you'd want to prevent the SDK from making HTTP calls, you can put it in offline mode:

```dart
client.setOffline();

```

In offline mode, the SDK won't initiate HTTP requests and will work only from its cache.

To put the SDK back in online mode, you can do the following:

```dart
client.setOnline();

```

> With `client.isOffline()` you can check whether the SDK is in offline mode.

## Flag Overrides[​](#flag-overrides "Direct link to Flag Overrides")

With flag overrides you can overwrite the feature flags & settings downloaded from the ConfigCat CDN with local values. Moreover, you can specify how the overrides should apply over the downloaded values. The following 3 behaviours are supported:

* **Local only** (`OverrideBehaviour.localOnly`): When evaluating values, the SDK will not use feature flags & settings from the ConfigCat CDN, but it will use all feature flags & settings that are loaded from local-override sources.

* **Local over remote** (`OverrideBehaviour.localOverRemote`): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the local-override version will take precedence.

* **Remote over local** (`OverrideBehaviour.remoteOverLocal`): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the downloaded version will take precedence.

You can set up the SDK to load your feature flag & setting overrides from a `Map<String, Object>`.

```dart
final client = ConfigCatClient.get(
    sdkKey: 'localhost',
    options: ConfigCatOptions(
        override: FlagOverrides(
            dataSource: OverrideDataSource.map({
                'enabledFeature': true,
                'disabledFeature': false,
                'intSetting': 5,
                'doubleSetting': 3.14,
                'stringSetting': 'test',
            }),
            behaviour: OverrideBehaviour.localOnly
        )
    )
);

```

## `getAllKeys()`[​](#getallkeys "Direct link to getallkeys")

You can get the keys for all available feature flags and settings by calling the `getAllKeys()` method.

```dart
final client = ConfigCatClient.get(sdkKey: '#YOUR-SDK-KEY#');
final keys = await client.getAllKeys();

```

## `getAllValues()`[​](#getallvalues "Direct link to getallvalues")

Evaluates and returns the values of all feature flags and settings. Passing a User Object is optional.

```dart
final client = ConfigCatClient.get(sdkKey: '#YOUR-SDK-KEY#');
final settingValues = await client.getAllValues();

// invoke with User Object
final user = ConfigCatUser(identifier: '#UNIQUE-USER-IDENTIFIER#');
final settingValuesTargeting = await client.getAllValues(user);

```

## Cache[​](#cache "Direct link to Cache")

The SDK caches the downloaded `config JSON` only in memory by default. In case you have a Flutter application, you can use the [Flutter Preferences Cache](https://github.com/configcat/flutter-preferences-cache) for caching.<br /><!-- -->It's based on the [shared\_preferences](https://pub.dev/packages/shared_preferences) package that uses the following storage locations by platform:

* **Web**: Browser `LocalStorage`.
* **iOS / macOS**: `NSUserDefaults`.
* **Android**: `SharedPreferences`.
* **Linux**: File in `XDG_DATA_HOME` directory.
* **Windows**: File in roaming `AppData` directory.

```dart
final client = ConfigCatClient.get(
    sdkKey: '#YOUR-SDK-KEY#',
    options: ConfigCatOptions(cache: ConfigCatPreferencesCache()));

```

### Custom Cache[​](#custom-cache "Direct link to Custom Cache")

You have the option to inject your custom cache implementation into the client. All you have to do is to inherit from the `ConfigCatCache` abstract class:

```dart
class MyCustomCache extends ConfigCatCache {
    @override
    Future<String> read(String key) {
        // here you have to return with the cached value
    }

    @override
    Future<void> write(String key, String value) {
        // here you have to store the new value in the cache
    }
}

```

Then use your custom cache implementation:

```dart
final client = ConfigCatClient.get(
    sdkKey: '<PLACE-YOUR-SDK-KEY-HERE>',
    options: ConfigCatOptions(cache: MyCustomCache()));

```

info

The Dart (Flutter) SDK supports *shared caching*. You can read more about this feature and the required minimum SDK versions [here](https://configcat.com/docs/advanced/caching.md#shared-cache).

## HttpClient[​](#httpclient "Direct link to HttpClient")

The ConfigCat SDK internally uses a [Dio HTTP client](https://github.com/flutterchina/dio) instance to download the latest config JSON over HTTP. You have the option to customize the internal HTTP client.

### HTTP Timeout[​](#http-timeout "Direct link to HTTP Timeout")

You can set the maximum wait time for a ConfigCat HTTP response by using Dio's timeouts.

```dart
final client = ConfigCatClient.get(
    sdkKey: '<PLACE-YOUR-SDK-KEY-HERE>',
    options: ConfigCatOptions(
        connectTimeout: Duration(seconds: 10), // timeout for establishing a HTTP connection with the server
        sendTimeout: Duration(seconds: 10), // timeout for sending a HTTP request to the server
        receiveTimeout: Duration(seconds: 10), // timeout for reading the server's HTTP response
    )
);

```

Default timeout values:

* `connectTimeout`: 10 seconds
* `sendTimeout`: 20 seconds
* `receiveTimeout`: 20 seconds

### HTTP Proxy[​](#http-proxy "Direct link to HTTP Proxy")

If your application runs behind a proxy you can do the following:

```dart
import 'package:dio/adapter.dart';

(client.httpClient.httpClientAdapter as DefaultHttpClientAdapter)
    .onHttpClientCreate = (client) {
        client.findProxy = (uri) {
            return 'PROXY proxyHost:proxyPort';
        };
    };

```

## Force refresh[​](#force-refresh "Direct link to Force refresh")

Call the `forceRefresh()` method on the client to download the latest config JSON and update the cache.

## Logging[​](#logging "Direct link to Logging")

The default logger used by the SDK simply outputs the log messages with `print()`, but you can override it with your implementation via the `logger` client option. The custom implementation must satisfy the [Logger](https://github.com/configcat/dart-sdk/blob/main/lib/src/log/logger.dart) abstract class.

```dart
class MyCustomLogger implements Logger {
  @override
  void close() {
    // close the logger
  }

  @override
  void debug(message, [error, StackTrace? stackTrace]) {
    // write the debug logs
  }

  @override
  void error(message, [error, StackTrace? stackTrace]) {
    // write the error logs
  }

  @override
  void info(message, [error, StackTrace? stackTrace]) {
    // write the info logs
  }

  @override
  void warning(message, [error, StackTrace? stackTrace]) {
    // write the warning logs
  }
}

```

Then you can use your custom logger implementation at the SDK's initialization:

```dart
final client = ConfigCatClient.get(
    sdkKey: '<PLACE-YOUR-SDK-KEY-HERE>',
    options: ConfigCatOptions(
        logger: ConfigCatLogger(internalLogger: MyCustomLogger()),
    )
);

```

You can change the verbosity of the logs by passing a `LogLevel` parameter to the `logger` option.

```dart
final client = ConfigCatClient.get(
    sdkKey: '<PLACE-YOUR-SDK-KEY-HERE>',
    options: ConfigCatOptions(
        logger: ConfigCatLogger(level: LogLevel.info),
    )
);

```

Available log levels:

| Level     | Description                                                                             |
| --------- | --------------------------------------------------------------------------------------- |
| `nothing` | Turn the logging off.                                                                   |
| `error`   | Only error level events are logged.                                                     |
| `warning` | Default. Errors and Warnings are logged.                                                |
| `info`    | Errors, Warnings and feature flag evaluation is logged.                                 |
| `debug`   | All of the above plus debug info is logged. Debug logs can be different for other SDKs. |

Info level logging helps to inspect how a feature flag was evaluated:

```bash
[INFO] 2022-01-20T18:22:02.313703 ConfigCat - [5000] Evaluating 'isPOCFeatureEnabled' for User '{"Identifier":"<SOME USERID>","Email":"configcat@example.com","Country":"US","SubscriptionType":"Pro","Role":"Admin","version":"1.0.0"}'
  Evaluating targeting rules and applying the first match if any:
  - IF User.Email CONTAINS ANY OF ['@something.com'] THEN 'False' => no match
  - IF User.Email CONTAINS ANY OF ['@example.com'] THEN 'True' => MATCH, applying rule
  Returning 'True'.

```

## Sample Apps[​](#sample-apps "Direct link to Sample Apps")

Check out our Sample Applications how they use the ConfigCat SDK

* [Console Application](https://github.com/configcat/dart-sdk/tree/main/example/lib)
* [Flutter Application](https://github.com/configcat/dart-sdk/tree/main/example/flutter)

## Guides[​](#guides "Direct link to Guides")

See [this](https://configcat.com/blog/2022/10/18/feature-flags-in-dart/) guide on how to use ConfigCat's Dart SDK.

## Look Under the Hood[​](#look-under-the-hood "Direct link to Look Under the Hood")

* [ConfigCat Dart (Flutter) SDK's repository on GitHub](https://github.com/configcat/dart-sdk)
* [ConfigCat Dart (Flutter) SDK's pub.dev page](https://pub.dev/packages/configcat_client)