How to use Provider to handle responses from an API

Atri Das
2 min readApr 6, 2020

First of all, a solid confession: I am not a pro Flutter developer. It is my first blog on Flutter. Currently, I am learning the Provider Pattern for State Management and I tried to implement the same technique to one of my apps, News App, where I managed the State with SetState(){} and that was a spaghetti of code. So I tried to manage the state with Provider.

In this blog, I will be sharing the information which I got to know during the learning phase.

Here is the UI of the app which I built earlier. But in this blog, I will just focus on state management.

Here is a preview of the mechanism which I used in the previous version:

Managing state in the UI is a bad approach. Now comes the concept of State Management. Here I will try to manage the state with Provider.

Till now I learned about 3 kinds of Provider:

  1. ChangeNotifierProvider
  2. StreamProvider
  3. FutureProvider

As we can understand, we are fetching an API and we have to wait till it gives us a result. So it will return something in the future. So I chose FutureProvider.

So let’s get the provider package from https://pub.dev/packages/provider in our pubspec.yaml

At first, let us create a model in which manner we will receive our data.

Now we will create a NewsList.class

And now we will write our Business Logic

The loadUserData() method will return a List type of NewsModel in the future. In that method loadAsset() method is called which gives a JSON response from the URL and later with the 3 lines of mechanism, we are getting users which is nothing but a List type of NewsModel.

That’s it. Now we have to fetch it in the UI.

In the main.dart, FutureProvider is being called. The loadUserData() method is called in the create section and the context will move down to its child which is the BusinessNewsScreen().

Now let us come to the BusinessNewsScreen().

And, we are getting the value with

var news = Provider.of<List<NewsModel>>(context);

Here are some links where you can get in-depth knowledge of the Provider.

--

--

Atri Das

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