Firestore check if cache data exists in flutter

Viewed 233

To reduce my document reads, I want to read firestore data from the cache:

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

This works. But if there doesn't exist cache data, how can I get an bool e.g cacheAvailable, to check if there exists the cache data or not?

1 Answers

You could try to fetch your data from your cache at first and if it fails get the data from the server.

As get() throws a FirebaseException if it tries to read from an unexisting cache using a try catch could work.

Code Sample

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;
}
Related