0

in this code I am able to retrieve data from Firestore once after I starts to run this page. Is it possible to make it run in real time where it will be able to get all the data from Firestore in real time?

Future getMarker() async{
    Firestore.instance.collection('markers').getDocuments().then((myData){
      if(myData.documents.isNotEmpty){
        for (int i = 0; i < myData.documents.length; i++){
          initMarker(myData.documents[i].data, myData.documents[i].documentID);
        }
      }
    });
  }

When i change the getDocuments() to snapshots() then method then() will give out an error stated that then() is not a Stream type. Or is there any approach to this. Thank you in advance.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84

1 Answers1

3

As explained in the doc, one option is to use the listen method of the Stream returned by the snapshots() method.

The doc also shows an example with another option: using a StreamBuilder which "helps automatically manage the streams state and disposal of the stream when it's no longer used within your app".

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • Thank you for the documentation. I have 1 more question. Is it possible to get the same functionality (retrieve data in real-time) without using a 'StreamBuilder'? Is there any alternative? or is there other documentation regarding this. Thank you so much for your kind answer. – randomstudent Jul 22 '21 at 08:49
  • 1
    Yes, you can use the `listen` method as mentioned at the top of the answer. See https://stackoverflow.com/questions/58942707/flutter-firestore-listen-for-document-changes – Renaud Tarnec Jul 22 '21 at 08:55