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

Flutter初学者:Web端集成Firebase遇Assertion failed报错求助

解决Flutter Web集成Firebase时的断言失败问题

你遇到的firebase_core_web断言失败,大概率是Web端Firebase配置缺失或者初始化流程存在问题,以下是具体排查和解决步骤:

1. 补全Web端Firebase配置到index.html

Flutter Web集成Firebase和移动端逻辑不同,必须手动在web/index.html的<body>标签内添加Firebase SDK脚本及项目专属配置:

<!-- 在web/index.html的<body>标签内插入 -->
<script type="module">
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.0/firebase-app.js";
  const firebaseConfig = {
    apiKey: "你的项目API_KEY",
    authDomain: "你的项目AUTH_DOMAIN",
    projectId: "你的项目PROJECT_ID",
    storageBucket: "你的项目STORAGE_BUCKET",
    messagingSenderId: "你的项目MESSAGING_SENDER_ID",
    appId: "你的项目APP_ID"
  };
  initializeApp(firebaseConfig);
</script>

配置信息可从Firebase控制台「项目设置」→「添加应用」→「Web」路径下获取

2. 修正初始化与数据写入逻辑

调整代码确保初始化流程完整,同时适配Web端Firestore的数据存储规则:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized(); // 必须添加,保证Flutter绑定完成初始化
  await Firebase.initializeApp();
  runApp(MyApp());
  await createUser(name: 'imane'); // 添加await,避免异步操作未完成就结束
}

Future createUser({required String name}) async {
  final docUser = FirebaseFirestore.instance
      .collection('users')
      .doc('PyRPEmg2tjbcoqLf0pEH');
  final json = {
    'name': name,
    'age': 21,
    'birthday': DateTime(2001, 7, 28).toIso8601String(), // Web端Firestore不支持直接存储DateTime,转成ISO字符串
  };
  await docUser.set(json);
}

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

3. 检查依赖版本兼容性

确保pubspec.yaml中firebase_core和cloud_firestore版本匹配,示例如下:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^2.15.0
  cloud_firestore: ^4.8.3

执行flutter pub get更新依赖后重新运行项目。

4. 验证Firebase控制台配置

确认Firebase控制台已启用Cloud Firestore服务,且开发阶段的数据库规则允许写入操作(上线后需修改为安全规则):

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

内容的提问来源于stack exchange,提问作者imane imane

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:01:26