• SDKS
No results for ""


Flutter SDK reference

Read time: 6 minutes
Last edited: Apr 01, 2021
This SDK is in beta

The Flutter SDK is currently in beta and undergoing active development. Elements of this SDK may change without notice. Do not use this SDK in production environments.


This reference guide documents the methods available in our Flutter SDK, and explains in detail how these methods work. If you want to dig even deeper, our SDKs are open source. To learn more, view the source on GitHub or the generated API documentation. Additionally you can clone and run a sample application that uses this SDK.

Supported platforms

The Flutter SDK supports Android API 16+ and iOS 10.0+.

Getting started

Building on top of our Getting Started guide, the following steps will get you started with using the LaunchDarkly SDK in your Flutter mobile application.

To get started, declare a dependency on the LaunchDarkly Flutter SDK.

1launchdarkly_flutter_client_sdk: ^0.1.0

Then, import the package in your application code.

1import 'package:launchdarkly_flutter_client_sdk/launchdarkly_flutter_client_sdk.dart';

After you install the SDK, initialize the single shared instance of LDClient. Specify your mobile key here. This authorizes your application to connect to LaunchDarkly and retrieve flag values for your application and environment.

The following example shows the simplest way to create the client.

1LDConfig config = LDConfigBuilder('YOUR_MOBILE_KEY').build();
2LDUser user = LDUserBuilder('user key')
3 .email('fake@example.com')
4 .build();
6await LDClient.start(config, user);
Use a mobile key

Always use a mobile key from your Environments page. Never embed a server-side SDK key into a mobile application.

Using LDClient, you can check which variation a particular user should receive for a given feature flag.

