Search code examples
databaseflutterdartgoogle-cloud-firestoremobile-application

FutureBuilder vs Streambuilder


Hello everybody I want to fetch data from cloud firestore, but I am not quite sure which is more efficient to use in flutter. Should I use a streambuilder or a futurebuilder. I have red many posts, but I did not quite understand the differences. Could anybody tell me if I should use a streambuilder or a futurebuilder for getting data from firestore


Solution

  • Both StreamBuilder and FutureBuilder have the same behavior: they listen to changes on their respective object. And trigger a new build when they are notified of a new value.

    Eventually, the difference comes in how they listen to the async calls.

    FUTUREBUILDER

    It has one and only one response. A very common usage of flutter Future is during the http calls. What you can do with Future is to listen to it's state, that is, when it is done or had an error after the fetching data is done via Future

    STREAMBUILDER

    Stream on the other hand are Iterators, that it can assimilate different values, which will change over time. By using Stream, you will get each new values and also if it has some error or it is done with a success message

    Representation:

    switch (snapshot.connectionState){
       case ConnectionState.none: //do something
       break;
       case ConnectionState.waiting: //do something
       break;
       case ConnectionState.active: //do something
       break;
       case ConnectionState.done: //do somethin
       break;
    }   
    

    The above, will run every time, and updates the value if there is a change in the value coming from async data, even when you are using the app. It doesn't stop. And shows the data which you put inside a particular cases.

    NOW FINAL ANSWER

    If the above still doesn't hit you clearly, than, take a look at the below data:

    1. If your use case is to just get the data, and display it, like Total number of courses from a class from API. Then you can use FutureBuilder.
    2. What if, the data updates every second or minute, while you use the app, like upcoming posts in a blog or increase comments on the blog or increase in likes on the blog. It updates asynchronously at certain interval, in that case StreamBuilder is the best option.

    Bases upon the use case, you decide which one to use. Both of them are good in their own way. Follow the below articles, to get clarity: