Sub topic 10
Per-flavor Firebase and service config files
This chapter assumes you can already run a flavor from the terminal and that your Android productFlavors and iOS schemes exist and build. Here you will attach a separate backend project to each flavor. Firebase is the example, because the same pattern applies to any service that ships a configuration file.
Why each flavor needs its own service config
A dev build should never write analytics events, crash reports, or test users into the production Firebase project. Each Firebase project has its own app registrations, and each registration is tied to an application ID (Android) or bundle ID (iOS). Your dev flavor uses an ID with a .dev suffix, so it is a different app in Firebase's eyes. It needs its own registration and its own config file.
Two files carry the connection details:
| Platform | File | Contains |
|---|---|---|
| Android | `google-services.json` | Project ID, app ID, API key, package name |
| iOS | `GoogleService-Info.plist` | Project ID, app ID, API key, bundle ID |
If a flavor ships with the wrong file, the app may fail at startup or, worse, run fine and send data to the wrong project. The goal is to make the correct file follow the flavor automatically.
The overall picture
The --flavor flag selects a Gradle product flavor on Android and an Xcode scheme on iOS. Each platform then picks its own config file by a different mechanism.
Android: one file per source set
The Google Services Gradle plugin looks for google-services.json in several places for each build variant. The most specific location wins. Putting one file inside each flavor's source set is the simplest layout:
android/app/src/dev/google-services.json
android/app/src/prod/google-services.jsonApply the plugin in android/app/build.gradle.kts. Flutter projects created with recent templates already declare the plugin versions in settings.gradle.kts, so you only need to add the plugin id to the app module:
// android/app/build.gradle.kts
plugins {
id("com.android.application")
id("kotlin-android")
id("dev.flutter.flutter-gradle-plugin")
id("com.google.gms.google-services")
}The plugin checks that the package_name inside the JSON matches the variant's application ID. With applicationIdSuffix = ".dev", the dev file must contain a client entry for com.example.myapp.dev. A mismatch fails the build with a message like "No matching client found for package name". That failure is useful, since it stops you from shipping the wrong file.
Register the apps first
In the Firebase console, create (or choose) a project per environment. Then add an Android app to each project using the exact application ID of that flavor, and download its JSON file. Doing this in the wrong order is the most common cause of the package-name error above.
iOS: copy the plist during the build
iOS has no automatic per-flavor lookup. A common approach is to store the plists outside the Runner target and copy the right one into the built app with a Run Script build phase.
Use a layout like this. Keep the plists out of the Runner group, so Xcode does not bundle them all:
ios/config/dev/GoogleService-Info.plist
ios/config/prod/GoogleService-Info.plistIn Xcode, select the Runner target, open Build Phases, add a New Run Script Phase, and paste:
#!/bin/bash
set -e
case "${CONFIGURATION}" in
*-dev) SRC="${PROJECT_DIR}/config/dev/GoogleService-Info.plist" ;;
*-prod) SRC="${PROJECT_DIR}/config/prod/GoogleService-Info.plist" ;;
*)
echo "error: no Firebase plist for configuration ${CONFIGURATION}"
exit 1
;;
esac
cp "${SRC}" "${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/GoogleService-Info.plist"This relies on the configuration naming that Flutter requires for flavors: Debug-dev, Release-dev, Profile-dev, and the same three for prod. If your configuration names differ from <mode>-<flavor>, flutter run --flavor dev will not find the scheme's configuration in the first place. The *) branch fails the build on an unknown configuration instead of silently shipping no file.
Order and sandboxing
Move the new script phase below "Copy Bundle Resources" so that nothing overwrites the file afterwards. If your project has User Script Sandboxing enabled (ENABLE_USER_SCRIPT_SANDBOXING = YES), the script may be blocked from reading config/. Either set it to NO for the Runner target or declare the plists as input files of the phase.
Initializing Firebase in Dart
There are two ways to give Firebase its settings. Pick one per project and stay consistent.
Option 1: native files, no options in Dart
With the native files in place, the platform plugins can read them at startup. Dart only needs:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'app.dart';
import 'app_config.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp(
config: AppConfig(
apiBaseUrl: 'https://api.dev.example.com',
enableLogging: true,
),
));
}This keeps Dart free of project identifiers. The cost is that the Dart code and the native files can only be checked together at run time, and the approach covers only Android and iOS.
Option 2: generated `FirebaseOptions` per flavor
The FlutterFire CLI generates a Dart file with the same settings. Run it once per environment and write each result to its own file:
flutterfire configure \
--project=myapp-dev \
--out=lib/firebase_options_dev.dart \
--android-app-id=com.example.myapp.dev \
--ios-bundle-id=com.example.myapp.dev
flutterfire configure \
--project=myapp-prod \
--out=lib/firebase_options_prod.dart \
--android-app-id=com.example.myapp \
--ios-bundle-id=com.example.myappEach generated file defines a class named DefaultFirebaseOptions. Import both with prefixes and choose by flavor:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/services.dart' show appFlavor;
import 'firebase_options_dev.dart' as dev;
import 'firebase_options_prod.dart' as prod;
FirebaseOptions optionsForFlavor() {
switch (appFlavor) {
case 'dev':
return dev.DefaultFirebaseOptions.currentPlatform;
case 'prod':
return prod.DefaultFirebaseOptions.currentPlatform;
default:
throw StateError('Unknown or missing flavor: $appFlavor');
}
}
Future<void> initFirebase() {
return Firebase.initializeApp(options: optionsForFlavor());
}Throwing on an unknown flavor is deliberate. A silent fallback to production data is the failure you are trying to prevent. If you use one entrypoint per environment, you can skip appFlavor and import only the matching options file in main_dev.dart and main_prod.dart.
Generated options work on platforms that have no native file, such as web, and they make the Dart side explicit. You can still keep the native files too. If both exist and disagree, you get confusing behavior, so check that each pair points at the same project.
Other services follow the same pattern
Firebase is one case of a general rule: anything that identifies a backend per environment should change with the flavor.
- Google Maps keys. On Android, set a
manifestPlaceholdersentry in each product flavor and reference it fromAndroidManifest.xml. On iOS, use a per-configuration.xcconfigvariable referenced fromInfo.plist. - Sentry, Crashlytics and analytics. Pass the DSN or project ID with
--dart-define-from-file, as you do for the API URL. - Auth redirects and deep links. URL schemes and associated domains often need a per-flavor value, because two apps with different IDs cannot share one scheme safely.
Use native files when the SDK reads them itself. Use Dart-level config when you control the initialization call.
CI: files that are not in the repository
Whether to commit the config files is a team decision. They hold identifiers and API keys that are restricted by app ID, not passwords, so many teams commit them. If yours does not, restore them in CI before the build. Store each file as a base64 secret and decode it:
echo "$GOOGLE_SERVICES_DEV" | base64 --decode > android/app/src/dev/google-services.json
echo "$GOOGLE_SERVICES_PROD" | base64 --decode > android/app/src/prod/google-services.json
echo "$GOOGLE_PLIST_DEV" | base64 --decode > ios/config/dev/GoogleService-Info.plist
echo "$GOOGLE_PLIST_PROD" | base64 --decode > ios/config/prod/GoogleService-Info.plistCommon errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "No matching client found for package name" | JSON registered for a different application ID | Add an Android app with the flavor's exact ID and download the file again |
| Dev build reports to the prod project | Wrong file in the source set, or fallback branch in Dart | Check each file's `project_id`, and throw on unknown flavors |
| iOS crashes at launch with "could not find GoogleService-Info.plist" | Run Script missing, wrong phase order, or sandboxing blocked the copy | Check the phase runs after resource copying and read the build log |
| Script fails with "no Firebase plist for configuration" | Configuration names do not match `<mode>-<flavor>` | Rename configurations to `Debug-dev` and so on |
| Push notifications work on one flavor only | APNs key or FCM setup missing in the other Firebase project | Configure each project separately |
Exercise
Your dev flavor uses applicationIdSuffix = ".dev" and the base ID com.example.myapp. You copied the production google-services.json into android/app/src/dev/ to save time. What happens at build time, and what is the correct fix?
Show answer
The Google Services plugin compares the package_name in the JSON with the variant's application ID, com.example.myapp.dev. The production file only has a client for com.example.myapp, so the build fails with "No matching client found for package name". The fix is to add an Android app with the ID com.example.myapp.dev in the dev Firebase project, download its google-services.json, and place it in android/app/src/dev/.
Exercise
Why does the appFlavor switch in optionsForFlavor throw on an unknown value instead of returning the production options as a default?
Show answer
If the flavor is missing or misspelled (for example when the app was built without --flavor, so appFlavor is null), a production default would silently connect a dev or test build to the production project. That pollutes real analytics and data. Throwing makes the mistake visible immediately at startup.
Exercise
Write the case pattern a Run Script would use to select the plist for the iOS staging flavor, and say what configuration names it must match.
Show answer
Add *-staging) SRC="${PROJECT_DIR}/config/staging/GoogleService-Info.plist" ;; to the case "${CONFIGURATION}" block. It matches the configurations Debug-staging, Release-staging and Profile-staging, which are the <mode>-<flavor> names Flutter expects for the staging flavor.