Fetch Cloud Firestore Data Stream in your Flutter App using StreamProvider & add data to Cloud Firestore[A Beginner’s guide]

Atri Das
3 min readApr 8, 2020

Hi there, I am here once again to share my experience with StreamProvider. Currently, I am learning the Provider pattern and today I have learned how Cloud Firestore Data can be fetched in a Flutter app with the help of Provider and how data can be added to Cloud Firestore. So, I will be sharing with you all the things that I have learned till now and if you find any better approach please let me know. I will be glad to know about them and honestly, I am still in the learning phase.

Firstly, let me show you the database.

And the data will be shown like this:

Now let’s get the provider and cloud_firestore package in our pubspec.yaml.

It is time to create the model class => user_model.dart . As we will receive only the name and age. So, only 2 fields are needed.

Now comes the firebase operation part. Let’s create a class named firebase_services.dart. We will do all our operations related to the Firebase here. Firstly I will discuss the two methods.

The getUserList() is a Stream of List type of UserModel. We are fetching the document located in the FireStore collection named ‘user’. After getting the snapShot of the data, we are mapping and sending the JSON to UserModel.fromJson().

Now comes the addUser() section:

We have to send a Map type of object to Cloud Firestore. I have already defined the fields in our collection as these two fields are available- ‘name’ and ‘age’. We can add many more fields as per our requirement and I gave those values to make it simple as an example. You can put the value from any widget. To put the data we are going to the collection then creating a document with a String(you can put any string value there and if you don’t give the value it will generate a random id in the FireStore collection). Then call the setData() method and put our map object.

All done. Now let’s put it all together in the firestore_services.class

Now comes the UI part where the parsed data will be shown. In order to do so, the Provider should be called in the ancestor widget, So here it is:

So we are getting the Stream here; firebaseServices.getUserList() will give us the user List. Next, comes the ViewUserPage() widget.

So here we are getting the Provider instance and printing the data from this. That’s it. Now when the FloatingActionButton() will be pressed, the addUser() method will be called and the data will be sent to Cloud Firestore. So after clicking the FloatingActionButton, we will be getting the following:

That is all for today. Here is the link to my previous blog about FutureProvider.

--

--

Atri Das

Developer Student Clubs Alumni by Google Developers || Flutter Developer and Explorer