Skip to content
NanoFlags
Start free

SDKs

Flutter and Dart SDK

The Dart SDK evaluates flags on the device, locally and synchronously, against a signed configuration that the edge pushes over a live WebSocket. 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.

Install

Install
flutter pub add nanoflags_flutter   # Flutter apps (re-exports nanoflags)
dart pub add nanoflags              # pure Dart
pubspec.yaml
dependencies:
  nanoflags_flutter: ^0.1.0
  # nanoflags_openfeature: ^0.1.0   # OpenFeature provider
PackageWhat it is
nanoflagsEngine port, signature verification, transports (live WebSocket, SSE, polling), the client. Dart VM, Flutter (Android, iOS, desktop), web (dart2js, Wasm).
nanoflags_flutterNanoFlagsProvider, FlagBuilder, lifecycle handling, SharedPreferencesStore. Flutter 3.27+.
nanoflags_openfeatureProvider 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)

main.dart
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

dart
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 accessors

Accessors 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

MemberWhat it does
ready({timeout})Completes once a configuration is loaded, or the first attempt finished without one. Never fails.
statusnotReady, ready, stale (usable, not known to be current).
revision · transport · contextState. transport is live, stream, poll or paused.
bool / string / number / jsonVariationTyped values.
…VariationDetailAn EvaluationDetail: value, reason, ruleIndex, ruleId, inRollout, bucket, revision, error, trace.
evaluate · allFlags()The raw engine result · every flag for the current context.
setContext · identify · updateContextLocal context changes (they fire changes).
updates · changes · errorsBroadcast 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

OptionDefault
baseUrlhttps://edge.nanoflags.io
serviceunknown; shown where the dashboard lists which revision each service runs.
pollInterval60 s while no socket is open; Duration.zero disables polling.
livePollInterval5 min safety poll while the socket is healthy.
streaming · livetrue · true: the /v1/live WebSocket first, SSE when it cannot be opened.
bootstrapNone. A bundle (map or JSON text) shipped with the app, used until something newer arrives.
storeNone (Flutter: SharedPreferencesStore). Persistence of the last verified bundle.
eventsSample 10 %, flush 30 s, report 5 min. EventsOptions.off() disables telemetry.
verifyOfficial edge: embedded keys, unsigned bundles refused.
dataSaver · dataSaverPollIntervalfalse · 15 min.

Live updates and lifecycle

  • Live (/v1/live): the key travels in the Authorization header 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 code 4004 (environment deleted): no reconnect, the last bundle is kept, status stale.
  • SSE (/v1/stream) when the socket cannot be opened, then polling with If-None-Match.
  • Background: in the hidden, paused and detached states the live connection is closed, polling stops and telemetry is flushed once. On resumed the 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 (status stale until 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's ConnectivityManager.isActiveNetworkMetered, iOS's NWPath.isConstrained through 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

dart
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

  1. ArgumentError about the key. Use a browser/client key (nf_pub_…).
  2. A flag always returns its fallback. Mark it client-exposed and publish.
  3. Version solving fails for nanoflags. Until the packages are on pub.dev, add the dependency_overrides entry shown in Install.
  4. 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.
Other mobile platforms
Native SDKs exist for React Native, iOS (Swift) and Android (Kotlin), with the same engine and the same results.