The Flutter tool (flutter
) supports the concept of feature flags, or boolean flags that can inform, change, allow, or deny access to behavior, either in the tool itself, or in the framework (package:flutter
, and related).
Table of Contents
For example, enabling the use of Swift Package Manager:
flutter config --enable-swift-package-manager
Feature flags can be configured globally (for an entire machine), locally (for a particular app), per-test, and be automatically enabled for different release channels (master
, versus beta
, versus stable
), giving multiple consistent options for developing.
See also, Flutter pubspec options > Fields > Config.
Feature flags allow conditionally, consistently, and conveniently changing behavior.
For example:
Gradual rollouts to introduce new features to a small subset of users.
A/B Testing to easily test or compare different implementations.
Kill Switches to quickly disable problematic features without large code changes.
Allow experimental access to features not ready for broad or unguarded use.
We do not consider it a breaking change to modify or remove experimental flags across releases, or to make changes guarded by experimental flags. APIs that are guarded by flags are subject to chage at any time.
Flags are managed in packages/flutter_tools/lib/src/features.dart
.
The following steps are required:
Add a new top-level const Feature
:
const Feature unicornEmojis = Feature( name: 'add unicorn emojis in lots of fun places', );
Additional parameters are required to make the flag configurable outside of a unit test.
To allow flutter config
, or in pubspec.yaml
's config: ...
section, include configSetting
:
const Feature unicornEmojis = Feature( name: 'add unicorn emojis in lots of fun places', configSetting: 'enable-unicorn-emojis', );
To allow usage of the flag in the Flutter framework, include runtimeId
:
const Feature unicornEmojis = Feature( name: 'add unicorn emojis in lots of fun places', runtimeId: 'enable-unicorn-emojis', );
To allow an environment variable, include environmentOverride
:
const Feature unicornEmojis = Feature( name: 'add unicorn emojis in lots of fun places', environmentOverride: 'FLUTTER_UNICORN_EMOJIS', );
Add a new field to abstract class FeatureFlags
:
abstract class FeatureFlags { /// Whether to add unicorm emojis in lots of fun places. bool get isUnicornEmojisEnabled; }
Implement the same getter in FlutterFeatureFlagsIsEnabled
:
mixin FlutterFeatureFlagsIsEnabled implements FeatureFlags { @override bool get isUnicornEmojisEnabled => isEnabled(unicornEmojis); }
Add a new entry in FeatureFlags.allFeatures
:
List<Feature> get allFeatures => const <Feature>[ // ... unicornEmojis, ];
Create a G3Fix to update google3's Google3Features
:
Add a new field to Google3Features
:
class Google3Features extends FeatureFlags { @override bool get isUnicornEmojisEnabled => true; }
Add a new entry to Google3Features.allFeatures
:
List<Feature> get allFeatures => const <Feature>[ // ... unicornEmojis, ];
By default, after adding a flag, the flag is considered disabled, and cannot be enabled outside of our own unit tests. This allows iterating locally with the code without having to support users or field issues related to the flag.
After some time, you may want to allow the flag to be enabled.
Using the options master
, beta
or stable
, you can make the flag configurable in those channels. For example, to make the flag available to be enabled (but still off by default) on the master
channel:
const Feature unicornEmojis = Feature( name: 'add unicorn emojis in lots of fun places', configSetting: 'enable-unicorn-emojis', master: FeatureChannelSetting(available: true), );
Or to make it available on all channels:
const Feature unicornEmojis = Feature( name: 'add unicorn emojis in lots of fun places', configSetting: 'enable-unicorn-emojis', master: FeatureChannelSetting(available: true), beta: FeatureChannelSetting(available: true), stable: FeatureChannelSetting(available: true), );
Once a flag is ready to be enabled by default, once again it can be configured on a per-channel basis.
For example, enabled on master
by default, but disabled by default elsewhere:
const Feature unicornEmojis = Feature( name: 'add unicorn emojis in lots of fun places', configSetting: 'enable-unicorn-emojis', master: FeatureChannelSetting(available: true, enabledByDefault: true), beta: FeatureChannelSetting(available: true), stable: FeatureChannelSetting(available: true), );
Once the flag is ready to be enabled in every environment:
const Feature unicornEmojis = Feature.fullyEnabled( name: 'add unicorn emojis in lots of fun places', configSetting: 'enable-unicorn-emojis', );
After a flag is no longer useful (perhaps the experiment has concluded, the flag has been enabled successfully for 1+ stable releases), most[^1] flags should be removed so that the older behavior (or lack of a feature) can be refactored and removed from the codebase, and there is less of a possibility of conflicting flags.
To remove a flag, follow the opposite steps of adding a flag.
You may need to remove references to the (disabled) flag from unit or integration tests as well.
[^1]: Some flags might have a longer or indefinite lifespan, but this is rare.
Users have several options to configure flags. Assuming the following feature:
const Feature unicornEmojis = Feature( name: 'add unicorn emojis in lots of fun places', configSetting: 'enable-unicorn-emojis', environmentOverride: 'FLUTTER_ENABLE_UNICORN_EMOJIS', );
Flutter uses the following precendence order:
The app's pubspec.yaml
file:
flutter: config: enable-unicorn-emojis: true
The tool's global configuration:
flutter config --enable-unicorn-emojis
Environment variables:
FLUTTER_ENABLE_UNICORN_EMOJIS=true flutter some-command
If none of these are set, Flutter falls back to the feature's default value for the current release channel.
Once you have a flag, you can use it to conditionally enable something or provide a different execution branch.
In the flutter
tool, feature flags. flags can be accessed either by adding (and providing) an explicit FeatureFlags
parameter (recommended):
class WebDevices extends PollingDeviceDiscovery { // While it could be injected from the global scope (see below), this larger // feature (and tests of it) are made more explicit by directly taking a // reference to a `FeatureFlags` instance. WebDevices({required FeatureFlags featureFlags}) : _featureFlags = featureFlags; final FeatureFlags _featureFlags; @override Future<List<Device>> pollingGetDevices({Duration? timeout}) async { if (!_featureFlags.isWebEnabled) { return <Device>[]; } /* ... omitted for brevity ... */ } }
Or by injecting the currently set flags using the globals
pattern:
// Relative path depends on location in the tool. import '../src/features.dart'; class CreateCommand extends FlutterCommand with CreateBase { Future<int> _generateMethodChannelPlugin() async { /* ... omitted for brevity ... */ final List<String> templates = <String>['plugin', 'plugin_shared']; if ((isIos || isMacos) && featureFlags.isSwiftPackageManagerEnabled) { templates.add('plugin_swift_package_manager'); } /* ... omitted for brevity ... */ } }
In the framework, feature flags can be accessed by importing src/foundation/_features.dart
:
import 'package:flutter/src/foundation/_features.dart'; final class SensitiveContent extends StatelessWidget { SensitiveContent() { if (!debugEnabledFeatureFlags.contains('enable-sensitive-content')) { throw UnsupportedError('Sensitive content is an experimental feature and not yet available.'); } } }
Note that feature flag usage in the framework runtime is very new, and is likely to evolve over time.
Feature flags are not designed to help tree shaking. For example, you cannot conditionally import Dart code depending on the enabled feature flags. Tree shaking might not remove code that is feature flagged off.
For integration tests representing packages where a flag is enabled, prefer using the config:
property in pubspec.yaml
:
flutter: config: enable-unicorn-emojis: true
You may see legacy cases where the flag is enabled or disabled globally using flutter config
.
For unit tests where the code directly takes a FeatureFlags
instance:
final WindowsWorkflow windowsWorkflow = WindowsWorkflow( platform: windows, featureFlags: TestFeatureFlags(isWindowsEnabled: true), ); /* ... omitted for brevity ... */
Or, for larger test suites, or code that uses the global featureFlags
getter:
testUsingContext('prints unicorns when enabled', () async { // You'd write a real test, this is just an example. expect(featureFlags.isUnicornEmojisEnabled, true); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isUnicornEmojisEnabled: true), });
Feature flags can be enabled by importing src/foundation/_features.dart
:
test('sensitive content should fail if the flag is disabled', () { final Set<String> originalFeatureFlags = {...debugEnabledFeatureFlags}; addTearDown(() { debugEnabledFeatureFlags.clear(); debugEnabledFeatureFlags.addAll(originalFeatureFlags); }); debugEnabledFeatureFlags.remove('enable-sensitive-content'); expect(() => SensitiveContent(), throwsUnsupportedError); });
Note that feature flag usage in the framework runtime is very new, and is likely to evolve over time.
The Flutter engine and embedders cannot use Flutter's feature flags directly.
If an embedder needs feature flags, you can instead use the project's platform-specific configuration.
On Android, use AndroidManifest.xml
:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application ...> <meta-data android:name="io.flutter.embedding.android.EnableUnicornEmojis" android:value="true" /> </application> </manifest>
On iOS and macOS, use Info.plist
:
... <plist version="1.0"> <dict> <key>FLTEnableUnicornEmojis</key> <true /> </dict> </plist>
See Impeller and UI thread merging for prior art.
[!IMPORTANT] If possible, prefer to use Flutter feature flags instead of platform-specific configuration files. Flutter feature flags are easier for Flutter app developers.