datadog_flags provides the Datadog OpenFeature provider for Dart and Flutter.
The provider fetches precomputed assignments, evaluates flags locally, and sends
Datadog exposure and evaluation telemetry. It does not use the native iOS or
Android Flags SDKs.
Use OpenFeature as the application API. The legacy Datadog evaluation API is deprecated and is scheduled for removal in the next major version.
The SDK automatically supports assignment responses with obfuscated flag keys. Applications continue to evaluate flags with their original keys. Flag values and telemetry identifiers do not change.
This integration requires Dart 3.10 or later and the published
openfeature_dart_client_sdk: ^0.0.1 package.
import 'package:datadog_flags/datadog_flags.dart';
import 'package:openfeature_dart_client_sdk/openfeature_dart_client_sdk.dart';
final api = OpenFeatureAPI.instance;
await api.setEvaluationContextAndWait(
EvaluationContext(
targetingKey: 'user-123',
attributes: {'plan': 'pro'},
),
);
final provider = DatadogProvider.fromConfiguration(
DatadogFlagsConfiguration(
datadogConfig: DatadogFlagsConfig(
clientToken: '<CLIENT_TOKEN>',
env: 'production',
site: DatadogFlagsSite.us1,
),
),
);
final client = api.getClient();
client.addHandler(ProviderEventType.ready, (_) {
// Reevaluate flags after initial readiness or recovery.
});
try {
await api.setProviderAndWait(provider);
} on OpenFeatureException {
// Evaluations return defaults until initial assignments become available.
}
final enabled = client.getBooleanValue('checkout.enabled', false);
final details = client.getStringDetails('checkout.copy', 'Continue');Evaluations are synchronous. OpenFeature handles hooks, events, defaults,
provider registration, and context reconciliation. Use getBooleanValue,
getStringValue, getIntegerValue, getDoubleValue, or getStructureValue.
Each method also has a corresponding get...Details method.
Structure evaluations accept JSON objects (Map<String, Object?>). A list or
scalar assignment returns the default with ErrorCode.typeMismatch. Failed
evaluations do not emit exposures. Successful structure values are immutable.
Details include the variant, reason, error code, and provider metadata.
The provider supplies allocationKey, doLog, and variationType, available
through DatadogProvider.allocationKeyMetadata and doLogMetadata. The
provider name is datadog. Metadata keys that start with __dd_ are internal
and can change, except the split feature keys that start with __dd_feature.
(see Exposures in your own data store).
await api.setEvaluationContextAndWait(
EvaluationContext(targetingKey: 'another-user'),
);
await provider.refresh();
await api.setEvaluationContextAndWait(EvaluationContext.empty); // Sign out.
await api.shutdown();Each provider instance owns one OpenFeature domain. For a named domain, register
with setProviderForDomainAndWait(domain, provider) and use getClient(domain).
The provider uses the domain name as its Datadog client name, or default for
the default domain.
By default, when only targeting attributes change, evaluations retain the previous assignments while loading or after failure. When the targeting key changes, including sign-out, evaluations return application defaults until assignments for the new key load. A targeting-key change cancels the previous key's pending load. A missing targeting key and an empty key identify the same subject. If reconciliation fails, OpenFeature retains the previous active context. The provider discards late results from that failed reconciliation.
Use strictContextSwitchingAttribute from package:datadog_flags/datadog_flags.dart
to use downloaded assignments only while both the targeting key and targeting
attributes match:
await api.setEvaluationContextAndWait(
EvaluationContext(
targetingKey: 'user-123',
attributes: {strictContextSwitchingAttribute: true},
),
);Strict mode returns defaults during an attribute change and after a failed fetch.
An unchanged-context refresh keeps assignments while pending, then returns defaults
if loading fails. Retries keep assignments withheld after a failure for their
context until a successful fetch. Returning to an exact retained context can reuse
its assignments when only a different context failed. The SDK removes this attribute, whatever its value,
from assignment requests, stored assignments, and telemetry. Other OpenFeature
hooks and providers still receive it.
Only the boolean value true enables strict mode.
refresh() reloads assignments for the current context. It waits for pending
initialization or context reconciliation before starting.
- After assignments have been activated, including stored assignments, a successful
refresh emits
readyfollowed byconfigurationChanged. - By default, a failed refresh emits
errorfollowed bystalewhen previous assignments remain usable. Evaluations continue to use those assignments. - In strict mode, a failed refresh emits
errorand evaluations return defaults until a successful fetch. - Before any assignments have been activated,
refresh()retries the initial context. Activation emitsready, followed bystalewhen using stored assignments. It does not emitconfigurationChanged. Failure without usable assignments emitserror.
After a failed context change, refresh() throws StateError until a later
setEvaluationContextAndWait succeeds. This also applies to same-key attribute
changes when previous assignments remain usable. Calling refresh() before
initialization or after shutdown also throws StateError.
An initialization retry replaces any pending initial assignment request. Avoid
calling refresh() from every error event: repeated retries can prevent a slow
request from completing.
Each setEvaluationContextAndWait call reloads assignments, even when the context
is unchanged. The provider does not poll automatically.
Shutdown clears active assignments, cancels pending assignment publication, and drains pending telemetry. Repeated shutdown is safe. A caller-supplied HTTP client remains owned by the caller. The provider closes its own client.
DatadogFlagsConfiguration.initializationTimeout defaults to five seconds.
The provider requires a positive value of at most 20 seconds. This leaves time
before the default OpenFeature lifecycle deadline of 30 seconds. Applications
using an isolated API with a shorter deadline must choose a smaller budget.
Missing configuration or an invalid budget produces PROVIDER_FATAL. Evaluations
return caller defaults with that error. Recovery requires a new provider with
corrected configuration. A valid budget expiring remains a recoverable error.
The provider applies this budget to initialization, each context change, and each refresh. The core budget covers cache loading, the request, decoding, state publication, and cache storage. Synchronous work can delay timer delivery. The deadline bounds the caller's wait; it does not cancel the underlying HTTP or store operation.
The provider catches the initialization timeout and reports availability through
OpenFeature events. Matching cached assignments produce stale. With no
assignments, registration fails and evaluations return defaults.
If the initial request succeeds after the deadline, the provider emits ready
and makes assignments available. The provider publishes assignments before it
writes to the cache, so a slow store cannot hide a successful response.
stale means assignments are usable but fresh assignments are unavailable. It
can indicate a pending refresh or a failed refresh.
DatadogFlagsConfig contains the client token, environment, site, and optional
application ID, service, and version. The environment is sent as dd_env.
DatadogFlagsConfiguration supports:
customFlagsEndpointandcustomFlagsHeadersfor assignment transport.httpClientfor an application-owned HTTP client.storefor aDatadogFlagsStoreimplementation.initializationTimeoutfor the lifecycle budget described above.trackExposuresandcustomExposureEndpointfor exposure telemetry. WithtrackExposures: false, the SDK sends no exposures to Datadog, but it still deduplicates exposures forExposureHook.trackEvaluations,customEvaluationEndpoint, andevaluationFlushIntervalfor evaluation telemetry. The interval must be between 1 and 60 seconds. The default is 10 seconds.dateProviderfor application-controlled timestamps.flagSelectionto load only the flags that match aFlagSelectionof tags or key patterns. Stored assignments are restored only under the same selection. After the selection the SDK sends is added, changed, or removed, clients start without stored assignments until the next successful fetch.
The store loads a FlagsData snapshot only when its context and configuration
scope match the request. The scope is a digest of the site, environment, and client
token. Snapshots without a scope are not used. After an upgrade or token rotation,
evaluations use defaults until fresh assignments arrive if no eligible snapshot exists.
Cache writes and deletes are serialized per store instance and client name.
A store operation that never completes can block later persistence operations.
Implement store operations so they always complete.
Storage adapters must preserve the complete FlagsData.toJson() result and
restore it with FlagsData.fromJson(). These methods retain the metadata needed
to evaluate obfuscated assignments.
Snapshots contain the targeting key and attributes. Context changes and shutdown
do not delete stored snapshots. A successful load for the same client name replaces
the snapshot. To remove stored data, call delete on your store with the domain
name, or default for the default domain.
OpenFeature DateTime attributes become UTC ISO-8601 strings. Non-finite numbers
become null. These conversions also apply inside structures and lists.
Assignment requests send structures and lists in targeting attributes as
JSON-encoded strings. Telemetry and stored snapshots keep them structured.
Exposure telemetry follows the assignment's logging policy. Evaluation telemetry
records successes, defaults, and errors when assignments are active. Evaluations
without active assignments return ErrorCode.providerNotReady and are not recorded.
The provider does not implement
OpenFeature track(). Do not use it in place of Datadog exposure telemetry.
The SDK writes diagnostics to the Dart developer log under the name
datadog_flags. To also print them, including in release builds, set
DatadogProvider.verbosity to the lowest level to print:
DatadogProvider.verbosity = FlagsLoggerLevel.warning;The setting applies to every datadog_flags component in the isolate. Nothing
is printed by default.
To record exposures in your own data store, add an ExposureHook:
api.addHooks([
ExposureHook((evaluation) {
if (evaluation.shouldSend) {
myQueue.add({
'flag': evaluation.flagKey,
'variant': evaluation.variant,
'allocation': evaluation.allocationKey,
'subject': evaluation.targetingKey,
'features': evaluation.features,
});
}
}),
]);The callback receives every completed evaluation from DatadogProvider:
isExposureis true for a successful evaluation of an allocation that logs exposures, repeats included.isCacheHitis true when the subject's most recent exposure to the flag had the same allocation, variant, and assignment serial ID.shouldSendis true for a new exposure. These are the exposures that the SDK sends to Datadog whentrackExposuresis on.featurescontains the features of the assignment's split that are published to hooks, such asholdout.key,holdout.assignment_group, andholdout.should_include_in_holdout_analysis.flagKey,variant,allocationKey,targetingKey, andevaluationContextdescribe the evaluation.
The callback runs synchronously during the evaluation. Keep it fast and do not
do I/O in it; queue the work instead. The SDK catches exceptions from the
callback and writes them to the Dart developer log under the name
datadog_flags. The evaluation result stays the same.
The exposure deduplication cache is in memory. After a restart, the first evaluation of each assignment is a new exposure.
The same features are also available in flag metadata under keys that start with
__dd_feature., for example __dd_feature.holdout.key. Other keys that start
with __dd_ are internal and can change.
An evaluation counts as an exposure only if the whole evaluation succeeds.
See the migration guide for deprecated APIs and their OpenFeature replacements.
For successful evaluations, details report CACHED when the installed assignments
were restored from the configured store, including an in-memory store. After a
network response replaces those assignments, details report the response reason.
See the contributing guide and package contributing guide.