Sub topic 2
Passing configuration with --dart-define
This chapter assumes you can run flutter run and flutter build from a terminal, and that you know what an API base URL is. It also assumes you can read a small Dart class. Flavors, entrypoints and native project files come in later chapters. Here you only need to learn how to get a value from the command line into Dart code.
What --dart-define does
--dart-define hands a key-value pair to the Dart compiler. The pair becomes part of the compiled program, in an environment the compiler can query while it builds your code. You then read the value in Dart with a fromEnvironment constructor.
flutter run --dart-define=API_BASE_URL=https://api.dev.example.comTwo properties follow from this design:
- The value is fixed when the app is built. The running app cannot change it.
- The compiler can treat the value as a constant. Branches that depend on it can be removed from release builds (tree shaking).
The next diagram shows the path a value takes.
Reading values in Dart
Dart provides four constructors for this: String.fromEnvironment, bool.fromEnvironment, int.fromEnvironment and bool.hasEnvironment. Each takes the key name. The first three also take an optional defaultValue.
const apiBaseUrl = String.fromEnvironment(
'API_BASE_URL',
defaultValue: 'https://api.example.com',
);
const enableLogging = bool.fromEnvironment('ENABLE_LOGGING');
const timeoutSeconds = int.fromEnvironment('TIMEOUT_SECONDS', defaultValue: 30);If the key was not defined, you get the default. The defaults when you give none are the empty string for String, false for bool, and 0 for int.
Parsing is strict:
bool.fromEnvironmentreturnstrueonly when the value is exactlytrue. Values such asTrue,1,yesandTRUEgivefalse.int.fromEnvironmentreturns the default when the value is not a valid integer, such as30s.- Key names are case-sensitive.
api_base_urlandAPI_BASE_URLare different keys.
Neither failure raises an error. A typo in a key name or value silently produces the default. This is the most common source of bugs with this feature, so the next sections cover ways to catch it.
The const requirement
The compiler resolves these constructors at build time. Always call them in a const context.
// Correct: evaluated at compile time.
const apiBaseUrl = String.fromEnvironment('API_BASE_URL');
// Risky: not a const context. The documentation only guarantees
// correct behavior when these constructors are invoked as const.
final apiBaseUrl2 = String.fromEnvironment('API_BASE_URL');The second form may appear to work on one platform and return the default on another. Write const, and use static const for class fields. Because the key must be known at compile time, you also cannot build the key from a variable: String.fromEnvironment(keyName) fails unless keyName is itself a constant.
Passing several values
Repeat the flag once per key:
flutter run \
--dart-define=API_BASE_URL=https://api.dev.example.com \
--dart-define=ENABLE_LOGGING=true \
--dart-define=TIMEOUT_SECONDS=10The same flags work with flutter build, flutter test and flutter drive. If you pass the same key twice, do not depend on which one wins. Remove the duplicate.
Quoting matters when a value contains characters your shell treats specially, such as &, ? in a query string, or spaces. Wrap the whole argument in quotes:
flutter run --dart-define="SUPPORT_URL=https://example.com/help?topic=app&lang=en"A value may contain =. Only the first = splits the key from the value.
Passing values from a file
Long command lines are hard to read and easy to get wrong. --dart-define-from-file reads the pairs from a JSON file instead. Create config/dev.json:
{
"API_BASE_URL": "https://api.dev.example.com",
"ENABLE_LOGGING": "true"
}Then run:
flutter run --dart-define-from-file=config/dev.jsonThis has the same effect as passing each pair with --dart-define. The file is a flat object. Keep every value a string, as above, so the result matches what the command-line form produces. You can combine both options in one command. A common pattern is a shared file per environment plus one extra --dart-define for a value that changes per developer or per CI run.
One file per environment is easy to review and easy to select:
| File | Used for |
|---|---|
| `config/dev.json` | Local development against a development backend |
| `config/staging.json` | Pre-release testing |
| `config/prod.json` | Store builds |
Putting it together
A small, runnable program shows the whole path. This lib/main.dart reads the three keys used above and prints them.
import 'package:flutter/material.dart';
const apiBaseUrl = String.fromEnvironment(
'API_BASE_URL',
defaultValue: 'https://api.example.com',
);
const enableLogging = bool.fromEnvironment('ENABLE_LOGGING');
const timeoutSeconds = int.fromEnvironment('TIMEOUT_SECONDS', defaultValue: 30);
void main() {
runApp(const ConfigDemo());
}
class ConfigDemo extends StatelessWidget {
const ConfigDemo({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: Text(
'API: $apiBaseUrl\n'
'Logging: $enableLogging\n'
'Timeout: $timeoutSeconds s',
textAlign: TextAlign.center,
),
),
),
);
}
}Run it twice:
flutter run
flutter run --dart-define-from-file=config/dev.jsonThe first run shows the defaults. The second shows the development URL and Logging: true. Timeout stays at 30 in both runs because dev.json does not define TIMEOUT_SECONDS.
In the next chapter you will move these loose constants into a typed AppConfig class. For now the point is that the values arrive without any change to the Dart source.
Common errors
The value does not change after editing the file
Constants are baked in at compile time, so hot reload cannot update them. Hot reload only patches code in the running process. After you change a --dart-define value or the JSON file, stop the app and start it again. A hot restart is not always enough on every platform. A full flutter run is the safe choice.
The value is empty or has the default
Check these in order:
- Does the key in the command match the key in Dart exactly, including case?
- Did you pass the flag to the command that actually builds the app? A flag given to
flutter rundoes not carry over to a laterflutter build. - For booleans, is the value exactly
true? - Did your IDE start the app with its own run configuration that lacks the flag? The IDE chapter covers this.
Release builds from CI differ from local runs
Local runs use your terminal command. CI uses whatever its script says. Keep the --dart-define-from-file path in a script or build file that both use, so the command cannot drift.
Tests see only defaults
Tests are compiled separately. Pass the same flags to the test command:
flutter test --dart-define=ENABLE_LOGGING=trueWithout the flag, enableLogging is false in tests.
When to use --dart-define
Use it for settings that differ by build and are safe to be public: backend URLs, feature switches, log levels, analytics project identifiers that are meant to ship in the client, and a build label such as staging.
It is not a good fit when:
- The value must change after the app is installed. Use remote configuration or a server response.
- The value is secret. Anything compiled in can be recovered.
- The value is the app's name, application ID or icon. Those live in the native projects and are handled by flavors.
Exercise
You run flutter run --dart-define=ENABLE_LOGGING=True, but bool.fromEnvironment('ENABLE_LOGGING') returns false. Why, and what would you change? After you fix it, you edit config/dev.json while the app is running and press hot reload, and the value does not change. Why?
Show answer
bool.fromEnvironment returns true only for the exact text true, and True has a capital letter, so it falls back to the default false. Pass --dart-define=ENABLE_LOGGING=true. The second problem happens because --dart-define values are compile-time constants. They are fixed when the app is built, and hot reload does not rebuild them. Stop the app and run it again with the flags.