Sub topic 6
Reading the flavor in Dart with appFlavor
This chapter assumes you can run flutter run and flutter build, and that you have seen the --flavor flag and the --dart-define options from earlier chapters. You do not need finished Android and iOS flavor setups to follow the Dart side here. You do need them to see a non-null value on a device.
The problem appFlavor solves
The --flavor flag selects a native build variant. On Android that is a Gradle product flavor, and on iOS it is a scheme and build configuration. Your Dart code runs inside that native app, but it has no direct view of which variant produced it.
Before Flutter 3.16, people worked around this in three ways:
- Passing a duplicate
--dart-define=FLAVOR=devnext to--flavor dev. - Using a platform channel to ask the native side for the flavor.
- Giving every flavor its own entrypoint and hard-coding the name there.
The appFlavor constant replaces the first two workarounds. It is exported by package:flutter/services.dart:
import 'package:flutter/services.dart';
void printFlavor() {
// appFlavor is null when the app was built without --flavor.
print('Running flavor: ${appFlavor ?? 'none'}');
}The type is String?. The value is exactly the string you passed to --flavor, with the same capitalization. If you run flutter run --flavor staging, then appFlavor == 'staging'.
How the value reaches Dart
When you pass --flavor, the Flutter tool does two jobs. It forwards the flavor name to the native build (Gradle or Xcode), and it adds a Dart define named FLUTTER_APP_FLAVOR to the compile step. The appFlavor constant reads that define. In effect, the tool does the duplicate --dart-define for you.
Two consequences follow from this design:
appFlavoris a compile-time constant. Its value is baked into the compiled Dart code, so you can use it inconstexpressions, and a hot reload cannot change it. Switching flavors always means a new build or a freshflutter run.- The value comes from the command line, not from the native project. Dart does not check that the Android flavor or iOS scheme exists. The native build fails earlier if they are missing.
What a null value means
appFlavor is null whenever the build had no --flavor flag. This happens in several situations:
- A plain
flutter runorflutter buildwith no flavor. - Most unit and widget tests, which normally run without a flavor.
- Platforms where you did not set up flavors at all.
Treat null as a real case in your code. Do not assume a flavor is always present. A null flavor in a release build usually points to a mistake in your build script, so it is worth failing loudly instead of defaulting silently.
Turning the string into a type
Comparing raw strings across the codebase invites typos. A common pattern converts appFlavor once, at startup, into an enum:
import 'package:flutter/services.dart';
enum Flavor {
dev,
staging,
prod;
/// Resolves the flavor passed to --flavor.
///
/// Throws if no flavor was given or the name is unknown, so a
/// misconfigured build fails at startup instead of hitting the
/// wrong backend.
static Flavor current() {
return switch (appFlavor) {
'dev' => Flavor.dev,
'staging' => Flavor.staging,
'prod' => Flavor.prod,
final other => throw StateError(
'Unknown or missing flavor: $other. '
'Pass --flavor dev, staging or prod.',
),
};
}
}The final pattern final other also matches null, so one branch handles both a missing flavor and an unknown name. The error message shows exactly what the build received.
A small app that uses the enum looks like this:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
enum Flavor {
dev,
staging,
prod;
static Flavor current() {
return switch (appFlavor) {
'dev' => Flavor.dev,
'staging' => Flavor.staging,
'prod' => Flavor.prod,
final other => throw StateError('Unknown or missing flavor: $other'),
};
}
}
void main() {
final flavor = Flavor.current();
runApp(FlavorDemo(flavor: flavor));
}
class FlavorDemo extends StatelessWidget {
const FlavorDemo({super.key, required this.flavor});
final Flavor flavor;
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(title: Text('Flavor: ${flavor.name}')),
body: Center(child: Text('Running ${flavor.name}')),
),
);
}
}Run it with flutter run --flavor dev. Without the flag it throws a StateError at startup, which is the behavior you want.
Combining appFlavor with AppConfig
The flavor tells you which environment you are in. The AppConfig class from earlier chapters holds the environment's settings. You have two ways to connect them.
Map the flavor to a config. The flavor is the only input and the settings live in Dart:
import 'package:flutter/services.dart';
class AppConfig {
const AppConfig({required this.apiBaseUrl, required this.enableLogging});
final String apiBaseUrl;
final bool enableLogging;
static AppConfig forFlavor(String? flavor) {
return switch (flavor) {
'dev' => const AppConfig(
apiBaseUrl: 'https://api.dev.example.com',
enableLogging: true,
),
'staging' => const AppConfig(
apiBaseUrl: 'https://api.staging.example.com',
enableLogging: true,
),
'prod' => const AppConfig(
apiBaseUrl: 'https://api.example.com',
enableLogging: false,
),
_ => throw StateError('Unknown or missing flavor: $flavor'),
};
}
static AppConfig get current => forFlavor(appFlavor);
}Keep settings in --dart-define-from-file and use the flavor only as a label. The settings stay out of the Dart source, and the flavor drives things such as a banner or analytics tags.
The mapping approach has fewer moving parts, because one flag selects everything. The define-file approach keeps URLs out of source and lets a CI job swap values without code changes. Choose one source of truth per setting. If a URL lives both in the switch and in a JSON file, the two will eventually disagree.
Notice that forFlavor takes the flavor as a parameter instead of reading appFlavor directly. That makes it testable, as the testing section below shows.
Catching mismatched flags
The flavor and the other build inputs are independent flags. Nothing stops you from running flutter run --flavor prod -t lib/main_dev.dart --dart-define-from-file=config/dev.json. The app then has the prod app ID and the dev backend, which is the kind of mistake that corrupts real data or ships the wrong build.
A cheap guard is to compare two signals at startup:
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
void assertFlavorMatches(String entrypointFlavor) {
if (appFlavor != entrypointFlavor) {
final message = 'Entrypoint is $entrypointFlavor but the build flavor '
'is ${appFlavor ?? 'none'}.';
if (kReleaseMode) {
throw StateError(message);
}
debugPrint('WARNING: $message');
}
}Call assertFlavorMatches('dev') from main_dev.dart before runApp. In debug builds you get a console warning. In release builds the app refuses to start, so a mislabeled build never reaches users.
Common uses
Teams usually read appFlavor for these purposes:
- Showing a visible banner or a different app bar color in non-production builds, so testers can tell builds apart at a glance.
- Choosing which backend or analytics project to talk to.
- Enabling debug menus, extra logging or feature toggles in dev and staging only.
- Tagging crash reports and analytics events with the environment.
Do not use it for anything that must stay hidden from users, such as secrets. The value and every branch of your switch are compiled into the app, so anyone can extract them. A later chapter covers that limit in detail.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `appFlavor` is `null` on a device | The app was started without `--flavor`, for example from an IDE button with no flavor in its launch configuration | Add the flavor to the run configuration or run from the terminal |
| `Unknown or missing flavor: Dev` | The flag was `--flavor Dev` but the code compares to `'dev'` | Use one spelling everywhere. The Dart string must equal the flag exactly |
| Changing the flavor has no effect after hot reload | `appFlavor` is a compile-time constant | Stop the app and run again with the new flag |
| Build fails before Dart compiles, saying the flavor does not exist | The Gradle flavor or Xcode scheme is missing or named differently | Create the native flavor or scheme with the same name |
| Tests see `null` | Tests run without a flavor | Pass the flavor as a parameter instead of reading `appFlavor` inside the code under test |
Testing code that depends on the flavor
Because appFlavor is a constant, you cannot reassign it in a test. Design around that. The forFlavor function above takes the flavor as an argument, so a test can call it with any name:
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/app_config.dart';
void main() {
test('prod disables logging', () {
expect(AppConfig.forFlavor('prod').enableLogging, isFalse);
});
test('dev points at the dev API', () {
expect(
AppConfig.forFlavor('dev').apiBaseUrl,
'https://api.dev.example.com',
);
});
test('a missing flavor is an error', () {
expect(() => AppConfig.forFlavor(null), throwsStateError);
});
}The only line that reads the global is AppConfig.current. Keep that in one place, and everything else stays easy to test.
Summary of the model
--flavorselects the native variant and also sets a Dart define, whichappFlavorexposes as aString?.- The value is a compile-time constant. It is
nullwithout the flag and cannot change at runtime. - Convert it once to an enum or config object, and fail loudly on an unknown or missing value.
- Compare it with other build inputs so mismatched flags do not slip through.
- Pass the flavor into your logic as a parameter so tests do not depend on how the app was built.
Exercise
Your teammate runs flutter run --flavor staging -t lib/main_dev.dart and the app talks to the dev backend while using the staging app ID. Using appFlavor, how would you stop this mistake from reaching a release build, and why can a hot reload not fix a wrong flavor value?
Show answer
In maindev.dart, compare appFlavor with the expected name 'dev' before calling runApp. In release mode (kReleaseMode) throw a StateError when they differ, and in debug mode print a warning. The guard works because the flavor flag and the entrypoint are independent inputs, so comparing them reveals a mismatch. Hot reload cannot change the value because appFlavor is a compile-time constant set from the FLUTTERAPP_FLAVOR define during the build. Changing it requires stopping the app and running again with the correct flags.
Exercise
Write a function bool showDebugBanner(String? flavor) that returns true for 'dev' and 'staging' and false for 'prod', and throws a StateError for any other value including null. Why is it better to take the flavor as a parameter than to read appFlavor inside the function?
Show answer
Code: bool showDebugBanner(String? flavor) => switch (flavor) { 'dev' || 'staging' => true, 'prod' => false, _ => throw StateError('Unknown or missing flavor: $flavor') }; Taking the flavor as a parameter lets a test call the function with any value. appFlavor is a constant fixed by the build, and tests usually run without a flavor, so reading it inside the function would make every test see null.