How to listen for document changes in Cloud Firestore using Flutter?

后端 未结 1 548
闹比i
闹比i 2020-12-08 23:33

I would like to have a listener method that checks for changes to a collection of documents if changes occur.

Something like:

import \'package:cloud         


        
相关标签:
1条回答
  • 2020-12-08 23:50

    Reading through cloud_firestore's documentation you can see that a Stream from a Query can be obtained via snapshots().

    For you to understand, I will transform your code just a tiny bit:

    CollectionReference reference = Firestore.instance.collection('planets');
    reference.snapshots().listen((querySnapshot) {
      querySnapshot.documentChanges.forEach((change) {
        // Do something with change
      });
    });
    

    You should also not run this in a transaction. The Flutter way of doing this is using a StreamBuilder, straight from the cloud_firestore Dart pub page:

    StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('books').snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (!snapshot.hasData) return new Text('Loading...');
        return new ListView(
          children: snapshot.data.documents.map((DocumentSnapshot document) {
            return new ListTile(
              title: new Text(document['title']),
              subtitle: new Text(document['author']),
            );
          }).toList(),
        );
      },
    );
    

    If you want to know any more, you can take a look at the source, it is well documented, where it is not self-explanatory.

    Also take note that I changed docChanges to documentChanges. You can see that in the query_snapshot file. If you are using an IDE like IntelliJ or Android Studio, it is also pretty easy to click through the files in it.

    0 讨论(0)
提交回复
热议问题