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

Flutter中Firestore无网络连接时如何获取DocumentSnapshot?

经过多次尝试后我来到此处咨询,根据官方文档说明:

Firestore默认支持离线能力,读写数据时Firestore会使用本地数据库自动与服务端同步。用户离线时Cloud Firestore功能仍可正常使用,恢复网络连接后会自动处理数据同步。

我在initState()中编写了如下代码:

FirebaseFirestore.instance
        .collection(AppString.FB_USERS)
        .doc(FirebaseAuth.instance.currentUser.uid)
        .get()
        .then((DocumentSnapshot documentSnapshot) {
      if (documentSnapshot.exists) {
        print('Document exists on the database');
      }
      else{
        print('Document not exists on the database');
      }
    });

该代码联网时运行正常,但关闭网络连接、将应用从后台最近任务列表移除后重新打开,离线状态下代码无法正常运行。

修正方案1

@override
  void initState() {
    super.initState();
    FirebaseFirestore.instance.collection(AppString.FB_USERS).doc(FirebaseAuth.instance.currentUser.uid).get(GetOptions(source: Source.cache)).then((DocumentSnapshot documentSnapshot) {
      if (documentSnapshot.exists) {
        print('Document exists on the database');
      }
    });

如果仅使用get()而非get(GetOptions(source: Source.cache)),将始终无法返回数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 11:06:02