OpenFeature Providers

OpenFeature Flutter Provider

ConfigDirector Provider for the OpenFeature Dart client SDK in Flutter applications

Introduction

The OpenFeature Flutter Provider is intended to be used in combination with the OpenFeature Dart client SDK, openfeature_dart_client_sdk, in Flutter applications on any of the platforms Flutter targets. The provider wraps the ConfigDirector Flutter SDK.

The OpenFeature Dart client SDK is the static-context SDK for client applications: one evaluation context is set for the whole application, and every flag is evaluated against it. It is distinct from the OpenFeature Dart server SDK, which the provider does not work with.

The OpenFeature Dart client SDK is in beta, so the provider is published as a beta alongside it: a new provider beta for each OpenFeature beta it is built against, until both go stable. Both packages have to be asked for by version, as shown below, because pub never picks a pre-release on its own.

The minimum supported version of Flutter is 3.44.2, which is the first to ship the Dart 3.12.2 the OpenFeature Dart client SDK requires.

Config evaluation is synchronous and reads config state the provider already holds in memory, which is what makes it safe to call from build. Telemetry about those evaluations is aggregated and reported off the main isolate, so evaluating a config never waits on the network.

Installation

The provider can be installed from pub.dev: https://pub.dev/packages/configdirector_openfeature_flutter_provider

The ConfigDirector Flutter SDK is included as a transitive dependency. The OpenFeature Dart client SDK is added alongside the provider, since that is the package your application evaluates flags with.

flutter pub add configdirector_openfeature_flutter_provider:^0.1.0-beta.1 openfeature_dart_client_sdk:^0.0.1-beta.1

Configure and initialize the client

  1. Create an instance of the provider providing your client SDK key. You can retrieve a client SDK key for each environment under SDK Keys in the dashboard's navigation panel.
  2. Set the evaluation context, then set the OpenFeature provider.
  3. Get a client instance from OpenFeature.
config_director_setup.dart (Register the provider)
import 'package:configdirector_openfeature_flutter_provider/configdirector_openfeature_flutter_provider.dart';
import 'package:openfeature_dart_client_sdk/openfeature_dart_client_sdk.dart';

// Creating the provider makes no network calls. It throws only when the SDK key is
// blank or an option holds an unusable value.
final provider = ConfigDirectorProvider(clientSdkKey: 'YOUR-CLIENT-SDK-KEY');

// The context the provider connects with. Set it before the provider.
await OpenFeatureAPI.instance.setEvaluationContextAndWait(
  EvaluationContext(targetingKey: 'user-123'),
);

// Connects and waits until config values are received. It throws an
// OpenFeatureException on a timeout, after which the provider keeps trying to
// connect in the background.
await OpenFeatureAPI.instance.setProviderAndWait(provider);

final client = OpenFeatureAPI.instance.getClient();

The constructor throws a ConfigDirectorValidationException in only two cases, both of which are programming errors rather than runtime conditions: a blank client SDK key, and an option that cannot be used, such as a timeout that is not positive or a base URL that is not absolute. Connection failures are not thrown from it.

setProviderAndWait returns once the initial config state arrives. When the configured timeout elapses first, the provider reports an error and setProviderAndWait throws an OpenFeatureException; the OpenFeature SDK reports the error status, and the provider keeps connecting in the background, then emits ready as soon as config state arrives. Until then, flags resolve to their default values with the providerNotReady error code.

Most applications register the provider once during startup and let it live for the lifetime of the app. That usually means doing so from the State of the root widget, with setProvider, which returns at once and initializes in the background:

app.dart
import 'package:configdirector_openfeature_flutter_provider/configdirector_openfeature_flutter_provider.dart';
import 'package:flutter/material.dart';
import 'package:openfeature_dart_client_sdk/openfeature_dart_client_sdk.dart';

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    OpenFeatureAPI.instance.setEvaluationContext(
      EvaluationContext(targetingKey: 'user-123'),
    );
    OpenFeatureAPI.instance.setProvider(
      ConfigDirectorProvider(clientSdkKey: 'YOUR-CLIENT-SDK-KEY'),
    );
  }

  @override
  void dispose() {
    unawaited(OpenFeatureAPI.instance.shutdown());
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => MaterialApp(home: const HomePage());
}

Flag evaluations are possible once the client's providerStatus is ProviderStatus.ready; the client's event handlers are how a widget follows it. See reading configs in widgets.

The underlying SDK follows the app lifecycle through WidgetsBinding so it can release its network connection while the app is backgrounded. If you create the provider before runApp, call WidgetsFlutterBinding.ensureInitialized() first. See the connection options of the Flutter SDK to manage that yourself instead.

Additional configuration options

Additional configuration options can be passed into the provider as ConfigDirectorClientOptions in the optional options argument of the constructor. They are the Flutter SDK's own options, and the provider exports the types they are built from, so configuring it needs no second import.

For example, the metadata can be provided like this:

config_director_setup.dart
import 'package:configdirector_openfeature_flutter_provider/configdirector_openfeature_flutter_provider.dart';

final provider = ConfigDirectorProvider(
  clientSdkKey: 'YOUR-CLIENT-SDK-KEY',
  options: const ConfigDirectorClientOptions(
    metadata: ConfigDirectorMetaContext(
      appName: 'YOUR-APP-NAME',
      appVersion: '1.0.2',
    ),
  ),
);

The provider accepts the same metadata, connection and logger options as the Flutter SDK client, refer to the additional configuration options section of the Flutter SDK for a full list.

Shut down

Shutting OpenFeature down, or replacing the provider, shuts the provider down, which closes its connection and reports any pending telemetry:

app.dart
await OpenFeatureAPI.instance.shutdown();

