Learn/Deployment & DevOps/Flavors & Environment Config

Flavors & Environment Config

Manage dev, staging, and production environments with flavors

7 min~5 min read+50 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Environment Isolation Model
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary
  9. 9. Architecture Lens
  10. 10. Interview Angle

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Flavors & Environment Configuration

Professional Flutter apps require separate configurations for development, staging, and production environments. Flavors (also called build variants) let you change the app name, icon, API base URL, and Firebase project depending on the environment. This prevents accidentally shipping debug configurations to production and ensures each environment is properly isolated.

dart
1// ── ENVIRONMENT CONFIGURATION ──
2enum Environment { dev, staging, prod }
3
4class AppConfig {
5 final Environment environment;
6 final String apiBaseUrl;
7 final String appName;
8 final bool enableLogging;
9
10 const AppConfig({
11 required this.environment,
12 required this.apiBaseUrl,
13 required this.appName,
14 required this.enableLogging,
15 });
16
17 static late final AppConfig instance;
18
19 static void initialize(Environment env) {
20 switch (env) {
21 case Environment.dev:
22 instance = const AppConfig(
23 environment: Environment.dev,
24 apiBaseUrl: 'https://dev-api.example.com',
25 appName: 'MyApp DEV',
26 enableLogging: true,
27 );
28 case Environment.staging:
29 instance = const AppConfig(
30 environment: Environment.staging,
31 apiBaseUrl: 'https://staging-api.example.com',
32 appName: 'MyApp STG',
33 enableLogging: true,
34 );
35 case Environment.prod:
36 instance = const AppConfig(
37 environment: Environment.prod,
38 apiBaseUrl: 'https://api.example.com',
39 appName: 'MyApp',
40 enableLogging: false,
41 );
42 }
43 }
44}
45
46// ── ENTRY POINTS PER FLAVOR ──
47// lib/main_dev.dart
48void main() {
49 AppConfig.initialize(Environment.dev);
50 runApp(const MyApp());
51}
52
53// lib/main_staging.dart
54void main() {
55 AppConfig.initialize(Environment.staging);
56 runApp(const MyApp());
57}
58
59// lib/main_prod.dart
60void main() {
61 AppConfig.initialize(Environment.prod);
62 runApp(const MyApp());
63}
64
65// Run with:
66// flutter run -t lib/main_dev.dart
67// flutter run -t lib/main_staging.dart
68// flutter run -t lib/main_prod.dart
dart
1// ── ANDROID FLAVORS (android/app/build.gradle.kts) ──
2// android {
3// flavorDimensions += "environment"
4// productFlavors {
5// create("dev") {
6// dimension = "environment"
7// applicationIdSuffix = ".dev"
8// resValue("string", "app_name", "MyApp DEV")
9// }
10// create("staging") {
11// dimension = "environment"
12// applicationIdSuffix = ".stg"
13// resValue("string", "app_name", "MyApp STG")
14// }
15// create("prod") {
16// dimension = "environment"
17// resValue("string", "app_name", "MyApp")
18// }
19// }
20// }
21
22// ── USING --dart-define FOR CONFIG ──
23// flutter run --dart-define=ENV=dev --dart-define=API_URL=https://dev.api.com
24
25// Access in Dart:
26const env = String.fromEnvironment('ENV', defaultValue: 'dev');
27const apiUrl = String.fromEnvironment('API_URL');
28
29// ── .env FILES WITH envied PACKAGE ──
30// pubspec.yaml: envied: ^0.5.0, envied_generator (dev), build_runner (dev)
31
32// .env
33// API_KEY=sk_live_abc123
34// BASE_URL=https://api.example.com
35
36// lib/env.dart
37// @Envied(path: '.env')
38// abstract class Env {
39// @EnviedField(varName: 'API_KEY', obfuscate: true)
40// static const String apiKey = _Env.apiKey;
41//
42// @EnviedField(varName: 'BASE_URL')
43// static const String baseUrl = _Env.baseUrl;
44// }
45
46// Run: dart run build_runner build
47// Access: Env.apiKey, Env.baseUrl
dart
1// ── FIREBASE PER FLAVOR ──
2// Use different Firebase projects per environment:
3//
4// android/app/src/dev/google-services.json
5// android/app/src/staging/google-services.json
6// android/app/src/prod/google-services.json
7//
8// ios/config/dev/GoogleService-Info.plist
9// ios/config/staging/GoogleService-Info.plist
10// ios/config/prod/GoogleService-Info.plist
11
12// Or use FlutterFire CLI:
13// flutterfire configure --project=myapp-dev --out=lib/firebase_options_dev.dart
14// flutterfire configure --project=myapp-prod --out=lib/firebase_options_prod.dart
15
16// In main_dev.dart:
17void main() async {
18 WidgetsFlutterBinding.ensureInitialized();
19 await Firebase.initializeApp(
20 options: DefaultFirebaseOptions.currentPlatform, // from firebase_options_dev.dart
21 );
22 AppConfig.initialize(Environment.dev);
23 runApp(const MyApp());
24}
25
26// ── LAUNCH CONFIGURATIONS (VS Code) ──
27// .vscode/launch.json
28// {
29// "configurations": [
30// {
31// "name": "Dev",
32// "request": "launch",
33// "type": "dart",
34// "program": "lib/main_dev.dart",
35// "args": ["--flavor", "dev"]
36// },
37// {
38// "name": "Prod",
39// "request": "launch",
40// "type": "dart",
41// "program": "lib/main_prod.dart",
42// "args": ["--flavor", "prod"]
43// }
44// ]
45// }

