Skip to content
FlagSwiftDocs

Flutter SDK

A Dart client and widgets.

Compare SDKs

Use this SDK in Flutter apps for iOS, Android, web and desktop, or in plain Dart. It takes a client key, so your server decides and only outcomes reach the device. Targeting lists and rollout numbers stay private. For other mobile platforms see the Swift and React Native SDKs. Options and behaviour every SDK shares are on Options and behaviour.

Not yet compiled

This package has not been analysed, compiled or run. Run flutter pub get && flutter analyze && flutter test first and expect to fix a small error or two. The pub.dev name is also a placeholder until the publishing location is decided, so install from the repository for now.

At a glance#

Install
flutter pub add flagswift
Requires
Dart 3, Flutter 3.13+
Key
Client key (fs_client_)
Evaluates
On the server, for one person
Real-time updates
No, it polls
Works offline from
Storage adapter (SharedPreferences)
Outcome analytics
Yes
Verified
Not yet compiled

Options, user context and behaviour every SDK shares are on Options and behaviour. To compare SDKs, see SDK features.

Installation#

bash
flutter pub add flagswift

It needs Dart 3 and Flutter 3.13 or newer. Import package:flagswift/flagswift_flutter.dart in an app. It adds the widgets and re-exports the client. In plain Dart, import package:flagswift/flagswift.dart instead.

Initialization#

You need a client key (fs_client_…) from the API Keys page, which is meant to ship in apps, and the address of your FlagSwift server. Never ship a server key (fs_srv_…) in an app. Create the client once and put FlagSwiftScope at the top of the widget tree.

main.dart
import 'package:flagswift/flagswift_flutter.dart';

final client = FlagSwiftClient(
  apiKey: 'fs_client_...',
  baseUrl: 'https://flags.example.com',          // required: your FlagSwift server
  user: const FlagSwiftUser(identifier: 'user-42', account: 'acme', attributes: {'plan': 'pro'}),
  fallbacks: const {'new-home': false},
  storage: const SharedPreferencesStorage(),     // offline cache across launches
);

void main() => runApp(FlagSwiftScope(client: client, child: const MyApp()));

Lifecycle is handled

FlagSwiftScope starts the client, pauses polling while the app is in the background, refreshes when it returns, and rebuilds widgets when flags change.

Plain Dart#

Without widgets, call initialize() yourself and dispose() when you are done.

dart
import 'package:flagswift/flagswift.dart';

final client = FlagSwiftClient(apiKey: 'fs_client_...', baseUrl: 'https://flags.example.com');
await client.initialize();   // waits at most initTimeout; never throws

Connection options#

apiKey and baseUrl are required, and the base URL must start with http:// or https://. Everything else has a default.

Common parameters of FlagSwiftClient
ParameterTypeDescription
apiKey*StringA client key (fs_client_...).
baseUrl*StringYour server address.
environmentString?Only for project-wide keys.
userFlagSwiftUser?The person to evaluate for. Change it later with identify.
refreshIntervalDurationHow often to check for changes. Default 30 seconds. Duration.zero turns polling off.
fallbacksMap<String, Object?>Served for unknown flags and before anything loads.
initialFlagsMap<String, ClientFlag>?Start ready with these flags, so the first frame is already correct.
storageFlagStorage?The offline cache. Use SharedPreferencesStorage in an app.
timeout, initTimeoutDurationPer request, and the longest initialize waits. Default 5 seconds each.
maxRetriesintDefault 2.
autoExposuresboolReport an exposure whenever a flag is read. Default false.
onErrorvoid Function(Object)?Called when a refresh fails. Flags stay as they were.

Check flags#

Inside a widget, context.flag returns whether a flag is on and rebuilds the widget when it changes. Feature shows or hides a block without a condition in your code.

dart
Widget build(BuildContext context) {
  if (context.flag('new-home')) return const NewHome();
  return const OldHome();
}

// Or declaratively:
Feature(flag: 'new-home', child: NewHome(), otherwise: OldHome());

Outside widgets, or when you do not want a rebuild, ask the client directly. isEnabled gives the flag, then your fallback, then the configured one, then false.

dart
final on = client.isEnabled('new-home');
final withDefault = client.isEnabled('beta-banner', fallback: true);

// context.flagswift is the client without rebuilding.
context.flagswift.isEnabled('new-home');

Check variants and values#

A flag can serve a named variant, such as a button colour or an upload limit. variant gives its key and value gives what it carries.

dart
// In build(): both rebuild when the flag changes.
final variant = context.flagVariant('checkout-layout');          // 'compact', 'wide' or null
final limit = context.flagValue<int>('upload-limit', fallback: 10);

// Match a variant declaratively.
Feature(flag: 'checkout', variant: 'compact', child: CompactCheckout());

// A custom layout.
FlagBuilder(
  flag: 'button-colour',
  builder: (context, enabled, variant) => MyButton(variant: variant),
);

// Imperative.
client.variant('button-colour');
client.value<String>('button-colour', fallback: 'blue');

Change the person#

Call identify after a login, logout or tenant switch. It switches the person and refreshes every flag.

dart
await context.flagswift.identify(const FlagSwiftUser(identifier: 'user-43'));

Offline, identify loads that person's cached flags if there are any. Otherwise the previous person's last good flags stay in place until the refresh succeeds, so they may briefly be the previous person's outcomes.

Updates#

