Flutter SDK

View as Markdown

The Unleash Flutter SDK lets you evaluate feature flags in Flutter applications. It connects to Unleash or Unleash Edge to fetch evaluated flags for a given Unleash context.

You can use this SDK with Unleash Enterprise or Unleash Open Source.

For an overview of how Unleash SDKs work, including offline behavior, feature compatibility across SDKs, and default refresh and metrics intervals, refer to the SDK overview.

Installation

flutter pub add unleash_proxy_client_flutter

Initialization

Configure the client according to your needs. The following example provides only the required options. Refer to configuration options for the full list.

Set url to the /api/frontend endpoint of your Unleash instance or your Unleash Edge instance. Set clientKey to a frontend API token.

1import 'package:unleash_proxy_client_flutter/unleash_proxy_client_flutter.dart';
2
3final unleash = UnleashClient(
4 url: Uri.parse('https://<your-unleash-instance>/api/frontend'),
5 clientKey: '<your-client-side-token>',
6 appName: 'my-app');
7unleash.start();

Check if the SDK is ready

You should wait for the client’s ready or initialized events before you start working with it. Before it’s ready, the client might not report the correct state for your features.

1unleash.on('ready', (_) {
2 if (unleash.isEnabled('flutter.demo')) {
3 print('flutter.demo is enabled');
4 } else {
5 print('flutter.demo is disabled');
6 }
7});

The difference between the events is explained below.

Check flags

Once the client is ready, you can start checking features in your application. Use the isEnabled method to check the state of any feature you want:

1unleash.isEnabled('flutter.demo');

You can use the getVariant method to get the variant of an enabled feature that has variants. If the feature is disabled or if it has no variants, then you will get back the disabled variant

1final variant = unleash.getVariant('flutter.demo');
2
3if (variant.name == 'blue') {
4 // something with variant blue...
5}

You can also access the payload associated with the variant:

1final variant = unleash.getVariant('flutter.demo');
2final payload = variant.payload;
3
4if (payload != null) {
5 // do something with the payload
6 // print(payload "${payload.type} ${payload.value}");
7}

Unleash context

The Unleash context holds properties such as user ID, session ID, and custom fields that drive flag evaluation, including strategy targeting, constraints, and stickiness. To update and configure the Unleash context in this SDK, use the updateContext, setContextField, and setContextFields methods.

The context you set in your app will be passed along to Unleash Edge or the Frontend API as query parameters for feature evaluation.

The updateContext method will replace the entire (mutable part) of the Unleash context with the data that you pass in.

The setContextField method only acts on the property that you choose. It does not affect any other properties of the Unleash context.

The setContextFields method only acts on the properties that you choose. It does not affect any other properties of the Unleash context.

1// Used to set the context fields, shared with the Unleash Edge. This
2// method will replace the entire (mutable part) of the Unleash Context.
3unleash.updateContext(UnleashContext(userId: '1233'));
4
5// Used to update a single field on the Unleash Context.
6unleash.setContextField('userId', '4141');
7
8// Used to update multiple context fields on the Unleash Context.
9unleash.setContextFields({'userId': '4141'});

Configuration options

The Unleash SDK takes the following options:

