Flutter Display Data from API with Skelton Loading & Custom Error Message

The Flutter Way
4 min readMay 29, 2022

--

Preview

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.

Video Tutorial

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.

CategoryService

It’s time to show the categories to our DiscoverScreen.

DiscoveryScreen.dart

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.

show a loading
Loading Preview

For batter user experience instead of CircularProgressIndicator we can use shimmer loading effect, Replace Center widget with Expanded and CircularProgressIndicator with DiscoverCategoriesSkelton.

Skelton loading effect
DiscoverCategoriesSkelton
Preview with Skelton Loading

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.builderthen sent the itemCount to _categories.lenght and itemBuilder will be the NormalCategory, (This NormalCategory widget is created by me.)

Show caregories
Preview

We are almost done but what happened if there any error occurred? it’s better if you notify the user there is an error.

Show Error Message
Error preview

You may like 👇

DiscoverScreen Complete Code ❤️

Hope we learn something new, Check out our Premium E-commerce UI kit for flutter. 🔥👇

Thank you, have a great day!

Thumbnail

--

--

The Flutter Way

Want to improve your flutter skill? Join our channel, learn how to become an expert flutter developer and land your next dream job!