SDKs
Flutter and Dart SDK
nanoflags_flutter adds a provider widget, FlagBuilder, app-lifecycle handling and on-device persistence. It runs on Flutter for Android, iOS, desktop and the web, and in the Dart VM.On this page
Install
flutter pub add nanoflags_flutter # Flutter apps (re-exports nanoflags)
dart pub add nanoflags # pure Dartdependencies:
nanoflags_flutter: ^0.1.0
# nanoflags_openfeature: ^0.1.0 # OpenFeature provider| Package | What it is |
|---|---|
nanoflags | Engine port, signature verification, transports (live WebSocket, SSE, polling), the client. Dart VM, Flutter (Android, iOS, desktop), web (dart2js, Wasm). |
nanoflags_flutter | NanoFlagsProvider, FlagBuilder, lifecycle handling, SharedPreferencesStore. Flutter 3.27+. |
nanoflags_openfeature | Provider for the official OpenFeature Dart SDK (openfeature_dart_client_sdk). Dart 3.10+. |
- The engine is tested against the shared parity fixtures (21,998 cases, plus the Go port's corner cases) in the Dart VM and compiled to JavaScript, with results identical to every other NanoFlags SDK.
- Apache-2.0. Source in the nanoflags-sdk repository.
Client keys
Apps ship to users, so the SDK takes browser/client keys (nf_pub_…) only. They receive the client view: client-exposed flags and only the segments those flags reference. A server key (nf_srv_…) is refused with an ArgumentError.
Quickstart (Flutter)
import 'package:flutter/material.dart';
import 'package:nanoflags_flutter/nanoflags_flutter.dart';
void main() {
runApp(NanoFlagsProvider.create(
options: const NanoFlagsOptions(
sdkKey: 'nf_pub_…', // a client key; server keys are refused
service: 'ios-app',
context: {'key': 'anonymous-device-id'},
),
child: const MyApp(),
));
}
class CheckoutButton extends StatelessWidget {
const CheckoutButton({super.key});
@override
Widget build(BuildContext context) => FlagBuilder<bool>(
flagKey: 'new-checkout',
fallback: false,
builder: (context, enabled) => enabled ? const NewCheckout() : const OldCheckout(),
);
}
// After sign-in (local, no network round trip):
NanoFlagsProvider.read(context)!.identify(user.id, {'plan': user.plan});
// Anywhere in build methods (rebuilds on changes):
final accent = context.nanoFlags.stringVariation('accent', 'blue');NanoFlagsProvider.create(options: …) owns its client and persists the last verified bundle with SharedPreferencesStore unless options.store is set. NanoFlagsProvider(client: …) provides a client you created yourself. Pass handleLifecycle: false to call pause() and resume() yourself. A runnable example with a device test is in nanoflags_flutter/example.
Dart client
import 'package:nanoflags/nanoflags.dart';
final flags = NanoFlagsClient(const NanoFlagsOptions(
sdkKey: 'nf_pub_…',
service: 'android-app',
context: {'key': 'user-42', 'plan': 'pro', 'country': 'DE'},
));
await flags.ready(timeout: const Duration(seconds: 5)); // never fails
if (flags.boolVariation('new-checkout', false)) {
// …
}
final accent = flags.stringVariation('accent', 'blue');
final limit = flags.numberVariation('upload-limit', 10);
final config = flags.jsonVariation('onboarding', const {'steps': 3});
final d = flags.boolVariationDetail('new-checkout', false);
print('${d.value} because ${d.reason} (rule ${d.ruleId}, r${d.revision})');
final all = flags.allFlags(); // no telemetry recorded
flags.identify('user-43', {'plan': 'free'}); // local: no network round trip
flags.updateContext({'country': 'FR'}); // merge; a null value removes an attribute
flags.updates.listen((e) => print('now r${e.revision} via ${e.transport.name}'));
flags.changes.listen((_) => rebuild()); // configuration, status or context changed
flags.errors.listen((e) => log(e)); // background problems; never thrown from accessorsAccessors never perform I/O and never throw: without a configuration, for a missing flag or for a value of another type they return the fallback. The context: argument of every accessor merges attributes over the current context for that one call.
API
| Member | What it does |
|---|---|
ready({timeout}) | Completes once a configuration is loaded, or the first attempt finished without one. Never fails. |
status | notReady, ready, stale (usable, not known to be current). |
revision · transport · context | State. transport is live, stream, poll or paused. |
bool / string / number / jsonVariation | Typed values. |
…VariationDetail | An EvaluationDetail: value, reason, ruleIndex, ruleId, inRollout, bucket, revision, error, trace. |
evaluate · allFlags() | The raw engine result · every flag for the current context. |
setContext · identify · updateContext | Local context changes (they fire changes). |
updates · changes · errors | Broadcast streams. |
refresh() · pause() · resume() | Revalidate now · background · foreground (the Flutter package calls these for you). |
setDataSaver(bool) | Metered or low-data networks: no socket, no stream, polling every 15 minutes, telemetry held back. |
flush() · close() | Telemetry · shutdown. |
Options
| Option | Default |
|---|---|
baseUrl | https://edge.nanoflags.io |
service | unknown; shown where the dashboard lists which revision each service runs. |
pollInterval | 60 s while no socket is open; Duration.zero disables polling. |
livePollInterval | 5 min safety poll while the socket is healthy. |
streaming · live | true · true: the /v1/live WebSocket first, SSE when it cannot be opened. |
bootstrap | None. A bundle (map or JSON text) shipped with the app, used until something newer arrives. |
store | None (Flutter: SharedPreferencesStore). Persistence of the last verified bundle. |
events | Sample 10 %, flush 30 s, report 5 min. EventsOptions.off() disables telemetry. |
verify | Official edge: embedded keys, unsigned bundles refused. |
dataSaver · dataSaverPollInterval | false · 15 min. |
Live updates and lifecycle
- Live (
/v1/live): the key travels in theAuthorizationheader on native platforms and in the subprotocol list on the web, never in the URL. The edge pushes the signed bundle itself. Ping about every 30 seconds, the socket is replaced about every 50 minutes, and reconnects use jittered backoff (1 s · 2ⁿ, up to 5 minutes). Close code4004(environment deleted): no reconnect, the last bundle is kept, statusstale. - SSE (
/v1/stream) when the socket cannot be opened, then polling withIf-None-Match. - Background: in the
hidden,pausedanddetachedstates the live connection is closed, polling stops and telemetry is flushed once. Onresumedthe client reconnects and revalidates.inactive(dialogs, app switcher, calls) keeps the connection. - Offline-first: with a
store, the last verified bundle is available at startup (statusstaleuntil the edge confirms it). It is verified again when loaded. - Metered networks: Flutter has no portable metered-network signal, so the app decides when to call
setDataSaver(true)(for example from Android'sConnectivityManager.isActiveNetworkMetered, iOS'sNWPath.isConstrainedthrough a platform channel, or a user setting).
Signature verification
Every bundle is verified before it replaces the current one: Ed25519 over the canonical signed string, computed from the exact bytes the edge signed. With the official edge the SDK uses the embedded key list and refuses unsigned bundles; a bundle naming an unknown key id loads GET /v1/keys once (at most once a minute). Tampered, unsigned, wrong-environment or newer-engine bundles are refused: the previous configuration stays and an error is emitted. For other edges pass VerifyOptions(publicKeys: […]). See Security.
OpenFeature provider
import 'package:nanoflags/nanoflags.dart';
import 'package:nanoflags_openfeature/nanoflags_openfeature.dart';
import 'package:openfeature_dart_client_sdk/openfeature_dart_client_sdk.dart';
final provider = NanoFlagsOpenFeatureProvider(const NanoFlagsOptions(sdkKey: 'nf_pub_…', service: 'android-app'));
await OpenFeatureAPI.instance.setProviderAndWait(provider);
await OpenFeatureAPI.instance.setEvaluationContextAndWait(
EvaluationContext(targetingKey: 'user-42', attributes: {'plan': 'pro'}),
);
final enabled = OpenFeatureAPI.instance.getClient().getBooleanValue('new-checkout', false);Or wrap an existing client with NanoFlagsOpenFeatureProvider.withClient(client). The mapping is the same as in the other NanoFlags providers: the targeting key becomes key; reasons DISABLED, DEFAULT, TARGETING_MATCH, SPLIT; the variant is the rule id; events ready, stale, error, configurationChanged and contextChanged.
Telemetry
Like the other SDKs: a service report (sdk: "dart/0.1.0" and the revision) and sampled evaluation events whose context carries attribute names and types only, never values, limited to the attributes the flag's rules use. EventsOptions.off() opts out.
Troubleshooting
ArgumentErrorabout the key. Use a browser/client key (nf_pub_…).- A flag always returns its fallback. Mark it client-exposed and publish.
- Version solving fails for
nanoflags. Until the packages are on pub.dev, add thedependency_overridesentry shown in Install. - The value does not change in the background. That is intended: the connection is paused in the background and the client catches up on
resumed.