How can I listen to Firestore data only from server?


If we want to use .get() method to fetch data from server only, we can use the following:

FirebaseFirestore.instance.collection('users').get(GetOptions(source: Source.server))

Here we used GetOptions(source: Source.server) to avoid reading from cache; but what if I want listen from server only, for example I have the following code:



FirebaseFirestore.instance.collection('userss').doc('1').snapshots()listen((event) {  });

I tried the following:

FirebaseFirestore.instance.collection('userss').doc('1').snapshots()listen((event) { 
      if(!event.metadata.isFromCache) {
            print('this data from server');
            //as (!) condition it should outputs true if data was from server  
            // but as a test i turn off my wifi but it also outputs true .. How !??

How can I listen from server only? If it’s not possible, how can I at least detect if my data is from server or not?


There is no way with a listener to not get any cached data, but you can check in each snapshot’s metadata whether it is guaranteed to be up to date with the server by checking its fromCache property. From that link:

True if the snapshot was created from cached data rather than guaranteed up-to-date server data. If your listener has opted into metadata updates (via SnapshotListenOptions) you will receive another snapshot with fromCache set to false once the client has received up-to-date data from the backend.

If the property is false, the data is guaranteed to be up to date from the server.

The alternative would be to disable disk caching.

Answered By – Frank van Puffelen

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *