On this page13 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Add firebase_core
  4. 2. Initialize Before runApp
  5. 3. The FlutterFire CLI (recommended)
  6. 4. Writing the Options by Hand
  7. Code Examples
  8. Common Beginner Mistakes
  9. Best Practices
  10. Practice Questions
  11. Practice Answers
  12. Key Takeaways
  13. Full Code (Copy-Paste Reference)

Lecture 004: Initializing Firebase in Flutter

Category1: Firebase Setup
Lecture004 of 014
Estimated video length16 min
TargetFlutter 3.44 · Dart 3.12 · FlutterFire (latest)
LevelIntermediate

The native side is ready. Now the Dart side: we add firebase_core and start Firebase in main(): 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_core to the project
  • Call Firebase.initializeApp before runApp
  • Generate firebase_options.dart with flutterfire configure
  • Write FirebaseOptions by hand and know where each value comes from

1. Add firebase_core

bash
flutter pub add firebase_core

This adds the newest compatible version to pubspec.yaml (yours may be newer):

yaml
dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^5.0.0

firebase_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

dart
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}
LineWhy
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.

bash
dart pub global activate flutterfire_cli
firebase login              # needs the Firebase CLI: npm install -g firebase-tools
flutterfire configure

Pick your project and the platforms. It writes lib/firebase_options.dart (and the config files, if missing). Then:

dart
import 'firebase_options.dart';

await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

4. Writing the Options by Hand

Without the CLI, pass FirebaseOptions yourself:

dart
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:

OptionFirebase consoleIn the config file
apiKey-google-services.json → api_key.current_key; plist → API_KEY
appIdProject settings → Your apps → App ID (1:…:android:… / 1:…:ios:…)mobilesdk_app_id; plist → GOOGLE_APP_ID
messagingSenderIdProject settings → Project numberproject_number; plist → GCM_SENDER_ID
projectIdProject settings → Project IDproject_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

dart
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 add so versions stay compatible.
  • These keys identify the project, they are not passwords: protect data with Security Rules, not by hiding keys.

Practice Questions

  1. Why is main marked async?
  2. Which two lines must come before runApp?
  3. Which option is the "project number"?
  4. Which options differ between Android and iOS?

Practice Answers

  1. It must await Firebase.initializeApp().
  2. WidgetsFlutterBinding.ensureInitialized(); and await Firebase.initializeApp(...).
  3. messagingSenderId.
  4. apiKey and appId.

Key Takeaways

  • flutter pub add firebase_core, then initialize in an async main before runApp.
  • flutterfire configure generates DefaultFirebaseOptions.currentPlatform.
  • By hand: apiKey and appId per 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

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}'),
        ),
      ),
    );
  }
}