1bool showFeature = await LDClient.boolVariation(flagKey, false);
2if (showFeature) {
3 // application code to show the feature
5else {
6 // the code to run if the feature is off

Optionally, if your application will no longer use the client, it may permanently shut down the client with close. This is not generally required, but is provided to clear any resources associated with the SDK and cleanly shut down.

1await LDClient.close();

Customizing your client

You can also pass other custom parameters to the client with the configuration object:

1LDConfig ldConfig = LDConfigBuilder('YOUR_MOBILE_KEY')
2 .setConnectionTimeoutMillis(5000)
3 .setEventsFlushIntervalMillis(5000)
4 .build();

Here, we've customized the client connect and flush interval parameters. For the full set of config options check out the API documentation.


Feature flag targeting and rollouts are all determined by the user you pass to your client. In our Flutter SDK, we use a builder pattern to make it easy to construct users. Here's an example:

1LDUser user = LDUserBuilder('aa0ceb')
2 .email('fake@example.com')
3 .firstName('Jake')
4 .lastName('Fake')
5 .custom('group', LDValue.ofString('microsoft'))
6 .build();

The first argument to the builder is the user's key. In this case, we've used the hash 'aa0ceb'. The user key is the only mandatory user attribute. The key should also uniquely identify each user. You can use a primary key, an e-mail address, or a hash, as long as the same user always has the same key. We recommend using a hash if possible.

All of the other attributes (like firstName, email, and the custom attributes) are optional. The attributes you specify will automatically appear on our dashboard, meaning that you can start segmenting and targeting users with these attributes.

In addition to built-in attributes like names and e-mail addresses, you can pass us any of your own user data by passing custom attributes, like the groups attribute in the example above.

A note on types

Most of our built-in attributes (like names and e-mail addresses) expect string values. Custom attributes values can be strings, booleans (like true or false), numbers, or lists of strings, booleans or numbers. Custom attribute values in the Flutter SDK use the LDValue class to support the various underlying types for the values. If you enter a custom value on our dashboard that looks like a number or a boolean, it'll be interpreted that way. The Flutter SDK is strongly typed, so be aware of this distinction.

Custom attributes are one of the most powerful features of LaunchDarkly. They let you target users according to any data that you want to send to us, including organizations, groups, and account plans. Anything you pass to us becomes available instantly on our dashboard.

Private user attributes

Optionally, you can configure the Flutter SDK to treat some or all user attributes as private user attributes. You can use private user attributes for targeting purposes. They are removed from the user data sent back to LaunchDarkly.

In the Flutter SDK, you can define private attributes for the entire LaunchDarkly client. When you create the LDConfig object, you can call the setPrivateAttributeNames method, which which takes in a set of custom or built-in attributes as a parameter. If any user has a custom or built-in attribute named in this set, it will be removed before the user is sent to LaunchDarkly.

1Set<String> privateAttributes =
2 { 'name' // built-in attribute
3 , 'group' // custom attribute
4 };
6LDConfig ldConfig = new LDConfigBuilder()
7 .setPrivateAttributeNames(privateAttributes)
8 .build();

You can also mark attributes as private when building the user object itself by using the private versions of the builder methods to set the attributes. For example:

1LDUser user = LDUserBuilder('aa0ceb')
2 .email('fake@example.com')
3 .privateName('Jane')
4 .privateCustom('group', LDValue.ofString('microsoft'))
5 .build();

When this user is sent back to LaunchDarkly, the name and group attributes will be removed.

Anonymous users

You can also distinguish logged-in users from anonymous users in the SDK, as follows:

1LDUser user = LDUserBuilder('user key')
2 .anonymous(true)
3 .build();

We recommend using the same user key for every initialization and then replacing that with the actual user key when you know who the user is. This way LaunchDarkly counts the initialization user key only once against your MAU, instead of every time you initialize.

Anonymous users work just like regular users, except that they won't appear on your Users page in LaunchDarkly. This keeps anonymous users from polluting your Users page.

You can't search for anonymous users on your Features page, and you can't search or autocomplete by anonymous user keys. If you use the same user key for every anonymous user, you also can't use percentage rollouts or Experimentation with anonymous users.


The variation methods determine the flag value for the current user. In Flutter, there is a variation method for each type (e.g. boolVariation, stringVariation):

1bool variationResult = await LDClient.boolVariation(flagKey, false);

The variation calls take the feature flag key and a fallback value.

The fallback value is only returned if an error is encountered. For example, the fallback value is served if the feature flag key doesn't exist or the user doesn't have a key specified.

Handling flag values on initial application launch

When LDClient is initialized for the first time at app launch, users will receive the feature flag fallback values until an initial connection to LaunchDarkly is completed for the first time. Take a look at the section above on various ways to initialize the client.


The variationDetail methods (boolVariationDetail, etc.) work the same as variation, but also provide additional "reason" information about how a flag value was calculated (for instance, if the user matched a specific rule). You can examine the "reason" data programmatically, or view it with Data Export destinations, if you are capturing detailed analytics events for this flag.

To learn more, read Evaluation reasons.


The allFlags method produces a map of feature flag keys to their values for a specific user. This does not send any evaluation events to LaunchDarkly.

1Map<String, LDValue> flagValues = await LDClient.allFlags();


The track method allows you to record actions your users take in your application. In LaunchDarkly, you can tie these events to goals in A/B tests. You can also attach custom JSON data to your event by passing an extra LDValue parameter to track. Here's a simple example:

1await LDClient.track('your-goal-key', data: LDValue.objectBuilder().addBool("clicked-button", true).build());

Offline mode

In some situations, you might want to stop making remote calls to LaunchDarkly and rely on locally cached values for your feature flags for future evaluations. offline mode lets you do this easily.

1LDConfig ldConfig = LDConfigBuilder('YOUR_MOBILE_KEY')
2 .setOffline(true)
3 .build();
5await LDClient.start(ldConfig, user);
7// Or to switch an already-instantiated client to offline mode:
8await LDClient.setOnline(false);
Airplane/Flight Mode

If a user's device is in airplane/flight mode or if they are not connected to a network, LaunchDarkly will use the latest stored flag settings in memory. If there are no previously stored flag settings, then the fallback values will be used.


Internally, the LaunchDarkly SDK keeps an event buffer for track calls. These are flushed periodically in a background thread. In some situations (for example, if you're testing out the SDK in a simulator), you may want to manually call flush to request any queued events to be sent immediately. Note that this call is still non-blocking, so it will return before the events are actually sent.

1await LDClient.flush();

The flush interval is configurable. If you need to change the interval, you can do so in the configuration.

Changing the user context

If multiple users use your app on the same device, you may want to change users and have separate flag settings for each. To achieve this, the SDK will store the last 5 user contexts on a single device, with support for switching between different user contexts.

You can use the identify method to switch user contexts:

1LDUser updatedUser = LDUserBuilder('user key')
2 .email('fake2@example.com')
3 .build();
5await LDClient.identify(updatedUser);

The identify call will load any saved flag values for the new user and immediately trigger an update of the latest flags from LaunchDarkly.

Real-time updates

The SDK maintains what variations a user should receive locally in cache. The SDK evaluates flags based on what it has cached locally. To keep the local cache in sync with your flag configurations in LaunchDarkly, the SDK maintains a streaming connection to the service when in the foreground. This allows near instantaneous flag update delivery to your application. Your application can register listeners to be notified immediately when the SDK receives updated flag values so it can respond accordingly:

1LDFlagUpdatedCallback listener = (String flagKey) {
2 LDClient.boolVariation(flagKey, false).then((bool val) {
3 print('${flagKey}: ${val}');
4 });
7await LDClient.registerFeatureFlagListener('yourFlagKey', listener);

The flag key passed to your LDFlagUpdatedCallback is the key of the updated flag, allowing a single listener to be registered for multiple flags.

Similarly you can unregister listeners to disable them:

1await LDClient.unregisterFeatureFlagListener(flagKey, listener);

Additionally a listener interface is provided for cases where you would like to be notified any time the flag cache is updated. The application provides a callback that will be called with a list of flag keys that were updated whenever the SDK receives new flag data from the service. If no flag values changed, this list will be empty.

1LDFlagsReceivedCallback listener = (List<String> flagKeys) {
2 print(flagKeys.toString());
5await LDClient.registerFlagsReceivedListener(listener);
6await LDClient.unregisterFlagsReceivedListener(listener);

Monitoring SDK status

The Flutter SDK exposes some of its internal status through new APIs to allow your application to monitor the SDK's status. This is provided primarily as a mechanism for the application to determine how recently the internal flag cache has been updated with the most recent values, as well as diagnosing potential reasons for the flag cache to be out of date.

The SDK also internally stores a timestamp of the most recent successful and failed connections to LaunchDarkly, as well as information related to the most recent failed connection. The LDClient method getConnectionInformation() returns a structure allowing retrieval of these fields.

1LDConnectionInformation connectionInfo = await LDClient.getConnectionInformation();
2// The current connection state
3LDConnectionState connectionState = connectionInfo.connectionState;
4// Most recent successful flag cache update
5DateTime lastSuccess = connectionInfo.lastSuccessfulConnection;
6// Most recent unsuccessful flag cache update attempt
7DateTime lastfailure = connectionInfo.lastFailedConnection;
8// Most recent failure or null
9LDFailure ldFailure = connectionInfo.lastFailure;

For more information on the connection status fields, see the API docs.

Data collection

To learn more about data collection within this SDK and implications on submissions to the Apple App Store, read Apple App Store data collection policy.