Flutter Display Data from API with Skelton Loading & Custom Error Message
--
Hello, today we will learn how to show the Skelton loading effect while fetching data also if there is any error how to show custom error message.
Let’s get started, what we try to do is fetching categories from API, for that we create CategoryService
and there is a method called getCategories
which return Future list of categories. Here we made a get
request to our API, if the response statusCode is 200 then we convert the response into a list of Categories.
It’s time to show the categories to our DiscoverScreen
.
As we know getCategories
return Future
, On flutter we already have a widget called FutureBuilder
which is utilizes the result of a Future to build itself. Inside the FutureBuilder we have to pass 2 parameter one is future
, where we need to pass the function that return a future, and the function is getCategories
. Another one is builder
. For now return a Text.
FutureBuilder
First I want to show a loading so that the user understand something going on under the hood. If the connectionState
is waiting then it shows the loading indicator right now which is a CircularProgressIndicator
.
For batter user experience instead of CircularProgressIndicator
we can use shimmer loading effect, Replace Center
widget with Expanded
and CircularProgressIndicator
with DiscoverCategoriesSkelton
.
If you want to learn how to create those shimmer effect check this👇
We are done with the loading now it’s time to show the categories, if snapshort has data then the data will be the list of categories, create a variable called _categories
then set the value to snapshort.data
. To display the categories inside an Expnaded
widget define ListView.builder
then sent the itemCount
to _categories.lenght
and itemBuilder
will be the NormalCategory
, (This NormalCategory
widget is created by me.)
We are almost done but what happened if there any error occurred? it’s better if you notify the user there is an error.
You may like 👇
Hope we learn something new, Check out our Premium E-commerce UI kit for flutter. 🔥👇
Thank you, have a great day!