hypergogeta
hypergogeta

Reputation: 115

What is the difference between getDocuments() and snapshots() in Firestore?

I am a little confused about the difference between these two. My understanding is that getDocuments is a type of Future and seems to get the entire documents according to the query. while snapshots, on the other hand, is a type of Stream and, correct me if I'm wrong, I think it represents the results of the query? I need a more specific explanation of this issue. I will include some code snippets as an example for more clarification

getDocuments()

getUserById(String userId) async {
    return await _firestore.collection("users").where("userId", isEqualTo: userId).getDocuments();
}

snapshots()

getUserById(String userId) async {
    return await _firestore.collection("users").where("userId", isEqualTo: userId).snapshots();
}

So what's the difference?

Upvotes: 5

Views: 6276

Answers (2)

Jitesh Mohite
Jitesh Mohite

Reputation: 34180

getDocuments():

It's used to provide data once. Cloud Firestore contains collections and inside these collections, you have documents that may contain subcollections or fields mapped to a value. To retrieve any of the doc fields to used it in widget this is used.

snapshots():

It will be called on every data change in your document query. For this StreamBuilder must be used to fetch fields as modified. In short, it will do the job of setState() where it gives you the response for every modification so that UI can be updated.

Upvotes: 2

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

When you call getDocuments(), the Firestore client gets the documents matching the query from the server once. Since this may take some time it returns a Future<QuerySnapshot>.

When you call snapshots() the Firestore client gets the documents, and then keeps watching the database on the server for changes that affect your query. So if document is written in the users collection that affects your query, your code gets called again. So this returns a stream of QuerySnapshot.

In both cases the results for the entire query are in the QuerySnapshot object.

I highly recommend reading the Firestore documentation on getting data once and on listening realtime updates. While they don't contain Flutter examples, the explanation in there applies equally to the Flutter libraries.

Upvotes: 9

Related Questions