Handling REST API calls with Flutter provider — Example Code

Krishan Madushanka
3 min readMay 13, 2022

--

In this article I am going to take you through the steps on how to handle a simple GET request using flutter http library and provider library which is used for state management. When talking about the state management mechanisms available with flutter(Bloc, Riverpod, Mobx, GetX, Redux), provider has become a popular and more stable mechanism in flutter developers’ community.

Prerequisites
General unserstanding about flutter(how to create a flutter project,widgets etc.)
Understanding about what are REST apis.
Understanding about what is state management and why we need it.

  1. Create project and add dependencies

Create a new flutter project and add provider and http library dependencies under dependencies in pubspec.yaml file where we add third party dependencies in flutter applications. Run following command inside project root directory from terminal(mac/linux) or command prompt(windows) to download libraries to the peoject.

flutter pub get

2. Create folder structure

Create above folder structure inside lib directory where we add different files.

3. Create Service class

Create a file called data_service.dart inside services directory and add the above code. Here we use http library to make the GET request and we need import ‘dart:convert’ to map our json response to the model that we will create next.

4. Create the model class

The json response that we get by calling the above api (https://jsonplaceholder.typicode.com/comments/1) is,

{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "Eliseo@gardner.biz",
"body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
}

Now we should create our model class to map this. For this you can easily generate model class from this website by using our json response. Just paste the json response there and click ‘Generate Dart’.

5. Create provider

Create data_provider.dart inside providers directory and add above code. Here we use the mixin ChangeNotifier from provider libarary.Since making an api call is a heavy process and to do it asynchronously, we use async keyword in front of getData() function. To wait until the response comes, use await keyword while calling service method. Call notifyListeners() after data is assigned to data variable to notify the listeners about the data change happened inside the provider.

6. Add provider to the app

Add the provider we created to the app as above in lines 10 and 11. You can add any other providers to the providers array if available.

7. Trigger the api call from the UI

Create HomeScreen class extending StatefulWidget (Since I want to trigger the api call inside initState()) and in initState() call the provider as follows.

Provider.of<DataProvider>(context, listen: false).getData(context);

You can only write above code with listen: false if you are writing it inside initState(). By setting listen: false you tell not to rebuild the widget upon data changes happen inside the provider. But inside build method we write,

final postMdl = Provider.of<DataProvider>(context);

to get data changes inside the provider. If postMdl.loading==true we show the CircularProgressIndicator() else we show the relevant data came from the api request. Since we are calling notifyListeners() inside the provider after fetching data and listening to it in HomeScreen, the build method inside HomeScreen getting called.Hence the HomeScreen widget is rebuilt with new data.

Final Output

Full code can be found here.

Hit on clap, share and comment to motivate me :)

--

--

Krishan Madushanka

Software Engineer | Android | iOS | Flutter | React Native | IoT | aws certified