Flutter Web端Firebase初始化报错:未创建DEFAULT应用
解决Flutter Web Firebase初始化错误
问题分析
你遇到的FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created错误,是因为Web端Firebase初始化逻辑冲突:你同时在main.dart中用Dart代码初始化Firebase,又在index.html中用JS脚本重复初始化,且两者执行顺序未协调,导致Flutter代码执行时Firebase还未完成正确初始化。
解决方案
1. 移除index.html中的Firebase JS初始化代码
删掉index.html底部的这段脚本:
<script type="module"> // Import the functions you need from the SDKs you need import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js"; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration const firebaseConfig = { apiKey: "<-------- My API Key---------->", authDomain: "<-------- Auth Domain---------->", projectId: "<-------- Project ID---------->", storageBucket: "<-------- Storage Bucket---------->", messagingSenderId: "<-------- Messaging SenderId---------->", appId: "<-------- App Id---------->" }; // Initialize Firebase const app = initializeApp(firebaseConfig); </script>
2. 确保Web平台配置已加入firebase_options.dart
如果你的firebase_options.dart中没有Web平台的配置,重新运行以下命令生成完整的跨平台配置:
flutterfire configure
运行时选择Web平台,工具会自动将Web的Firebase配置写入firebase_options.dart,这样DefaultFirebaseOptions.currentPlatform在Web端就能正确获取配置。
3. 确认初始化顺序(当前逻辑已正确,可跳过)
你的main.dart初始化顺序没问题,保持现有逻辑即可:
void main() async { WidgetsFlutterBinding.ensureInitialized(); await ScreenUtil.ensureScreenSize(); // 先初始化Firebase,再调用依赖Firebase的方法 await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); await initNotification(); await GetStorage.init(); runApp(const MyApp()); }
完成以上步骤后,重新运行Flutter Web项目,错误即可解决。
内容的提问来源于stack exchange,提问作者Istiak Ahmed
相关产品推荐
相关产品推荐

