Sub topic 1
Why one app needs several environments
Prerequisites
You should be comfortable with these before you start:
- Writing Dart and building a Flutter app with
flutter runandflutter build. - Basic familiarity with the
android/andios/folders. - The idea of an API base URL, the address your app calls for data.
Why separate environments matter
An app usually runs against several backends. A development backend lets you test freely. A production backend serves real users. Each one needs a different API URL, logging setting, and sometimes a different app name, so developers can install both on one phone.
Hard-coding these values means editing source code before every build, which is error-prone. Flutter offers compile-time values instead.
Passing configuration with --dart-define
A compile-time value is fixed when the app is built. Pass it with --dart-define:
flutter run --dart-define=API_BASE_URL=https://api.dev.example.comRead it with String.fromEnvironment. The call must be const, and the default applies when the value is missing.
const apiBaseUrl = String.fromEnvironment(
'API_BASE_URL',
defaultValue: 'https://api.example.com',
);For many keys, store them in a JSON file and pass it with --dart-define-from-file=config/dev.json.
Wrapping settings in an AppConfig class
Reading raw strings across the code spreads the configuration everywhere. A typed class keeps it in one place:
class AppConfig {
const AppConfig({required this.apiBaseUrl, required this.enableLogging});
final String apiBaseUrl;
final bool enableLogging;
}> Keep this class free of secrets. Values passed with --dart-define are stored in the compiled app.
One entrypoint per environment
An entrypoint is the main() function that starts the app. Create one file per environment, such as lib/main_dev.dart, and select it with -t.
import 'package:flutter/material.dart';
import 'app.dart';
import 'app_config.dart';
void main() {
runApp(const MyApp(
config: AppConfig(
apiBaseUrl: 'https://api.dev.example.com',
enableLogging: true,
),
));
}Run the dev build with:
flutter run -t lib/main_dev.dartCheck your understanding
Exercise
Why is a value passed with --dart-define not suitable for an API secret key?
Show answer
The value is compiled into the app binary, so anyone who extracts the app can read it. Store secrets on a server, or fetch them at runtime after authentication.