Sub topic 3
Wrapping settings in an AppConfig class
This chapter assumes you can pass values with --dart-define and --dart-define-from-file, and that you know Dart classes and const constructors. You will gather the scattered String.fromEnvironment calls into one typed class, add validation, and hand the class to the rest of the app. You will also see the errors that appear most often when you do this.
Why a class instead of loose constants
Reading String.fromEnvironment('API_BASE_URL') directly in an HTTP client works. It stops working as the app grows:
- The key name is a string literal. A typo in one file silently returns the default value.
- Every file that reads a key must repeat its default.
- Tests cannot replace the values, because the values are compiled into the program.
- Nothing checks that a required value was supplied.
An AppConfig class fixes all four. The keys appear in one place, the fields are typed, and the rest of the app receives a plain object that a test can build by hand.
The basic class
This version reads the two keys from the earlier example and keeps their defaults.
class AppConfig {
const AppConfig({
required this.apiBaseUrl,
required this.enableLogging,
});
final String apiBaseUrl;
final bool enableLogging;
static const AppConfig fromEnvironment = AppConfig(
apiBaseUrl: String.fromEnvironment(
'API_BASE_URL',
defaultValue: 'https://api.example.com',
),
enableLogging: bool.fromEnvironment('ENABLE_LOGGING'),
);
}Two details matter here.
- The constructor is
const, and so is the static field.String.fromEnvironmentandbool.fromEnvironmentare only guaranteed to read--dart-definevalues when they are evaluated as compile-time constants. - The class holds no logic that depends on the running app. It is a bag of values, which keeps it easy to construct in tests.
What each fromEnvironment constructor returns
| Constructor | Default when the key is missing | Notes |
|---|---|---|
| `String.fromEnvironment` | `''` unless `defaultValue` is given | Every define arrives as text. |
| `bool.fromEnvironment` | `false` unless `defaultValue` is given | Only the text `true` or `false` is understood. Any other text, such as `yes` or `1`, gives `defaultValue`. |
| `int.fromEnvironment` | `0` unless `defaultValue` is given | Text that is not a valid integer gives `defaultValue`. |
The bool behavior catches people out. With --dart-define=ENABLE_LOGGING=yes the app builds without complaint and logging stays off.
Failing early on missing values
A default URL such as https://api.example.com is dangerous for a required setting. If someone forgets the define, the app builds and talks to the wrong server. For required values, use an empty default and an assert in the constructor.
class AppConfig {
const AppConfig({
required this.environment,
required this.apiBaseUrl,
required this.enableLogging,
}) : assert(
apiBaseUrl != '',
'API_BASE_URL was not provided. '
'Pass --dart-define=API_BASE_URL=... or --dart-define-from-file.',
);
final String environment;
final String apiBaseUrl;
final bool enableLogging;
static const AppConfig fromEnvironment = AppConfig(
environment: String.fromEnvironment('APP_ENV', defaultValue: 'dev'),
apiBaseUrl: String.fromEnvironment('API_BASE_URL'),
enableLogging: bool.fromEnvironment('ENABLE_LOGGING'),
);
bool get isProd => environment == 'prod';
/// Joins the base URL and a path such as '/users'.
Uri endpoint(String path) => Uri.parse('$apiBaseUrl$path');
}An assert inside a const constructor is checked when the compiler evaluates the constant. If API_BASE_URL is missing, the build fails with your message, even in a release build. This is stronger than the usual runtime-only assert.
Some things cannot live inside the const initializers:
Uri.parseis not a constant expression, so keep the URL as aStringand parse it in a getter or method, asendpointdoes.- The
environmentfield is aStringhere. You can compare it in getters such asisProd, which run at runtime and are not restricted.
The endpoint method concatenates strings on purpose. Uri.parse('https://api.dev.example.com/v1').resolve('/users') returns https://api.dev.example.com/users and drops /v1, because a path that starts with / replaces the whole base path. Keep the base URL without a trailing slash and give paths a leading slash.
Matching the JSON file
The keys in the file must equal the keys in fromEnvironment, character for character.
{
"APP_ENV": "dev",
"API_BASE_URL": "https://api.dev.example.com",
"ENABLE_LOGGING": "true"
}Values in the file are strings, so write "true" and not true. Check what your Flutter version does with an unquoted JSON boolean before relying on it.
Handing the config to the app
Create the config once, at the top, and pass it down. Do not let widgets and services reach for the static field themselves. A class that takes its config in its constructor can be tested with any config.
import 'package:flutter/material.dart';
import 'app_config.dart';
void main() {
runApp(const MyApp(config: AppConfig.fromEnvironment));
}
class ApiClient {
const ApiClient(this.config);
final AppConfig config;
Uri usersUri() => config.endpoint('/users');
}
class MyApp extends StatelessWidget {
const MyApp({super.key, required this.config});
final AppConfig config;
@override
Widget build(BuildContext context) {
final client = ApiClient(config);
return MaterialApp(
title: 'Config demo',
home: Scaffold(
appBar: AppBar(title: Text('Environment: ${config.environment}')),
body: Center(child: Text(client.usersUri().toString())),
),
);
}
}Run it with:
flutter run --dart-define-from-file=config/dev.jsonThe app bar shows Environment: dev and the body shows https://api.dev.example.com/users.
For a deeper tree you can expose the config through an InheritedWidget or your dependency-injection package of choice. The rule stays the same: build it once, then pass it in.
Testing without defines
Tests should not depend on command-line flags. Build the config directly:
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/app_config.dart';
import 'package:my_app/main.dart';
void main() {
test('usersUri joins base URL and path', () {
const config = AppConfig(
environment: 'test',
apiBaseUrl: 'http://localhost:8080',
enableLogging: false,
);
expect(const ApiClient(config).usersUri().toString(),
'http://localhost:8080/users');
});
}Replace my_app with your package name. The test never touches AppConfig.fromEnvironment. If a test did read it without --dart-define, the assert above would stop compilation, which is a useful signal that the test depends on the build setup.
Common errors
- Changing a define and seeing no effect. Values are fixed when the app is compiled. Hot reload and hot restart do not recompile with new defines, so stop and rerun
flutter run. - A key typo.
API_BASEURLinstead ofAPI_BASE_URLgives the default value, not an error. The empty default plusassertturns this into a build failure. - Calling
String.fromEnvironmentwithoutconst. It may silently return the default value. Keep every call inside aconstexpression. - Putting secrets in the config. The values are compiled into the app and can be extracted. A later chapter covers this limit.
- Reading the config inside widgets through the static field. This works but ties the widget to the build flags and makes widget tests awkward.
Where this fits
AppConfig holds the data. It does not decide which values to use. That choice comes from the command line, from a JSON file, or from a dedicated entrypoint, which the next chapter covers. In that approach the entrypoint builds an AppConfig with literal values instead of calling fromEnvironment. The rest of the app does not change, because it only ever sees an AppConfig.
Exercise
A teammate runs flutter run --dart-define=ENABLE_LOGGING=1 and finds that logging is still off, even though AppConfig uses bool.fromEnvironment('ENABLE_LOGGING'). Why, and how do you fix the command?
Show answer
bool.fromEnvironment only understands the text true and false. Any other text, including 1, gives the default value, which is false. Use --dart-define=ENABLE_LOGGING=true, or set "ENABLE_LOGGING": "true" in the JSON file.
Exercise
You add API_TIMEOUT_SECONDS to AppConfig as an int. Write the field initializer in fromEnvironment so that the value is 30 when the define is missing, and name one problem with how int.fromEnvironment handles bad input.
Show answer
apiTimeoutSeconds: int.fromEnvironment('API_TIMEOUT_SECONDS', defaultValue: 30). If the define is text that is not a valid integer, such as abc, int.fromEnvironment does not report an error. It returns the default value, so a mistake in the value goes unnoticed unless you add an assert on the range.