flutterfire
flutterfire copied to clipboard
[cloud_firestore📚] How can I know if a QuerySnapshot exists in cache?
Hello, how can I know if a QuerySnapshot
exists in cache? Since if I use GetOptions(source: Source.cache,)
to obtain a list of documents, it gives us an empty list when it does not exist. But with this we cannot know if it is because there are no documents online or only in the cache. With DocumentSnapshot
this does not happen since it throws us an exception which is much more practical to handle this situation.
Hi @hortigado, what platform(s) do you see this behavior on?
@danagbemava-nc Hi, on flutter.
Hi @hortigado, by platform(s), I mean, android
, iOS
, or web
?
Android, is same for all
Hi @hortigado, there https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/SnapshotMetadata/isFromCache.html
Does it suit your needs?
Yes, something like that, although that only works in real time, at least it throws an exception if it does not exist in the cache and not an empty list that causes this inconvenience.
hi @hortigado There isn't a clear way in Firestore to find out if a QuerySnapshot is cached. Nevertheless, by looking at its metadata, you may determine if the QuerySnapshot is from the cache or not. Firestore will attempt to collect the data from the local cache before attempting to retrieve it using GetOptions(source: Source.cache). It will return an empty QuerySnapshot if the data is not present in the cache. Should the data be found in the cache, it will return the data together with metadata identifying it as cached content. To find out if the QuerySnapshot is from the cache, you can examine its metadata. The metadata property of the QuerySnapshot holds details about the data's original source.
If you have accessed the data (i.e. queried it), Firestore will contain it in cache (provided you have allowed cache). You can get events when the data is from cache or not using 'includeMetadataChanges'
FirebaseFirestore.instance
.collection('your-collection')
.where('hello', isEqualTo: 'world')
.snapshots(includeMetadataChanges: true)
.listen((event) {
print('hasPendingWrites: ${event.metadata.hasPendingWrites}');
print('isFromCache: ${event.metadata.isFromCache}');
});
This will fire when metadata also updates i.e. if the data has been written to the server, this event.metadata.isFromCache
will be false
.