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

Flutter无网络连接时如何从缓存获取Firestore查询数据

核心原因

Firestore 默认的get()请求逻辑为优先尝试拉取服务器最新数据,仅在网络请求失败时才回退读取本地缓存,你当前的写法没有指定数据源,所以不会主动走离线缓存。

修复方案

给get()方法传入GetOptions参数,显式指定读取数据源为缓存即可:

UserRef.doc(FirebaseAuth.instance.currentUser.uid).get(
  // 强制从本地缓存读取数据
  const GetOptions(source: Source.cache)
).then((DocumentSnapshot snapshot) {
  if(snapshot.exists){
    print('this is exists');
    userExistence = true;
    setState(() {});
  }
});

兼顾性能与数据新鲜度的优化方案

如果你希望既实现打开应用秒加载,又能同步拿到最新数据,可以采用「先读缓存渲染、再拉服务器更新」的逻辑:

// 先读缓存快速更新UI,减少用户等待时间
UserRef.doc(FirebaseAuth.instance.currentUser.uid).get(
  const GetOptions(source: Source.cache)
).then((cacheSnapshot) {
  if(cacheSnapshot.exists){
    userExistence = true;
    setState(() {});
  }
});

// 异步拉取服务器最新数据,拿到后更新UI和本地缓存
UserRef.doc(FirebaseAuth.instance.currentUser.uid).get(
  const GetOptions(source: Source.server)
).then((serverSnapshot) {
  if(serverSnapshot.exists){
    // 这里可以覆盖缓存数据对应的本地状态
    userExistence = true;
    setState(() {});
  }
});

注意:首次打开应用还没有生成缓存时,Source.cache的请求会返回不存在,此时依赖后续服务器请求结果即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 16:30:02