You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter应用报错No Firebase App '[Default]',回滚代码仍未解决

Flutter应用启动抛出No Firebase App '[Default]'错误排查方案

问题描述

此前正常运行的Flutter应用,现在每次启动都会抛出No Firebase App '[Default]'错误。项目已关联GitHub,下载之前能正常运行的版本可正常工作,但将主仓库回滚至该提交后错误再次出现,通过Git对比文件未发现差异,无法定位问题原因。

错误日志

════════ 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)
════════════════════════════════════════════════════════════════════════════════

核心代码(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 bgColor = Color.fromRGBO(20, 20, 20, 1);
const Color themeColor = Color.fromARGB(255, 107, 65, 114);
late ThemeData currentTheme;
const Color defTextColor = Colors.white;
dynamic loadingCircle;
late Icon shareIcon;

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");

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

排查与解决方法

1. 检查Firebase配置文件完整性

确认Android项目的android/app/google-services.json和iOS项目的ios/Runner/GoogleService-Info.plist是否存在且配置正确。若这两个文件在.gitignore中,回滚代码时不会自动恢复,需手动将正常版本的配置文件复制到对应目录。

2. 清理项目缓存并重建

执行以下命令清理Flutter缓存:

flutter clean
flutter pub get
  • Android平台:删除android/build和android/app/build目录,重新执行flutter run
  • iOS平台:删除ios/Pods目录和ios/Podfile.lock,执行pod install后再运行项目

3. 调整Firebase初始化逻辑

将Firebase初始化移至main函数中,确保在启动应用前完成初始化,避免FutureBuilder可能的状态异常:
修改main函数:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  Hive.registerAdapter(UserSettingsAdapter());
  await Hive.openBox<UserSettings>("user_settings");
  // 提前初始化Firebase
  await Firebase.initializeApp();
  runApp(Phoenix(child: const HomePage()));
}

简化Setup组件:

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

  @override
  Widget build(BuildContext context) {
    final user = FirebaseAuth.instance.currentUser;
    if (user != null) {
      return user.emailVerified ? const MainUIView() : const VerifyEmailView();
    } else {
      return const LoginView();
    }
  }
}

4. 锁定依赖版本

检查pubspec.lock中firebase_core和firebase_auth的版本是否与正常运行版本一致,若不一致,在pubspec.yaml中指定固定版本:

dependencies:
  firebase_core: ^x.x.x  # 替换为正常运行的版本号
  firebase_auth: ^x.x.x  # 替换为正常运行的版本号

执行flutter pub get更新依赖。


内容的提问来源于stack exchange,提问作者Sunken In Time

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 06:10:32