Sub topic 2
Connecting your Flutter app to Firebase
This chapter connects a Flutter project to a Firebase project, so later chapters can receive messages. It assumes you can build and run a Flutter app on an emulator or device, and that you know async/await and the basics of Dart isolates. It also assumes you have a Google account. The previous chapter showed how FCM routes a message to a device. This chapter sets up the client side of that route.
What "connected" means
A Flutter app is not linked to Firebase by a single setting. Three things must agree:
- A Firebase project exists, with an Android app and an iOS app registered in it.
- Each native app carries configuration that identifies it:
google-services.jsonon Android andGoogleService-Info.pliston iOS. - Your Dart code calls
Firebase.initializeAppwith matching options before it uses any Firebase service.
The FlutterFire CLI automates most of this. You still need to know what it generates, because a mismatch between these pieces causes most setup failures.
Install the tools
You need two command-line tools. The Firebase CLI signs you in and lists your projects. The FlutterFire CLI reads your projects and writes configuration into your Flutter app.
# Install the Firebase CLI (requires Node.js), then sign in
npm install -g firebase-tools
firebase login
# Install the FlutterFire CLI as a global Dart tool
dart pub global activate flutterfire_cliMake sure the Dart global bin directory (~/.pub-cache/bin on macOS and Linux) is on your PATH. Otherwise the shell reports flutterfire: command not found.
Add the packages
Two packages are needed for this tutorial. firebase_core starts Firebase and holds the connection to your project. firebase_messaging is the FCM client.
flutter pub add firebase_core firebase_messagingBoth packages are released together as part of FlutterFire, and their versions must be compatible. Add them with flutter pub add and let pub choose versions, instead of pinning one package to an old version by hand. If you add more Firebase packages later, such as firebase_auth, upgrade them together.
Run `flutterfire configure`
From the root of your Flutter project, run:
flutterfire configureThe command asks you to pick a Firebase project, or create one. It then asks which platforms to configure. Select Android and iOS. For each platform it registers an app in Firebase, using the identifiers already in your project, and writes files into your project.
| Platform | Identifier used | Native config file |
|---|---|---|
| Android | `applicationId` in `android/app/build.gradle` (or `.kts`) | `android/app/google-services.json` |
| iOS | Bundle identifier in the Xcode project | `ios/Runner/GoogleService-Info.plist` |
It also generates lib/firebase_options.dart. That file contains a class named DefaultFirebaseOptions with a currentPlatform getter. The getter returns the API key, app ID, project ID and sender ID for whichever platform the app is running on.
Recent versions of the CLI also add the Google services Gradle plugin to the Android build. Check your Android Gradle files after running the command. If the plugin is missing, builds succeed but the native Android side cannot read google-services.json.
The diagram shows how the pieces relate.
Initialize Firebase in `main`
Firebase must be initialized before any Firebase service is used. The example below also registers the background handler, which the later chapters on background messages explain in detail.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
// Must be a top-level function so it can run in its own isolate.
@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
debugPrint('Background message: ${message.messageId}');
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
runApp(const MaterialApp(home: Scaffold(body: Center(child: Text('FCM demo')))));
}Each line has a reason:
WidgetsFlutterBinding.ensureInitialized()is required becausemainisasyncand calls plugins beforerunApp. Plugins use platform channels, and those need the binding to exist first.await Firebase.initializeApp(...)must finish before you touchFirebaseMessaging.instance. Withoutawait, you create a race that fails only sometimes.FirebaseMessaging.onBackgroundMessageregisters the handler once, inmain, not inside a widget.
Why the handler initializes Firebase again
When a message arrives while the app is in the background or terminated, Flutter runs your handler in a separate isolate. An isolate is an independent Dart execution context. It has its own memory, so the Firebase.initializeApp call made in main is not visible there. The handler therefore initializes Firebase on its own.
Two rules follow from this:
- The handler must be a top-level function, or a static method. A closure or an instance method cannot be looked up by the engine when it starts the isolate.
- The
@pragma('vm:entry-point')annotation tells the compiler not to remove the function in release builds, where unused code is stripped (tree-shaken). Without it, background delivery can work in debug and silently fail in release.
Keep `firebase_options.dart` in sync
The identifiers in firebase_options.dart must match the native files. If you change the Android applicationId or the iOS bundle identifier, the registered Firebase app no longer matches your project. Run flutterfire configure again after any of these changes:
- You rename the application ID or bundle identifier.
- You add a new platform, such as web.
- You switch to a different Firebase project.
- You add build flavors (for example
devandprod) that each need their own Firebase app.
Flavors need extra care. A single firebase_options.dart points to one Firebase project. For separate environments, generate one options file per flavor with the --out and --android-package-name options of flutterfire configure, then choose the file at startup.
Firebase configuration values are identifiers, not secrets. The API key in firebase_options.dart is safe to commit, because access is controlled by Firebase security rules and by restrictions on the key. Do not commit service account keys. You will use those later for server-side sending.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `[core/no-app] No Firebase App '[DEFAULT]' has been created` | `initializeApp` not awaited, or not called before first use | Await it in `main`, before `runApp` |
| `flutterfire: command not found` | Dart global bin directory not on `PATH` | Add `~/.pub-cache/bin` to `PATH` |
| `No matching client found for package name` during an Android build | `google-services.json` was generated for a different `applicationId` | Align the ID and rerun `flutterfire configure` |
| iOS app launches, then fails to find the Firebase app | `GoogleService-Info.plist` is not in the Runner target | Add the file to the Runner target in Xcode |
| Background handler never runs in a release build | Missing `@pragma('vm:entry-point')` or handler is not top-level | Fix the handler declaration |
| Version solving fails during `pub get` | Firebase packages have incompatible versions | Upgrade all FlutterFire packages together |
Verify the connection
Run the app on an Android emulator and read the log. A successful start prints no Firebase errors, and debugPrint output from your own code appears. To confirm the link, temporarily print the project ID:
debugPrint('Firebase project: ${Firebase.app().options.projectId}');If this prints the project you chose in flutterfire configure, Dart and the native side agree. Remove the line when you are done.
Push delivery on iOS needs more setup, including APNs keys and Xcode capabilities. The next chapter covers it, and the app can start on iOS without it.
Exercise
Your app works in debug mode, but in a release build the background handler never runs, even though main calls FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler). The handler is a top-level function and calls Firebase.initializeApp. Name the most likely missing piece and explain why it matters only in release builds.
Show answer
The handler is missing the @pragma('vm:entry-point') annotation. Release builds use tree shaking to remove code that appears unused. The engine starts the background isolate by looking up the handler by name, so the compiler cannot see that it is used. Without the annotation, the function can be removed. Debug builds do not strip code, so the problem only shows up in release.
Exercise
You rename your Android applicationId from com.example.shop to com.example.shopapp. The build now fails with "No matching client found for package name". What do you do, and why does the error happen?
Show answer
Run flutterfire configure again, so it registers an Android app with the new ID and regenerates google-services.json and firebase_options.dart. The error happens because the existing google-services.json only lists a client for com.example.shop. The Google services Gradle plugin finds no entry that matches the new applicationId.