Potato
Potato

Reputation: 539

When should i use streams vs just accessing the cloud firestore once in flutter?

I want to create a groups functionality for my app, so far when i set up the profile page of each user, i've used something like this :

DocumentReference documentReference =
               _firestore.collection("users").document("$email");
               await documentReference.get().then((DocumentSnapshot datasnapshot) {
                 if (datasnapshot.exists) {
                   displayName=datasnapshot.data['displayName'].toString();
                   bio=datasnapshot.data['bio'].toString();
                   print(bio);
                 }
                 else {
                   print("No such user");
                 }

This works but im thinking if i want to create groups and record the changes that different users may make then i should probably use a stream is that correct? Generally i am unsure when to use which if anyone could provide some insight?

Upvotes: 3

Views: 2193

Answers (2)

Tadas Petra
Tadas Petra

Reputation: 428

It all really comes down to whether you want the data to reload every time something changes in your database.

  • If you want it to update as it changes in your database, use a Stream (most likely with a StreamBuilder)

  • If you want it only to update when you reload the screen, use get() like you are in your example

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

The technical difference is that get only gets the document once, while the stream will get the current data straight away, and then continue to listen for changes.

I typically use a stream (or its underlying onSnapshot()) when I display the data straight into the UI, because that means the UI updates whenever the data changes. This is one of the really cool Firebase features, because it makes your UI reactive to the data changes. I use get() for things that I only need once, such as configuration data (although it's also very cool if you use a stream for that), client-side joins, etc.

Upvotes: 3

Related Questions