Every Flutter team we join eventually ships a feature they wish they could turn off. The redesigned checkout that tanks conversion, the new sync engine that melts batteries on one OEM, the AI summariser whose token bill triples overnight. Store review plus phased release means the honest answer to "can you roll that back today?" is usually no — unless the switch lives in your app, not in your binary.
This tutorial builds a feature flag layer for Flutter that holds up in production: a provider-agnostic abstraction, Firebase Remote Config as the default backend, safe defaults that work offline and on first launch, percentage rollouts with stable bucketing, experiment assignment wired to analytics, and the tests and kill-switch drills that make the whole thing trustworthy. Versions assume Flutter 3.3x–3.4x and Dart 3.
Four things people confuse
Keep them separate in your head and in your code; they have different lifetimes and different owners.
| Concept | Lifetime | Owner | Example |
|---|---|---|---|
| Release toggle | Weeks, then deleted | Engineering | new_checkout_enabled |
| Kill switch | Permanent | On-call | ai_summaries_enabled |
| Experiment | One test cycle | Product/growth | onboarding_variant |
| Entitlement | Permanent | Billing | pro_tier_exports |
Entitlements are not flags. They are user state and must come from your own server with the purchase receipt behind them — never from Remote Config, which a rooted device can trivially tamper with. Everything else in this tutorial is safe to serve from a config service, because the worst case is a user sees a feature early.
The abstraction comes first
Do not sprinkle FirebaseRemoteConfig.instance.getBool('x') through your widgets. You will want to swap providers (Remote Config, LaunchDarkly, ConfigCat, Statsig, your own endpoint), and you will want flags in widget tests without a network.
// lib/flags/flag.dart
class Flag<T> {
const Flag(this.key, this.defaultValue, {this.description = ''});
final String key;
final T defaultValue;
final String description;
}
class Flags {
static const newCheckout = Flag<bool>('new_checkout_enabled', false,
description: 'Release toggle for the rebuilt checkout flow.');
static const aiSummaries = Flag<bool>('ai_summaries_enabled', true,
description: 'Kill switch: disables all LLM calls.');
static const syncBatchSize = Flag<int>('sync_batch_size', 50);
static const onboardingVariant = Flag<String>('onboarding_variant', 'control');
}
A single Flags class is the registry. Reviewers can see every flag in the app, its type, its default and why it exists — which is the first thing that rots when flags are string literals scattered across 200 files.
// lib/flags/flag_source.dart
abstract interface class FlagSource {
Future<void> initialize();
T value<T>(Flag<T> flag);
Stream<void> get changes; // emit when values are refreshed
Future<void> refresh();
}
Three implementations cover everything: RemoteConfigFlagSource for production, StaticFlagSource for tests, and LayeredFlagSource that lets a debug override win over remote values.
Defaults are the real product
The single most important rule: the default value in the binary must be the safe value, and the app must be fully usable if the config fetch never succeeds. First launch on a cold install, airplane mode, a corporate network blocking Firebase — all of these happen, and all of them happen on the day of your launch demo.
For release toggles, the safe default is false (old code path). For kill switches, the safe default is true (feature on) — otherwise a network outage disables your product. That asymmetry trips people up constantly, so write it in the flag's description.
// lib/flags/remote_config_source.dart
import 'package:firebase_remote_config/firebase_remote_config.dart';
class RemoteConfigFlagSource implements FlagSource {
RemoteConfigFlagSource(this._rc, this._defaults);
final FirebaseRemoteConfig _rc;
final Map<String, Object> _defaults;
final _changes = StreamController<void>.broadcast();
@override
Future<void> initialize() async {
await _rc.setDefaults(_defaults);
await _rc.setConfigSettings(RemoteConfigSettings(
fetchTimeout: const Duration(seconds: 8),
minimumFetchInterval: const Duration(hours: 1),
));
// Serve last-known-good immediately, fetch in the background.
unawaited(_rc.fetchAndActivate().then((changed) {
if (changed) _changes.add(null);
}).catchError((_) {/* keep cached/default values */}));
_rc.onConfigUpdated.listen((_) async {
await _rc.activate();
_changes.add(null);
});
}
@override
T value<T>(Flag<T> flag) {
final v = _rc.getValue(flag.key);
if (v.source == ValueSource.valueStatic) return flag.defaultValue;
return switch (flag.defaultValue) {
bool _ => v.asBool() as T,
int _ => v.asInt() as T,
double _ => v.asDouble() as T,
String _ => v.asString() as T,
_ => flag.defaultValue,
};
}
@override
Stream<void> get changes => _changes.stream;
@override
Future<void> refresh() async {
if (await _rc.fetchAndActivate()) _changes.add(null);
}
}
Two details matter. fetchAndActivate is not awaited during startup — blocking your splash screen on a network call is how flag systems get ripped out again. And onConfigUpdated (real-time Remote Config) gives you sub-minute propagation for kill switches, which is the difference between a five-minute incident and a five-hour one.
In release builds set minimumFetchInterval to an hour or more; in debug set it to Duration.zero so QA can flip a flag and pull-to-refresh.
Reading flags in the widget tree
With Riverpod the whole thing is about fifteen lines, and crucially it rebuilds when config changes arrive.
final flagSourceProvider = Provider<FlagSource>((ref) => throw UnimplementedError());
final flagChangesProvider = StreamProvider<void>(
(ref) => ref.watch(flagSourceProvider).changes);
Provider<T> flagProvider<T>(Flag<T> flag) => Provider<T>((ref) {
ref.watch(flagChangesProvider); // rebuild on refresh
return ref.watch(flagSourceProvider).value(flag);
});
final newCheckoutProvider = flagProvider(Flags.newCheckout);
Usage stays boring, which is the point:
class CheckoutRoute extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) =>
ref.watch(newCheckoutProvider) ? const NewCheckout() : const LegacyCheckout();
}
One caveat: never let a flag flip mid-transaction. Read the value once when a flow starts and hold it for the duration, or a user who was mid-checkout when your rollout advanced will see the screen swap under their thumb. A simple late final bool _useNew = ref.read(newCheckoutProvider); in the flow's controller is enough.
Percentage rollouts with stable bucketing
Server-side percentage rollouts (Remote Config conditions, LaunchDarkly targeting) are fine, but you still want client-side bucketing for experiments you assign locally and for provider-independent logic. The requirements: the same user always lands in the same bucket, buckets are independent per flag, and nothing depends on a server round trip.
import 'dart:convert';
import 'package:crypto/crypto.dart';
int bucketOf(String stableId, String flagKey, {int buckets = 100}) {
final digest = sha256.convert(utf8.encode('$flagKey:$stableId'));
final n = digest.bytes.take(4).fold<int>(0, (a, b) => (a << 8) | b);
return (n & 0x7fffffff) % buckets;
}
bool inRollout(String stableId, String flagKey, int percent) =>
bucketOf(stableId, flagKey) < percent;
Salting the hash with the flag key is what keeps rollouts independent — without it, the same unlucky 5% of users get every half-baked feature in the app and your crash-free rate for that cohort looks like a different product.
The stableId must survive app restarts and must not be a device identifier you are not allowed to use. Use your authenticated user ID when you have one; otherwise generate a UUID on first launch and store it in secure storage. On iOS remember that Keychain entries survive reinstalls, which is usually what you want for experiment consistency but occasionally surprising in QA.
Experiments: assignment, exposure, and analytics
An experiment is a flag plus a recorded exposure. If you do not log which variant a user actually saw, at the moment they saw it, your analysis is guesswork.
class ExperimentService {
ExperimentService(this._flags, this._analytics, this._stableId);
final FlagSource _flags;
final Analytics _analytics;
final String _stableId;
final _exposed = <String>{};
String variant(Flag<String> flag) {
final v = _flags.value(flag);
if (_exposed.add(flag.key)) {
_analytics.logEvent('experiment_exposure', {
'experiment': flag.key,
'variant': v,
'bucket': bucketOf(_stableId, flag.key),
});
}
return v;
}
}
Call variant() at the point of render, not at app start. Exposure logged for users who never reached the screen dilutes your sample and makes a winning variant look flat.
Also push the variant into your crash reporter and your logs — Crashlytics custom keys, Sentry tags, whatever you run:
FirebaseCrashlytics.instance.setCustomKey('onboarding_variant', v);
The first thing you will ask during an incident is "is this cohort-specific?", and this one line answers it.
The debug overrides screen
Build it on day one. A hidden screen (seven taps on the version string, or a flavour-gated route) listing every flag in the registry with a switch or text field, writing to a local override store that the LayeredFlagSource checks first.
class LayeredFlagSource implements FlagSource {
LayeredFlagSource(this.overrides, this.remote);
final OverrideStore overrides; // SharedPreferences-backed, debug builds only
final FlagSource remote;
@override
T value<T>(Flag<T> flag) => overrides.get<T>(flag.key) ?? remote.value(flag);
// ...delegate the rest
}
Gate the override store behind kDebugMode or a build flavour so a release binary can never read it. The payoff: QA tests both branches of a flag without a backend change, and designers can demo the unreleased variant on a plane.
Testing both sides of every flag
A flag doubles the states of a screen. Your test suite should admit that.
FlagSource staticFlags(Map<String, Object> values) => StaticFlagSource(values);
testWidgets('renders legacy checkout when flag is off', (tester) async {
await tester.pumpWidget(ProviderScope(
overrides: [flagSourceProvider.overrideWithValue(
staticFlags({'new_checkout_enabled': false}))],
child: const App(),
));
expect(find.byType(LegacyCheckout), findsOneWidget);
});
Two cheap additions pay for themselves:
- A unit test asserting that every
Flagin the registry has a safe default and a non-empty description. - A golden test per variant for flags that change layout, so a stale branch does not quietly drift.
For bucketing, a property-style test over 100k synthetic IDs asserting the distribution is within a percent or two of the target catches a bad hash truncation immediately.
Operational discipline
Name flags with intent. new_checkout_enabled is fine; flag_2 and test_new are landmines eighteen months later.
Give every release toggle an expiry. Put the removal date in the description and fail CI when it passes:
// test/flag_hygiene_test.dart — fails once a toggle outlives its ticket
expect(expiredFlags(Flags.all, DateTime.now()), isEmpty,
reason: 'Delete the toggle and the dead branch.');
The cost of flags is not the infrastructure, it is the combinatorial explosion of untested code paths. A flag that has been at 100% for six months is technical debt wearing a feature's clothes. Deleting it is part of the rollout, not an optional follow-up.
Rehearse the kill switch. Once a quarter, flip a kill switch in production during business hours with the team watching, and time how long it takes to reach a device. If nobody knows who can change the value or how long propagation takes, you do not have a kill switch — you have a config value.
Watch the staged rollout per cohort. Pair flags with your crash and performance dashboards filtered by the variant key. A rollout that is fine at 5% and broken at 50% is usually a backend capacity problem, not a client bug, and the cohort-tagged telemetry is what tells you which.
Respect privacy rules. Experiment exposure events are analytics. If you ship in the EU, they belong behind your consent flow and in your App Store privacy manifest / Play Data safety declaration alongside everything else your analytics SDK collects.
When to use something other than Remote Config
Firebase Remote Config is free, integrates with A/B testing and Analytics, and supports real-time updates — it covers most apps. Reach for a dedicated platform when you need per-user targeting rules maintained by non-engineers, audit logs of who changed what, flag values shared between your Flutter app and your backend services, or guardrail metrics that auto-roll-back a bad variant. If you run your own config endpoint, keep the same contract: cached last-known-good, safe binary defaults, ETag-based polling, and a payload small enough to fetch on a bad connection.
A sane rollout sequence
- Ship the flag off, in a release, with both paths tested. Flag-less code is never tested in production.
- Enable internal builds and dogfood for a few days.
- 1% → watch crash-free rate, ANRs, and the one business metric that matters.
- 10% → 50% → 100%, pausing at each step for a full day of data.
- Delete the flag and the dead branch in the next release, and close the ticket.
That sequence takes two weeks and makes a bad feature a five-minute non-event instead of an emergency hotfix stuck in review.
AviaryApps builds and modernises Flutter apps for teams that need senior capacity quickly, including agencies subcontracting Flutter work. If you want a feature flag and release-safety layer retrofitted into an existing app — or a review of the rollout process behind it — get in touch.