In this blog, we will learn when should we use FutureBuilder?
Future Builder removes boilerplate code.Using this we don’t need to write the same code again and again.
Let’s say you want to fetch some data from the backend on a page launch and also you wanna show a loader until data comes.
You may also check our flutter app development services.
Tasks for ListBuilder:-
- For this we are having two state variables i.e. getData and isLoading.
- on the screen launch set isLoading = true and based on this ,we will show the loader on the screen.
- When data arrived from the backend,set data with what you get from the backend and also set isLoading=false(obviously inside setstate).
- We need to have a if-else in widget creation.if isLoading is true,then show the Loader else show the data.On failure ,show error message.
Tasks for FutureBuilder:-
- Give the async task in future of FutureBuilder.
- We have different connectionstate(loading,active(streams),done).Based on these connectionState.show the message.
- Based on data(snapshot.hasError) show the view.
Pros of FutureBuilder:-
Now you can differentiate easily from above explanation of using ListBuilder and FutureBuilder.
Let’s take a short summary for the pros of Future Builder.
- We don’t need to use tow state variables and also no need to use setState.
- FutureBuilder gives us Reactive programming(it will take care of updating the view on data arrival).
Let’s take code example for more clarity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
FutureBuilder<String>( future:_fetchData, //async work builder:(BuildContext context,AsyncSnapshot<String>snapshot) { switch(snapshot.connectionState){ case ConnectionState.waiting: return Text("Loading....."); default: if(snapshot.hasError) return Text("Error": ${snapshot.error}); else return Text("Result": ${snapshot.data}); }, } ) |
This was all about the usage of Future Builder.I hope my blog gives me more clarity it.
For more details, you can refer to the official doc of flutter here.
For more interesting blogs check out here – https://mobikul.com/blog/
Hope this blog helped you with a better understanding for when should we use FutureBuilder?
Thanks for reading.😇