How To Fetch Data using API Calls in Flutter

Muhammad Affan Khan
3 min readJan 11, 2020
Photo by Rob Fuller on Unsplash

Welcome to the first Flutter story of 2020. In my previous story, I discussed screen navigation in Flutter. You can check it here.

Today’s story is about how you can make API calls in a Flutter application. It’s pretty easy, believe me. You can get a complete picture in just 2 minutes of reading. Let’s Start building step by step.

Note: I assume you have a basic understanding of Flutter.

Step 1

If you are starting from scratch, you can create a fresh Flutter application or if you already have one, just skip this step.

$ flutter create rest_api

Step 2

To make API calls, we’ll be using http, it’s a Flutter package to make API calls with ease. In the root directory of the recently created project, open pubspec.yaml file and under dependencies, add:

http: ^0.12.0+4

Note: The above version may have changed at the time when you read this so I suggest you use the latest available version from the official docs.

Your dependencies section in pubspec.yaml file should look like this:

dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
http: ^0.12.0+4

Save the file and in the root directory and run:

$ flutter pub get

You’re all set to make API calls in your app now.

Step 3

In our sample app, we’re going to use a freely available random user API to fetch a list of users and display them in a list. We’ll fetch a list of 10 random users for our list.

Now create a dart file user-list.dart and add the following content in them:

Now let’s break down the code into smaller pieces and see what’s happening there.

final String apiUrl = "https://randomuser.me/api/?results=10";

Future<List<dynamic>> fetchUsers() async {

var result = await http.get(apiUrl);
return json.decode(result.body)['results'];

}

The above function will return an array of random users. Here we are only interested in the user list which is in the ‘results’. We are making a GET request here. Since getting data from the internet takes time, we are doing it asynchronously. That’s why we are returning data as a Future.

FutureBuilder<List<dynamic>>(
future: fetchUsers(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.hasData){
print(_age(snapshot.data[0]));
return ListView.builder(
padding: EdgeInsets.all(8),
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index){
return
Card(
child: Column(
children: <Widget>[
ListTile(
leading: CircleAvatar(
radius: 30,
backgroundImage: NetworkImage(snapshot.data[index]['picture']['large'])),
title: Text(_name(snapshot.data[index])),
subtitle: Text(_location(snapshot.data[index])),
trailing: Text(_age(snapshot.data[index])),
)
],
),
);
});
}else {
return Center(child: CircularProgressIndicator());
}
},


)

Here, the FutureBuilder is used to render the list to the screen. We have given it a future and a builder. When there is no data, it displays a CircularProgressIndicator on the screen. It automatically rebuilds its contents once the data is returned by the future method.

Under that, we have a ListView widget. We are building the list using the builder method which is an efficient way to do that when you have a dynamic number of items in your list.

Finally, we have used Card and ListTile widgets to give a nicer look to the list.

Now you have a user list page ready, you can make it the starting point for your app from main.dart file:

Here is how the final list will look like:

Conclusion

Though we only used the GET request to fetch our user list, we can also use other types of requests such as POST, PUT and DELETE using the same http package. We’ve done all the code in a single file for learning purposes here but it’s a good idea to keep in separate files and make widgets as reusable as possible. See you in another Flutter story, till then, enjoy learning Flutter :)

--

--

Muhammad Affan Khan

Software Engineer | Ruby on Rails | Flutter | Open source lover