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

Flutter Web端Firebase Firestore报错:客户端离线无法获取文档

问题描述

使用FireFlutter在Firebase Firestore存储数据时,Web应用返回错误:

Error: [cloud_firestore/unavailable] Failed to get document because the client is offline.

复现步骤

  1. 创建新Firebase项目(无Analytics),以测试模式启用Firestore;添加test集合及同名文档并填入测试数据;在项目设置中添加新Web应用,将CDN配置复制到web/index.html的</body>标签前;
  2. 创建新Flutter空应用(VSCode);
  3. 添加firebase_core和cloud_firestore依赖;
  4. 终端执行fireflutter configure,关联上述Firebase项目,仅构建Web应用;
  5. 在main函数中添加初始化代码:
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
);

在MainApp构造函数中添加Firestore请求代码:

MainApp({super.key}) {
    FirebaseFirestore.instance
            .collection('test')
            .doc('test')
            .get()
            .then((value) {
                print(value);
            }).catchError((error) {
                print(error);
            });
    }
}
  1. 运行Flutter项目,调试控制台出现上述错误。

已知:网络正常,无广告拦截,移动端版本运行正常,推测问题出在配置文件,求排查方向。


排查方向

1. 检查Web端Firebase配置完整性

  • 确认web/index.html中的Firebase CDN配置参数(apiKey、authDomain、projectId等)与Firebase项目设置中Web应用的配置完全一致,无遗漏或拼写错误。
  • 排查配置冲突:fireflutter configure会在lib/firebase_options.dart生成Web端配置,若同时在index.html手动添加了CDN配置,可能导致冲突,建议只保留一种配置方式(优先用firebase_options.dart的配置,移除index.html中的手动配置)。

2. 验证Firestore权限规则

确认Firestore规则处于测试模式或包含允许Web端读取的条件,避免规则限制导致访问失败:

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

3. 调整Firestore请求时机

当前在MainApp构造函数中直接发起请求,Firebase可能未完成初始化。建议将请求移至Firebase初始化完成后,或StatefulWidget的initState方法中:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  // 初始化完成后发起请求
  FirebaseFirestore.instance
      .collection('test')
      .doc('test')
      .get()
      .then((value) => print(value))
      .catchError((error) => print(error));
  runApp(const MainApp());
}

4. 检查依赖版本兼容性

确认pubspec.yaml中firebase_core和cloud_firestore的版本为最新稳定版,执行flutter pub upgrade更新依赖,避免版本不匹配导致连接问题。

5. 验证Firebase Web应用状态

进入Firebase控制台,检查项目设置中的Web应用是否已正确注册,状态正常未被删除或禁用。

6. 查看浏览器详细错误信息

打开浏览器开发者工具(F12),查看Console和Network标签的详细错误提示(如CORS问题、请求状态码),定位具体连接障碍。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:09:27