The Flutter SDK polls and has no real-time stream. It checks every refreshInterval (30 seconds), pauses in the background and refreshes at once on return. To react to a change outside the widget tree, listen to client.changes, a broadcast stream that emits a FlagState on every change.

dart
client.changes.listen((state) {
  debugPrint('flags from ${state.source.name}, status ${state.status.name}');
});

Offline and errors#

Once the client has flags, from a fetch, the offline cache or initialFlags, evaluation is purely local and never throws. It keeps working with no internet and through a FlagSwift outage.

What happens when something goes wrong
SituationDescription
A refresh failsThe last good flags stay. The state becomes error, onError is called, and polling backs off up to about six minutes. The next success resets it.
First load, nothing cachedYou get your fallbacks, then false, until the response arrives. initialize waits at most initTimeout and never throws.
Next launch, offlineWith storage set, the cached flags for that person and environment apply at once. A corrupt entry is ignored, and a cache never overwrites network or bootstrap flags.
App in the backgroundFlagSwiftScope pauses polling, and resume refreshes at once. You can also call pause() and resume() yourself.
Reading the stateclient.state has status, flags, error, lastUpdated and source (none, bootstrap, cache or network).

Outcome analytics#

Report what people saw and what they did so FlagSwift can compare variants. Nothing is sent unless you call these or set autoExposures, and only the person's identifier, the flag, the variant and the event name leave the device.

dart
client.trackExposure('checkout');          // this user was shown the flag's current outcome
client.track('purchase', value: 49.0);     // what they did; the value is optional
await client.flushAnalytics();             // send what is queued now
final status = client.analyticsStatus;     // pending, sent, dropped, enabled

See Outcomes for how results are read in the console.

Reference#

Package flagswift, Dart 3, Flutter 3.13 or newer. package:flagswift/flagswift.dart is the pure Dart client and also works outside Flutter. package:flagswift/flagswift_flutter.dart adds the widgets and re-exports the client.

FlagSwiftClient constructor
ParameterTypeDescription
apiKey*StringA client key (fs_client_...).
baseUrl*StringYour server address. Must start with http:// or https://.
environmentString?Only for project-wide keys.
userFlagSwiftUser?The person to evaluate for. Change it later with identify.
refreshIntervalDurationDefault 30 seconds.
timeoutDurationPer request. Default 5 seconds.
initTimeoutDurationThe longest initialize waits. Default 5 seconds.
maxRetriesintDefault 2.
fallbacksMap<String, Object?>Served for unknown flags or before anything loads.
initialFlagsMap<String, ClientFlag>?Start ready with these flags.
storageFlagStorage?The offline cache. Use SharedPreferencesStorage in an app.
reportErrorsboolDefault true.
onErrorvoid Function(Object)?Called when a refresh fails.
httpClient, sdkhttp.Client?, SdkInfoA custom HTTP client, and the name and version sent to the server (default flutter).
FlagSwiftClient members
MemberDescription
Future<void> initialize()Loads the cache, fetches and starts polling. Waits up to initTimeout.
Future<void> identify(FlagSwiftUser? user)Switches the person and refreshes.
Future<void> refresh()Fetch now. A failure keeps the last flags and sets the error state.
bool isEnabled(String flagKey, {bool? fallback})The flag, then your fallback, then the configured one, then false. Unknown flags count a FLAG_NOT_FOUND error.
String? variant(String flagKey)The served variant.
T? value<T>(String flagKey, {T? fallback})The variant's value, or the boolean for plain flags.
ClientFlag? flag(String flagKey) / Map<String, ClientFlag> get allOne raw result, or all of them.
FlagState get statestatus, flags, error, lastUpdated and source.
Stream<FlagState> get changesA broadcast stream that emits on every change.
trackExposure(flag) / track(event, {value})Report that this user was shown the flag's current outcome, and what they then did. Never throw. track sends the user's pending exposures first.
flushAnalytics() / analyticsStatusSends what is queued now. analyticsStatus has pending, sent, dropped and enabled (null while unknown). The autoExposures constructor option queues an exposure on every read (default false).
void pause() / void resume()Stop and restart polling.
void dispose()Permanent. Closes the stream and stops polling.
Flutter types and widgets
NameDescription
FlagSwiftUseridentifier or identifiers, account or accounts, device or devices, and attributes. The first identifier is used for bucketing.
FlagState, FlagStatus, FlagSourceStatus is idle, loading, ready or error. Source is none, bootstrap, cache or network.
FlagStorage, MemoryStorage, SharedPreferencesStorageFlagStorage has read(key) and write(key, value). MemoryStorage is for tests; SharedPreferencesStorage keeps the cache across launches.
FlagSwiftScope(client, child, autoInitialize = true, manageLifecycle = true, disposeClient = false)Puts the client in the widget tree, starts it, and pauses polling in the background (refreshing on return). Widgets below rebuild when flags change.
context.flag(key, {fallback})On or off, and rebuilds the widget when it changes.
context.flagVariant(key)The served variant, rebuilding on change.
context.flagswiftThe client, without rebuilding.
Feature(flag:, child:, otherwise?, variant?, invert = false, fallback?)Shows child when the flag is on and the variant matches; otherwise otherwise or nothing.
FlagBuilder(flag:, builder:, fallback?)builder(context, enabled, variant) for custom layouts.
FlagSwiftException, backoffDelayThe error type and the retry delay helper.