Search code examples
firebaseflutterdartgoogle-cloud-firestore

Firebase.initializeApp() gives error: Null check operator used on a null value


This is giving Null check operator used on a null value and pointing out the line Firebase.initializeApp(). The issue persists even after running flutter clean.

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

void main() async {
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ThePage(),
    );
  }
}

class ThePage extends StatelessWidget {
  const ThePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(          
    );
  }
}

Solution

  • You should add the WidgetsFlutterBinding.ensureInitialized(); inside the main function:

    void main() async {
      WidgetsFlutterBinding.ensureInitialized(); // Add this
    
      await Firebase.initializeApp();
      runApp(MyApp());
    }
    

    For Firebase initialization, access to the native code is needed using Flutter Platform Channels. For this, you need to ensure that Flutter engine binding is initialized.