optionrequireddefaultdescription
urlyesn/aThe Unleash Frontend API URL to connect to. E.g.: https://eu.app.unleash-hosted.com/demo/api/frontend
clientKeyyesn/aThe Frontend Token to be used
appNameyesn/aThe name of the application using this SDK. Will be used as part of the metrics sent to Unleash Edge/Frontend API. Will also be part of the Unleash Context.
refreshIntervalno30How often, in seconds, the SDK should check for updated toggle configuration. If set to 0 will disable checking for updates
disableRefreshnofalseIf set to true, the client will not check for updated toggle configuration
metricsIntervalno30How often, in seconds, the SDK should send usage metrics back to Unleash
disableMetricsnofalseSet this option to true if you want to disable usage metrics
storageProvidernoSharedPreferencesStorageProviderAllows you to inject a custom storeProvider
bootstrapnonullAllows you to bootstrap the cached feature toggle configuration.
bootstrapOverridenotrueShould the bootstrap automatically override cached data in the local-storage. Will only be used if bootstrap is not an empty array.
headerNamenoAuthorizationProvides possibility to specify custom header that is passed to Unleash / Unleash Edge with the clientKey
customHeadersno{}Additional headers to use when making HTTP requests to the Unleash. In case of name collisions with the default headers, the customHeaders value will be used.
impressionDataAllnofalseAllows you to trigger “impression” events for all getToggle and getVariant invocations. This is particularly useful for “disabled” feature flags that are not visible to frontend SDKs.
fetchernohttp.getAllows you to define your own fetcher. Can be used to add certificate pinning or additional http behavior.
posternohttp.postAllows you to define your own poster. Can be used to add certificate pinning or additional http behavior.
experimentalnonullEnabling optional experimentation. togglesStorageTTL : How long (Time To Live), in seconds, the toggles in storage are considered valid and should not be fetched on start. If set to 0 will disable expiration checking and will be considered always expired.

Events

The client is also an event emitter. This means that your code can subscribe to updates from the client. This is a neat way to update your app when toggle state updates.

1unleash.on('update', (_) {
2 final myToggle = unleash.isEnabled('flutter.demo');
3 //do something useful
4});

The SDK emits the following events:

  • error - emitted when an error occurs on init, or when fetch function fails, or when fetch receives a non-ok response object. The error object is sent as payload.
  • initialized - emitted after the SDK has read local cached data in the storageProvider.
  • ready - emitted after the SDK has successfully started and performed the initial fetch towards Unleash.
  • update - emitted every time the Unleash returns a new feature toggle configuration. The SDK will emit this event as part of the initial fetch from the SDK.
Please remember that you should always register your event listeners before your call unleash.start(). If you register them after you have started the SDK you risk losing important events.

Session ID

You may provide a custom session id via the “context”. If you do not provide a sessionId this SDK will create a random session id, which will also be stored in the provided storage. By always having a consistent sessionId available ensures that even “anonymous” users will get a consistent experience when feature flags are evaluated, in combination with a gradual (percentage based) rollout.

Stop the client

You can stop the Unleash client by calling the stop method. Once the client has been stopped, it will no longer check for updates or send metrics to the server.

A stopped client can be restarted.

1unleash.stop();

Bootstrap

You can bootstrap the SDK with your own flag configuration to avoid an API call on startup. Add a bootstrap attribute when you create a new UnleashClient. There’s also a bootstrapOverride attribute which by default is true.

1final unleash = UnleashClient(
2 url: Uri.parse('https://app.unleash-hosted.com/demo/api/flutter'),
3 clientKey: 'token-123',
4 appName: 'my-app',
5 bootstrapOverride: false,
6 bootstrap: {
7 'demoApp.step4': ToggleConfig(
8 enabled: true,
9 impressionData: false,
10 variant: Variant(enabled: true, name: 'blue'))
11});
  • If bootstrapOverride is true (by default), any local cached data will be overridden with the bootstrap specified.
  • If bootstrapOverride is false any local cached data will not be overridden unless the local cache is empty.

Manage your own refresh mechanism

You can opt out of the Unleash feature flag auto-refresh mechanism and metrics update by settings the refreshInterval and/or metricsInterval options to 0. In this case, it becomes your responsibility to call updateToggles and/or sendMetrics methods.

Skip fetching flags on start

This is an experimental feature and may change in future releases.

If you run multiple clients that share the same storage provider (for example, the default SharedPreferencesStorageProvider), you can skip fetching flags on start for all but one client. Set togglesStorageTTL to a non-zero value to reuse cached flags that are still within the TTL window.

In the following example, flags in storage are considered valid for 60 seconds and are not fetched on start if they already exist. Set togglesStorageTTL to a value greater than refreshInterval.

1final anotherUnleash = UnleashClient(
2 // ...
3 experimental: const ExperimentalConfig(togglesStorageTTL: 60)
4);