An instance serves a single registration. After it has been shut down, create a new one rather than registering it again.

Most applications never need to do this — the provider lives as long as the app. Shut it down when an application wants the connection gone before that, on sign-out for instance.

Retrieve config values

To retrieve config values, use the OpenFeature client:

main.dart
final booleanValue = client.getBooleanValue('my-config-key', false);

final stringValue = client.getStringValue('my-string-config-key', 'Default');

Each OpenFeature getter maps to a ConfigDirector config type:

OpenFeature getterConfigDirector config value
getBooleanValueBoolean
getStringValueString or enum
getIntegerValue, getDoubleValueNumber
getStructureValueJSON object

getIntegerValue takes and returns an int; a value written as a decimal is truncated. Every config can be read with getStringValue, including a JSON config's raw document, which is also how to read a JSON config whose document is an array: the OpenFeature Dart client SDK has no list getter, so getStructureValue reads a JSON object only.

main.dart
final settings = client.getStructureValue('my-json-config-key', const {});
final theme = settings['theme'] as String?;

For additional information regarding the OpenFeature client refer to the OpenFeature Dart client SDK documentation.

Evaluation details

The detailed getters of the OpenFeature client, such as getBooleanDetails, report why an evaluation produced the value that it did:

OutcomeReasonError code
A value was foundTARGETING_MATCH
The config carries no valueDEFAULT
The config key is unknownERRORflagNotFound
No config state has arrived yetERRORproviderNotReady
The value does not match the requested typeERRORtypeMismatch

When a value was found, the variant is ConfigDirector's identifier for that value. In every other case the default value is returned.

main.dart
final details = client.getBooleanDetails('my-config-key', false);
debugPrint('my-config-key is ${details.value} because ${details.reason} (variant ${details.variant})');

Reading configs in widgets

The getters are synchronous and make no network calls, so they are safe to call directly from build. That gives you the current value, but the widget will not rebuild on its own when the value changes.

To have a widget follow a config, rebuild it whenever the provider becomes ready or reports a configuration change. The client's addHandler registers a handler per event type and returns a subscription to cancel when the widget goes away:

dark_mode_toggle.dart
import 'package:flutter/material.dart';
import 'package:openfeature_dart_client_sdk/openfeature_dart_client_sdk.dart';

class DarkModeToggle extends StatefulWidget {
  const DarkModeToggle({super.key});

  @override
  State<DarkModeToggle> createState() => _DarkModeToggleState();
}

class _DarkModeToggleState extends State<DarkModeToggle> {
  final OpenFeatureClient _client = OpenFeatureAPI.instance.getClient();
  final List<ProviderEventSubscription> _subscriptions = [];

  @override
  void initState() {
    super.initState();
    // Rebuild once config state arrives, after every configuration change, and
    // once a new context has taken effect.
    for (final type in const [
      ProviderEventType.ready,
      ProviderEventType.configurationChanged,
      ProviderEventType.contextChanged,
    ]) {
      _subscriptions.add(_client.addHandler(type, (_) => setState(() {})));
    }
  }

  @override
  void dispose() {
    for (final subscription in _subscriptions) {
      subscription.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final darkMode = _client.getBooleanValue('dark-mode', false);
    return Switch(value: darkMode, onChanged: null);
  }
}

Until providerStatus is ProviderStatus.ready, the read returns the default value, which is a good moment to show a loading state rather than flashing the in-code default on a slow connection.

Update the user context

main.dart
import 'package:openfeature_dart_client_sdk/openfeature_dart_client_sdk.dart';

await OpenFeatureAPI.instance.setEvaluationContextAndWait(
  EvaluationContext(
    targetingKey: '12345', // In OpenFeature, the targeting key represents the context's user ID
    attributes: {
      'name': 'Example User',
      // Any arbitrary traits which can be referenced in targeting rules
      'traits': {'region': 'North America'},
    },
  ),
);

The evaluation context maps onto the ConfigDirector user context as follows:

OpenFeature evaluation contextConfigDirector user context
The targeting key, or otherwise an id attributeid
The name attributename
The traits structure attributetraits
The boolean anonymous attributeanonymous

Any other attribute is ignored. Put the values your targeting rules depend on inside traits. Traits are sent as JSON; a DateTime inside them is sent as an ISO 8601 string in UTC.

In client SDKs (browser and mobile), updating the user context re-establishes a new connection to ConfigDirector servers with the new context. While the new connection is in flight, the OpenFeature SDK reports the reconciling status and config values continue to evaluate to the currently cached values from the prior user context.
Awaiting setEvaluationContextAndWait will wait until the new config values are downloaded or the connection times out. In the case of a timeout, it throws an OpenFeatureException, the provider reports the error status and continues to attempt to connect with the new context in the background, then emits ready once it succeeds.

setEvaluationContext, without the wait, returns at once and reconciles in the background; handle the contextChanged event to know when the new values are in effect.

For additional information regarding the OpenFeature client refer to the OpenFeature Dart client SDK documentation.

Events

The provider publishes its events through the OpenFeature API and clients, one handler per event type. It emits configurationChanged whenever configs are updated on the dashboard or via the admin API, carrying the keys of the configs in the update:

config_director_setup.dart
import 'package:openfeature_dart_client_sdk/openfeature_dart_client_sdk.dart';

OpenFeatureAPI.instance.addHandler(ProviderEventType.configurationChanged, (details) {
  debugPrint('Configs updated: ${details.flagsChanged}');
});

OpenFeatureAPI.instance.addHandler(ProviderEventType.error, (details) {
  debugPrint('OpenFeature provider error: ${details.message}');
});

It emits ready when config state arrives after initialization or a context change has already timed out, which moves the status from error back to ready.