Home > Software engineering >  No Firebase App '[Default]' error but firebase is already initialized
No Firebase App '[Default]' error but firebase is already initialized

Time:09-28

Every time I try to run my flutter app that has been previously working, I get No Firebase App '[Default]' error. I have this project connected to my GitHub and I downloaded a different version and it seemed to work fine, so I thought to revert my main repo to that commit, and then the same thing happened again. I did a git compare and found no differences in the files, which made it hard to find out what was happening.

Error caught in the debug console

════════ Exception caught by widgets library ═══════════════════════════════════
The following FirebaseException was thrown building FutureBuilder<FirebaseApp>(dirty, state: _FutureBuilderState<FirebaseApp>#d30ed):
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

The relevant error-causing widget was
FutureBuilder<FirebaseApp>
package:mynotes/main.dart:105
When the exception was thrown, this was the stack
#0      MethodChannelFirebase.app
package:firebase_core_platform_interface/…/method_channel/method_channel_firebase.dart:193
#1      Firebase.app
package:firebase_core/src/firebase.dart:53
#2      FirebaseAuth.instance
package:firebase_auth/src/firebase_auth.dart:38
#3      Setup.build.<anonymous closure>
package:mynotes/main.dart:110
#4      _FutureBuilderState.build
package:flutter/…/widgets/async.dart:615
#5      StatefulElement.build
package:flutter/…/widgets/framework.dart:4919
#6      ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4806
#7      StatefulElement.performRebuild
package:flutter/…/widgets/framework.dart:4977
#8      Element.rebuild
package:flutter/…/widgets/framework.dart:4529
#9      BuildOwner.buildScope
package:flutter/…/widgets/framework.dart:2659
#10     WidgetsBinding.drawFrame
package:flutter/…/widgets/binding.dart:891
#11     RendererBinding._handlePersistentFrameCallback
package:flutter/…/rendering/binding.dart:370
#12     SchedulerBinding._invokeFrameCallback
package:flutter/…/scheduler/binding.dart:1146
#13     SchedulerBinding.handleDrawFrame
package:flutter/…/scheduler/binding.dart:1083
#14     SchedulerBinding._handleDrawFrame
package:flutter/…/scheduler/binding.dart:997
#18     _invoke (dart:ui/hooks.dart:151:10)
#19     PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:308:5)
#20     _drawFrame (dart:ui/hooks.dart:115:31)
(elided 3 frames from dart:async)
════════════════════════════════════════════════════════════════════════════════

Error on my screen

Main.dart

import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_phoenix/flutter_phoenix.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:mynotes/constants/routes.dart';
import 'package:mynotes/services/auth/auth_service.dart';
import 'package:mynotes/services/auth/auth_user.dart';
import 'package:mynotes/services/hive/boxes.dart';
import 'package:mynotes/services/hive/settings_service.dart';
import 'package:mynotes/themes/themes.dart';
import 'package:mynotes/views/forgot_password_view.dart';
import 'package:mynotes/views/login_view.dart';
import 'package:mynotes/views/notes/create_update_note_view.dart';
import 'package:mynotes/views/main_ui.dart';
import 'package:mynotes/views/register_view.dart';
import 'package:mynotes/views/settings_view.dart';
import 'package:mynotes/views/verify_email_view.dart';
import "dart:developer" as devtools show log;

const double sizedBoxWidth = 300;
const double sizedBoxHeight = 300;
late Color textColor;
// const Color themeColor = Color.fromRGBO(85, 111, 68, 1);
const Color bgColor = Color.fromRGBO(20, 20, 20, 1);
const Color themeColor = Color.fromARGB(255, 107, 65, 114);
//const Color bgColor = Color.fromARGB(255, 31, 31, 31);
late ThemeData currentTheme;
const Color defTextColor = Colors.white;
dynamic loadingCircle;
late Icon shareIcon;
//Creates an empty sized box for sapce
SizedBox createSpace(double height) {
  return SizedBox(height: height);
}

SizedBox createSpaceWidth(double height, double width) {
  return SizedBox(
    height: height,
    width: width,
  );
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  Hive.registerAdapter(UserSettingsAdapter());
  await Hive.openBox<UserSettings>("user_settings");

  //Allows for app restart for themes
  runApp(Phoenix(child: const HomePage()));
}

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

  @override
  Widget build(BuildContext context) {
    final box = Boxes.getUserSettings();
    //Making sure a first time user has the theme setting
    if (box.containsKey("defaultKey")) {
      if (box.get("defaultKey", defaultValue: UserSettings("Purple"))!.theme ==
          "Green") {
        currentTheme = MyThemes.greenTheme;
        textColor = Colors.white;
      } else if (box.get("defaultKey")!.theme == "White") {
        currentTheme = MyThemes.lightTheme;
        textColor = Colors.black;
      } else {
        currentTheme = MyThemes.purpleTheme;
        textColor = Colors.white;
      }
    } else {
      box.put("defaultKey", UserSettings("Purple"));
      currentTheme = MyThemes.purpleTheme;
      textColor = Colors.white;
    }

    return MaterialApp(
      title: 'Flutter Demo',
      theme: currentTheme,
      debugShowCheckedModeBanner: false,
      home: const Setup(),
      routes: {
        loginRoute: (context) => const LoginView(),
        registerRoute: (context) => const RegisterView(),
        notesRoute: (context) => const MainUIView(),
        verifyRoute: (context) => const VerifyEmailView(),
        createOrUpdateNoteRoute: (context) => const CreateUpdateNoteView(),
        forgotPasswordViewRoute: (context) => const ForgotPasswordView(),
        settingsRoute: (context) => const SettingsView(),
        homeRoute: (context) => const HomePage(),
      },
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: Firebase.initializeApp(),
      builder: (context, snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.done:
            final user = FirebaseAuth.instance.currentUser;
            if (user != null) {
              if (user.emailVerified) {
                return const MainUIView();
              } else {
                devtools.log(user.toString());
                return const VerifyEmailView();
              }
            } else {
              return const LoginView();
            }

          default:
            if (Platform.isIOS) {
              loadingCircle = const CupertinoActivityIndicator();
              shareIcon = const Icon(Icons.ios_share);
            } else {
              loadingCircle = const CircularProgressIndicator();
              shareIcon = const Icon(Icons.share);
            }
            return Scaffold(
              body: Center(
                child: SizedBox(
                  width: sizedBoxWidth,
                  height: sizedBoxHeight,
                  child: Center(child: loadingCircle),
                ),
              ),
            );
        }
      },
    );
  }
}

CodePudding user response:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  //initialize it here
  await Firebase.initializeApp(),
  await Hive.initFlutter();
  Hive.registerAdapter(UserSettingsAdapter());
  await Hive.openBox<UserSettings>("user_settings");
  //Allows for app restart for themes
  runApp(Phoenix(child: const HomePage()));
}

CodePudding user response:

  static Future<FirebaseApp?> initialize() async {
    await Firebase.initializeApp(
        options: kIsWeb
            ? const FirebaseOptions(
                appId: appId,
                authDomain: authDomain,
                apiKey: apiKey,
                databaseURL: databaseURL,
                projectId: projectId,
                storageBucket: storageBucket,
                messagingSenderId: messagingSenderId,
                measurementId: measurementId,
              )
            : null);
    return Firebase.app();
  }

call it.

main() async{
await ClassName.initialize();
}

I am using it like that and it works fine.

  • Related