Sub topic 5
Passing environment values with --dart-define
This chapter assumes you can run flutter run and flutter build from a terminal and write basic Dart. It also assumes you know what a const value is. You don't need any Gradle or Xcode knowledge.
By the end you will be able to pass values such as an API address into a build, read them in Dart, keep them in files per environment, and avoid the common mistakes. One of those mistakes is treating these values as secrets.
Why build-time configuration
A typical app talks to a staging backend while you develop and to a production backend after release. You could edit a constant before each build, but that is easy to forget, and a wrong value can reach the store.
Flutter lets you supply values on the command line instead. The flag is --dart-define. The Dart compiler reads the values while it compiles your code and bakes them into the app as constants. The source code stays the same, and only the command changes.
Reading values in Dart
Dart provides three constructors for reading these values: String.fromEnvironment, int.fromEnvironment and bool.fromEnvironment. Each takes the key name and an optional defaultValue. The default is used when no value was supplied for that key.
import 'package:flutter/material.dart';
class AppConfig {
static const environment = String.fromEnvironment(
'APP_ENV',
defaultValue: 'staging',
);
static const apiBaseUrl = String.fromEnvironment(
'API_BASE_URL',
defaultValue: 'https://staging.example.com',
);
static const requestTimeoutSeconds = int.fromEnvironment(
'REQUEST_TIMEOUT_SECONDS',
defaultValue: 30,
);
static const enableLogging = bool.fromEnvironment('ENABLE_LOGGING');
}
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Config demo')),
body: Center(
child: Text(
'env: ${AppConfig.environment}\n'
'api: ${AppConfig.apiBaseUrl}\n'
'timeout: ${AppConfig.requestTimeoutSeconds}s\n'
'logging: ${AppConfig.enableLogging}',
textAlign: TextAlign.center,
),
),
),
);
}
}Two details matter here.
- Without a
defaultValue, a missingStringis the empty string, a missingintis0, and a missingboolisfalse. A default ofhttps://staging.example.commeans an unconfigured build points at staging, not at production. - Keeping all lookups in one
AppConfigclass gives you a single place to see every setting the app accepts.
Always use const
These constructors are only guaranteed to work when called as const. The compiler has to resolve them while compiling. If you write final url = String.fromEnvironment('API_BASE_URL'); inside a method, Flutter may silently return the default value and ignore what you passed. Declare them as static const fields or const variables.
Supplying values on the command line
Pass --dart-define=KEY=VALUE to flutter run, flutter build, flutter test or flutter drive. Repeat the flag for each value.
flutter run \
--dart-define=APP_ENV=development \
--dart-define=API_BASE_URL=http://10.0.2.2:8080 \
--dart-define=ENABLE_LOGGING=trueOn the Android emulator, 10.0.2.2 is the address of your development machine. This is why a local backend often needs a different URL than a real device or the production server does.
Release builds take the same flags:
flutter build appbundle --release \
--dart-define=APP_ENV=production \
--dart-define=API_BASE_URL=https://api.example.com \
--dart-define=REQUEST_TIMEOUT_SECONDS=15Some rules to remember:
- Everything after the first
=is the value, so a URL with query characters works. Quote the whole argument if it contains&,?, spaces or other characters your shell interprets. --dart-define=ENABLE_LOGGING=trueproducestrueforbool.fromEnvironment. Any other string is treated asfalse.- An
intvalue that does not parse as a number falls back to the default, so a typo such as15sfails quietly. - Use the same key spelling in the command and in Dart. Keys are case-sensitive.
Using a file instead of many flags
Long commands become hard to read and easy to get wrong. Flutter can read the same values from a JSON file with --dart-define-from-file.
{
"APP_ENV": "production",
"API_BASE_URL": "https://api.example.com",
"REQUEST_TIMEOUT_SECONDS": 15,
"ENABLE_LOGGING": false
}Save it as config/prod.json, then build:
flutter build appbundle --release --dart-define-from-file=config/prod.jsonA common layout is one file per environment, such as config/dev.json, config/staging.json and config/prod.json. The command then selects the environment by choosing a file. You can combine this flag with --dart-define for one-off overrides.
Running from an IDE
The IDE can add the same flags for you, so you don't type them on every run.
- VS Code: add the flags to the
argslist of a configuration in.vscode/launch.json, for example"args": ["--dart-define-from-file=config/dev.json"]. Create one configuration per environment. - Android Studio: open the run configuration and put the flags in Additional run args.
A value is a compile-time constant, so changing it needs a full restart. Hot reload will not pick it up. If you edit a JSON file while the app is running, stop the app and run it again.
Values are not secrets
The compiler writes each defined value into the app. Anyone who downloads your app can extract it. Obfuscation, which a later chapter covers, renames Dart classes and functions but does not encrypt string constants.
Values that are safe to pass include a public API address, an analytics project identifier meant for client use, an environment name, and a feature switch. Some services issue "publishable" client keys, which are designed to be shipped inside apps. Check the service documentation before you decide a key is one of those.
--dart-define compared with flavors
Teams often mix up --dart-define and --flavor. They solve different problems.
| Concern | `--dart-define` | `--flavor` |
|---|---|---|
| What it changes | Constants in Dart code | Native build settings (Android product flavors, iOS schemes) |
| Typical use | API URL, feature switches, environment name | Different application ID, app name, icon or signing per environment |
| Needs native setup | No | Yes, in Gradle and Xcode |
| Can install side by side | No, same app identity | Yes, if the application IDs differ |
If you only need a different backend address, --dart-define is enough. If you want a staging build and a production build installed on the same phone at the same time, you need flavors, because the two builds need different application IDs. You can use both together, for example --flavor staging --dart-define-from-file=config/staging.json.
Common problems
- The app always shows the default value. Check that the call is
const, that the key spelling matches exactly, and that you did a full restart instead of a hot reload. - A build in the store points at staging. The default fell through because the release command left out the flag. Make the safe default match your riskiest mistake. Some teams use an empty default for production-critical values and fail fast at startup.
- A shell mangles the value. An unquoted
&in a URL ends the command in most shells. Wrap the argument in quotes or move the value into a JSON file. - A test passes locally and fails in CI.
flutter testneeds the same defines as the app. Pass--dart-defineor--dart-define-from-fileto the test command too.
A cheap safeguard is an assertion at startup that catches an unconfigured production build:
import 'package:flutter/foundation.dart';
void checkConfig() {
const env = String.fromEnvironment('APP_ENV');
if (kReleaseMode && env.isEmpty) {
throw StateError('APP_ENV was not set for this release build.');
}
}Call checkConfig() at the top of main(). Because kReleaseMode is true only in release builds, debug runs are unaffected. A release built without APP_ENV fails the first time you test it, instead of reaching users.
How this fits the release process
The next chapters in this tutorial cover signing and building the artifacts. Your final build commands will include the --dart-define or --dart-define-from-file flag for the production environment. Your CI pipeline will pass the same flag, selecting the file by branch or release type, so no one has to type it by hand.
Exercise
Your release build of an app should call https://api.example.com, but the installed app still contacts https://staging.example.com. The code reads the URL with final url = String.fromEnvironment('API_BASE_URL', defaultValue: 'https://staging.example.com'); inside a build method, and you built with flutter build apk --release --dart-define=API_BASE_URL=https://api.example.com. What is the likely cause, and how do you fix it?
Show answer
The constructor is not being called as const. These constructors are only guaranteed to work as compile-time constants, so inside a method it can return the default value. Declare it as static const apiBaseUrl = String.fromEnvironment('API_BASE_URL', defaultValue: ...); in a config class or at top level, rebuild with the same flag, and the production URL is used.
Exercise
A teammate proposes passing the production payment-provider secret key with --dart-define=PAYMENT_SECRET=... because "the build is obfuscated." Why is this unsafe, and what should you do instead?
Show answer
Defined values are stored in the compiled app as constants, and obfuscation renames symbols but does not encrypt string constants, so anyone can extract the key from the downloaded app. Keep the secret key on a server, and have the app call your backend, which uses the key. Pass only public, client-safe values through --dart-define.