Flavor Best Practices

💡 Flavor Best Practices

Always use separate Firebase projects per environment so test data never mixes with production. Add the .env file to .gitignore so secrets are not committed to version control. Use the envied package with obfuscate set to true for API keys to prevent easy extraction from the compiled binary.

Environment Isolation Model

Flavor setup is most effective when isolation is complete:

  • Separate backend endpoints, auth credentials, and storage buckets per environment.
  • Unique app identifiers prevent accidental overwrite between variants.
  • Feature flags can differ by environment for staged rollouts.
  • Logging verbosity and debug tools stay disabled in production.

Complete isolation prevents accidental production impact from test workflows.

Flavor Operations Checklist

  • Each flavor has dedicated main entry point and config constants.
  • Sensitive keys are sourced from secure build-time injection.
  • Firebase and backend resources are mapped correctly per flavor.
  • CI jobs build and test every supported flavor path.
  • Release candidate verification confirms production flavor only.

This Lesson In Simple Words

Manage dev, staging, and production environments with flavors. Flutter lets you build one app codebase and run it on Android, iOS, web, and desktop.

Your level focus

Operate with production and interview-level clarity.

One practical habit

After each setup step, run a minimal app to confirm your environment before moving ahead.

Deep Understanding Guide

Why this lesson matters

Strong fundamentals in setup and platform model save hours of confusion when projects become bigger.

Study flow for better retention

  1. Tie each concept to scale, failure handling, and delivery strategy.
  2. Think like a team lead: if a new developer joins today, can they run this project in 20 minutes?
  3. If you can defend trade-offs under constraints, your understanding is strong.

Common Mistakes To Avoid

  • Skipping environment checks and debugging setup issues too late.
  • Memorizing commands without understanding what each tool does.
  • Treating Flutter as only a mobile framework and ignoring web/desktop impact.
  • Moving to advanced widgets before understanding widget tree basics.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Create a fresh starter app and run it on one emulator and one browser target.
  • Write a one-paragraph explanation of Flutter architecture in simple words.
  • Draw a basic widget tree for a login screen on paper.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "Why should you use separate environments for dev, staging, and production?".

Quick Glossary

  • build: The method that describes UI for the current state.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Project setup quality becomes architecture quality later, because broken foundations spread quickly.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Interview Angle

Practice this prompt: How does Flutter render UI without relying on native UI bridge components?

Strong answer structure: context, decision, trade-off, and measurable outcome.

Lesson Completion Checklist

  • I can explain "Flavors & Environment Config" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Skipping environment checks and debugging setup issues too late.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

Why should you use separate environments for dev, staging, and production?

Separate environments ensure that test data, debug settings, and development API keys never reach production users. Each environment has its own database, API endpoints, and credentials.

How do you run a specific flavor entry point in Flutter?

The -t flag (target) specifies which main file to use as the entry point. Combined with --flavor for native flavor support.

What does the envied package do?

The envied package reads .env files at build time and generates Dart code with optional obfuscation, making API keys harder to extract from compiled binaries.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue