Home > Net >  "No Firebase App '[DEFAULT]' has been created" despite "initializeApp()&quo
"No Firebase App '[DEFAULT]' has been created" despite "initializeApp()&quo

Time:10-09

I have the following workpiece of a starting widget:

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

import 'firebase_options.dart';
import 'apps/auth_app.dart';
import 'apps/main_app.dart';

class StartingWidget extends StatelessWidget {
  const StartingWidget({super.key});

  void _initFirebase() async {
    //WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();
  }

  void _addAuthStatusListener() {
    try {
      FirebaseAuth.instance.authStateChanges().listen((User? user) {
        if (user != null) {
          //runApp(const MainApp());
        } else {
          //runApp(const AuthApp());
        }
      });
    } catch (e) {
      print(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    _initFirebase();
    _addAuthStatusListener();
    return const Scaffold(
      body: CircularProgressIndicator(),
    );
  }
}

When I start it on an Android emulator, I get the "No Firebase App '[DEFAULT]' has been created" error at line

FirebaseAuth.instance.authStateChanges().listen((User? user) {

despite Firebase.initializeApp() was called before. Uncommenting

WidgetsFlutterBinding.ensureInitialized();

doesn't change anything.

CodePudding user response:

The reason is simple:

You have not waited for your _initFirebase() to complete, before you call _addAuthStatusListener(), which uses the Firebase app!

You also can't wait inside your build method (it has to render immediately and therefore can't be async), so I suggest you call _initFirebase() from inside _addAuthStatusListener() instead:

  @override
  Widget build(BuildContext context) {
//    _initFirebase();  // <- Remove this here!
    _addAuthStatusListener();
    return const Scaffold(
      body: CircularProgressIndicator(),
    );
  }

...

  void _addAuthStatusListener() async {  // Make async!
    await _initFirebase();  // <- Add _initFirebase() here, with "await"!
    try {
      FirebaseAuth.instance.authStateChanges().listen((User? user) {
        if (user != null) {
          //runApp(const MainApp());
        } else {
          //runApp(const AuthApp());
        }
      });
    } catch (e) {
      print(e.toString());
    }
  }

That should do it!

  • Related