Firestore 检查颤振中是否存在缓存数据

时间:2021-06-03 09:02:39

标签: flutter google-cloud-firestore

为了减少我的文档读取,我想从缓存中读取 firestore 数据:

result = await FirebaseFirestore.instance
          .collection(
              'path/toDocument')
          .get(cacheAvailable ? GetOptions(source: Source.cache));

这有效。但是如果不存在缓存数据,我怎样才能得到一个布尔值,例如 cacheAvailable,来检查是否存在缓存数据?

1 个答案:

答案 0 :(得分:0)

您可以先尝试从缓存中获取数据,如果失败,则从服务器获取数据。

因为 get() throws a FirebaseException if it tries to read from an unexisting cache 使用 try catch 可以工作。

代码示例

final collection = FirebaseFirestore.instance.collection('path/toDocument');
QuerySnapshot results;

try {
  // By default we try to read the data from the cache.
  results = await collection.get(GetOptions(source: Source.cache));
} on FirebaseException catch (e) {
  // Getting data from cache failed so we get the result from the server.
  results = await collection.get();
} catch (e) {
  throw e;
}