On this page13 sections
Lecture 004: Initializing Firebase in Flutter
| Category | 1: Firebase Setup |
| Lecture | 004 of 014 |
| Estimated video length | 16 min |
| Target | Flutter 3.44 · Dart 3.12 · FlutterFire (latest) |
| Level | Intermediate |
The native side is ready. Now the Dart side: we add
firebase_coreand start Firebase inmain(): first with the FlutterFire CLI, then by writing the options by hand so you know what each value is.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Practice Questions · Answers · Takeaways · Full Code
Prerequisites
Lectures 002–003: Gradle set up, both config files in place.
Learning Objectives
- Add
firebase_coreto the project - Call
Firebase.initializeAppbeforerunApp - Generate
firebase_options.dartwithflutterfire configure - Write
FirebaseOptionsby hand and know where each value comes from
1. Add firebase_core
flutter pub add firebase_coreThis adds the newest compatible version to pubspec.yaml (yours may be newer):
dependencies:
flutter:
sdk: flutter
firebase_core: ^5.0.0firebase_core is the base every other Firebase package needs. Add the others (firebase_auth,
firebase_messaging, …) the same way, with flutter pub add, so their versions match each
other: mixing versions from different years is what breaks builds.
2. Initialize Before runApp
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}| Line | Why |
|---|---|
async / Future<void> | initializeApp takes a moment; main must wait for it |
ensureInitialized() | Flutter's engine must be ready before plugins talk to Android/iOS |
await Firebase.initializeApp() | connects to the project in the config files |
With no options, Firebase reads google-services.json and GoogleService-Info.plist.
3. The FlutterFire CLI (recommended)
dart pub global activate flutterfire_cli
firebase login # needs the Firebase CLI: npm install -g firebase-tools
flutterfire configurePick your project and the platforms. It writes lib/firebase_options.dart (and the config
files, if missing). Then:
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);4. Writing the Options by Hand
Without the CLI, pass FirebaseOptions yourself:
import 'dart:io';
await Firebase.initializeApp(
options: FirebaseOptions(
apiKey: Platform.isIOS ? 'YOUR_IOS_API_KEY' : 'YOUR_ANDROID_API_KEY',
appId: Platform.isIOS ? 'YOUR_IOS_APP_ID' : 'YOUR_ANDROID_APP_ID',
messagingSenderId: 'YOUR_PROJECT_NUMBER',
projectId: 'your-project-id',
),
);Where each value comes from:
| Option | Firebase console | In the config file |
|---|---|---|
apiKey | - | google-services.json → api_key.current_key; plist → API_KEY |
appId | Project settings → Your apps → App ID (1:…:android:… / 1:…:ios:…) | mobilesdk_app_id; plist → GOOGLE_APP_ID |
messagingSenderId | Project settings → Project number | project_number; plist → GCM_SENDER_ID |
projectId | Project settings → Project ID | project_id; plist → PROJECT_ID |
apiKey and appId differ per platform: hence Platform.isIOS. The project number and ID are
the same for both.
Code Examples
Example 1: Prove It's Connected
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
final app = Firebase.app();
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Firebase')),
body: Center(
child: Text('Connected to ${app.options.projectId}'),
),
),
);
}
}The screen shows Connected to notify-demo-a1b2c: your project ID.
Common Beginner Mistakes
1. Forgetting ensureInitialized(): "Binding has not yet been initialized". It must come
before initializeApp.
2. Forgetting await: the app starts before Firebase is ready: "No Firebase App
'[DEFAULT]' has been created".
3. Mismatched package versions: copying firebase_auth: ^4.17.4 from an old guide next to
a new firebase_core: ^5.0.0 fails pub get: an old firebase_auth needs an old
firebase_core. Use flutter pub add for every Firebase package.
4. Android values on iOS: each platform has its own apiKey and appId.
Best Practices
- Prefer
flutterfire configure; rerun it whenever you add a platform or app. - Add every Firebase package with
flutter pub addso versions stay compatible. - These keys identify the project, they are not passwords: protect data with Security Rules, not by hiding keys.
Practice Questions
- Why is
mainmarkedasync? - Which two lines must come before
runApp? - Which option is the "project number"?
- Which options differ between Android and iOS?
Practice Answers
- It must
await Firebase.initializeApp(). WidgetsFlutterBinding.ensureInitialized();andawait Firebase.initializeApp(...).messagingSenderId.apiKeyandappId.
Key Takeaways
flutter pub add firebase_core, then initialize in anasync mainbeforerunApp.flutterfire configuregeneratesDefaultFirebaseOptions.currentPlatform.- By hand:
apiKeyandappIdper platform;messagingSenderId= project number. - Keep all Firebase packages on compatible versions.
Full Code (Copy-Paste Reference)
Everything the app needs up to and including this lecture. firebase_options.dart is
generated for you by flutterfire configure (Section 3): never hand-write it unless you're
using the manual FirebaseOptions approach from Section 4 instead.
lib/main.dart
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart'; // generated by `flutterfire configure`
Future<void> main() async {
// Must come first: plugins need the Flutter engine bound before they talk to native code.
WidgetsFlutterBinding.ensureInitialized();
// Connects to the project named in firebase_options.dart - must finish before runApp.
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
final app = Firebase.app();
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Firebase')),
// Proves the connection: shows this project's real project ID.
body: Center(
child: Text('Connected to ${app.options.projectId}'),
),
),
);
}
}