Sub topic 4
One entrypoint per environment
This chapter assumes you can run flutter run and flutter build, and that you know the AppConfig class from the previous chapter. You should also know that a Flutter app starts at a main() function. The chapter shows how to give each environment its own main file and how to select it with the -t flag.
What an entrypoint is
An entrypoint is the Dart file that contains the main() function the app starts from. By default the Flutter tool compiles lib/main.dart. The -t flag (long form --target) tells the tool to compile a different file instead.
Dart compiles only the code that can be reached from the target file. A file such as lib/main_prod.dart is not part of a dev build unless something imports it. Each build contains the settings of one entrypoint, and the other environments' entrypoint files add nothing to it.
Why use separate entrypoints
You already have two ways to choose settings: --dart-define values and the --flavor flag. A separate entrypoint file is a third option, and it has its own trade-offs.
| Approach | Where the values live | Strength | Weakness |
|---|---|---|---|
| `--dart-define-from-file` | A JSON file passed on the command line | Values stay out of Dart source and CI can inject them | A wrong or missing file silently falls back to defaults |
| One entrypoint per environment | A `main_*.dart` file in the repository | Values are in version control and checked by the compiler | One more file for each environment |
| `appFlavor` | The `--flavor` value | Needs no extra Dart code | Gives you only a name, not a set of settings |
Entrypoints suit settings that are not sensitive and that you want reviewed in pull requests. They also suit startup behavior that differs by environment. Examples are a crash reporter that is switched off in dev, or a debug banner that appears only in staging. A command-line value can't express that kind of difference, but a different main() can.
The structure
Keep one shared app and put the differences into thin entrypoint files:
lib/
app.dart // MyApp, the shared root widget
app_config.dart // AppConfig
bootstrap.dart // shared startup code
main_dev.dart // dev settings, calls bootstrap
main_staging.dart // staging settings, calls bootstrap
main_prod.dart // prod settings, calls bootstrapThe diagram shows how a command reaches the shared code.
Only the entrypoint chosen with -t runs. The dotted lines are the files the command did not select.
Writing the files
Start with the config class. It is a plain class with a const constructor, so each entrypoint can build its value at compile time.
// lib/app_config.dart
class AppConfig {
const AppConfig({
required this.apiBaseUrl,
required this.enableLogging,
});
final String apiBaseUrl;
final bool enableLogging;
}The shared widget receives the config through its constructor:
// lib/app.dart
import 'package:flutter/material.dart';
import 'app_config.dart';
class MyApp extends StatelessWidget {
const MyApp({super.key, required this.config});
final AppConfig config;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MyApp',
home: Scaffold(
appBar: AppBar(title: const Text('MyApp')),
body: Center(child: Text('API: ${config.apiBaseUrl}')),
),
);
}
}Startup code that every environment needs goes into one function. If each main_*.dart repeated it, the copies would drift apart.
// lib/bootstrap.dart
import 'package:flutter/material.dart';
import 'app.dart';
import 'app_config.dart';
void bootstrap(AppConfig config) {
WidgetsFlutterBinding.ensureInitialized();
if (config.enableLogging) {
debugPrint('Starting with API ${config.apiBaseUrl}');
}
runApp(MyApp(config: config));
}Each entrypoint then states only what is different:
// lib/main_dev.dart
import 'app_config.dart';
import 'bootstrap.dart';
void main() {
bootstrap(const AppConfig(
apiBaseUrl: 'https://api.dev.example.com',
enableLogging: true,
));
}// lib/main_prod.dart
import 'app_config.dart';
import 'bootstrap.dart';
void main() {
bootstrap(const AppConfig(
apiBaseUrl: 'https://api.example.com',
enableLogging: false,
));
}main_staging.dart has the same shape with its own URL. Add any per-environment startup steps in the entrypoint before the bootstrap call, or pass them to bootstrap as arguments.
Running and building with -t
Pass the entrypoint with -t to every command that compiles the app:
flutter run -t lib/main_dev.dart
flutter build apk --release -t lib/main_prod.dart
flutter build ios --release -t lib/main_prod.dartThe flag works the same way for run, build, and test with integration tests. Without -t the tool compiles lib/main.dart. If that file does not exist, the command fails. If it does exist, you get that file's behavior and no error, which is a quiet way to ship the wrong settings.
Combining -t with flavors
-t and --flavor are independent. -t picks the Dart code, and --flavor picks the native build variant, meaning the Android product flavor or the iOS scheme. Nothing checks that they agree, so this command compiles without complaint:
flutter run --flavor dev -t lib/main_prod.dartIt produces an app with the dev ID and name that calls the production API. The next section shows one way to catch that.
Guarding against a mismatch
Chapter material on appFlavor is covered separately, but it helps here. appFlavor from package:flutter/services.dart holds the value of --flavor, or null when none was given. You can compare it with the config in the entrypoint's startup path:
// lib/bootstrap.dart (extended)
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'app.dart';
import 'app_config.dart';
void bootstrap(AppConfig config, {required String expectedFlavor}) {
WidgetsFlutterBinding.ensureInitialized();
assert(
appFlavor == expectedFlavor,
'Entrypoint expects flavor "$expectedFlavor" but the build used "$appFlavor".',
);
if (config.enableLogging) {
debugPrint('Starting $expectedFlavor with API ${config.apiBaseUrl}');
}
runApp(MyApp(config: config));
}Each entrypoint then passes its own name, for example bootstrap(config, expectedFlavor: 'dev'). An assert runs only in debug builds. A release build skips it, so a mismatch there still needs a CI check or a code review.
Common errors
- Hot restart ignores a new target. The target is fixed when you start the session. After you switch to another entrypoint, stop the run and start it again.
- A
mainthat never runs. Only the target'smain()is called. Amain()in an imported file does nothing. - Missing
-tin CI. A build script that works locally from a saved IDE configuration can lose the flag in CI and produce an app fromlib/main.dart. Keep the full command in a script or a Makefile target. - Xcode builds. Building from Xcode directly does not pass your
-tflag. If you need that, set theFLUTTER_TARGETuser-defined build setting in the matching build configuration, or build from the terminal. - Duplicated startup logic. If a fix to initialization has to be made in three
main_*files, move it intobootstrap. - Non-const values. A value such as
DateTime.now()inside aconst AppConfig(...)expression is a compile error. Keep config values to literals.
When to choose entrypoints
Use separate entrypoints when environments differ in startup behavior, or when you want the settings reviewed as code. Use --dart-define-from-file when values change often or when CI supplies them. Many projects combine both: the entrypoint chooses the environment, and a defines file supplies the few values that must not live in source. Whichever you pick, give every environment one documented command, and run that command from a script so nobody has to remember the flags.
Exercise
You run flutter build apk --release --flavor prod in CI and the app calls the dev API. Your repository has lib/main.dart (which wraps the dev config), lib/main_dev.dart and lib/main_prod.dart. What went wrong, and what is the fix?
Show answer
The command has no -t flag, so the tool compiled the default lib/main.dart, which contains the dev config. --flavor prod only selected the native Android flavor (application ID, app name), not the Dart code. Add -t lib/main_prod.dart to the command. To prevent the problem, put the full command in a script, and add a check such as an assert on appFlavor or a CI step that verifies the entrypoint name.
Exercise
Why is it better for main_dev.dart and main_prod.dart to call a shared bootstrap(config) function than to each call runApp directly?
Show answer
Startup steps such as WidgetsFlutterBinding.ensureInitialized() and logging setup are identical for every environment. Keeping them in one function means a change is made once. If each entrypoint repeated them, one copy could be fixed while another stayed wrong, and the environments would behave differently for reasons unrelated to configuration.