Most of the apps nowadays are connected to the Internet. Internet has become more of a necessity to all of us and It's pretty hard to even imagine a world without internet.
Most of the apps communicate over the internet to get and push data to and from the servers. Be it be any e-commerce application or any other application that require some internet functionalities to run , they all make API calls to make the data available in the application. Let's take a look at how we can make API calls in our flutter application and begin the learning.
We will be building a mobile applications which will display some facts about the computers and softwares. The facts will be fetched from an api (The API can be accessed from the "Sample API" section in this website). We will see how we can extract useful information from the api and parse it using different data structures.
Here is the screenshot for the app :
The complete tutorial will be divided into the following steps :
We need to add the http package in our pubspec.yaml file. Go to your pubspec.yaml file and add the following line in dependencies section. Your dependencies section will look something like this.
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.3
http:
Future<T> is an object representing a delayed computation. A Future is used to represent a potential value, or error, that will be available at some time in the future. Let's understand it in a more simpler way. Whenever you search something on Google or go to any website, your browser takes some time to process the request and then displays the web page.
You make a request --> Your browser takes the request --> You get the response in near Future (based on your internet connectivity).
In simpler words, any process or method execution that takes some time to execute is known as Future in dart.
async keyword is used to declare a method an asynchronous one. To make API calls, we will also define our methods with async keyword as we don't want the execution of other methods to stop.
await is used to wait for the future to complete. While calling the API, we will use await so as to wait for the response from the server.
Note : The await keyword works only in async functions.
The API url that we are gonna use for this app is this:
http://thegrowingdeveloper.org/apiview?id=2&type=application/json
The response that we get from this api is in form of a JSON object. I am attaching a snapshot of the response down below.
{
"id": 1,
"category": "Facts by The Growing Developer ft Developer Singh",
"facts": [
{
"id": 1,
"title": "Computers run on binary code that means their software is written using only 1s and 0s",
"description": "",
"image_url": "http://thegrowingdeveloper.org/thumbs/1000x1000r/demo_api_folder/tgd-fact-1.png"
},
{
"id": 2,
"title": "The First Gigabyte Drive Cost $40,000",
"description": "It was released in 1980 and weighed 550lbs. How’s that for a portable drive?",
"image_url": "http://thegrowingdeveloper.org/thumbs/1000x1000r/demo_api_folder/tgd-fact-2.png"
},
{
"id": 3,
"title": "About 90% of the World’s Currency only exists on Computers",
"description": "This means only about 10% of the global currency is actually cash",
"image_url": "http://thegrowingdeveloper.org/thumbs/1000x1000r/demo_api_folder/tgd-fact-3.png"
},
{
"id": 4,
"title": "The password for the Computer Controls of nuclear tipped missiles of the U.S was 00000000 for eight years.",
"description": "Even our Developer Singh was amazed",
"image_url": "http://thegrowingdeveloper.org/thumbs/1000x1000r/demo_api_folder/tgd-fact-4.png"
}
]
}
The complete response is enclosed inside { } (curly braces) , that means the complete structure is in the form of a JSON or we can say Map in dart. So, it's pretty clear that we need to have a variable of type Map to store the response. In Map, the values are stored in key-value pairs. So we can access the values using the key names i.e map_name['id'] will return the respective id and so on.
The most important and useful information is contained in 'facts'. The data that 'facts' is holding is of type List, so, we will require a List variable to store the facts data.
Now, take a look at the method I wrote to get the result and store it inside the respective variables.
// import the required packages
import 'package:http/http.dart' as http;
import 'dart:convert';
//A Map variable to store the complete response
Map mapResponse;
//A List that will store the 'facts' data inside the response
List listOfFacts;
Future fetchData() async {
http.Response response;
response = await http.get(
'http://thegrowingdeveloper.org/apiview?id=2&type=application/json');
// response code 200 means that the request was successful
if (response.statusCode == 200) {
setState(() {
// We decode the response using the dart:convert library and stored into a Map
mapResponse = json.decode(response.body);
// 'facts' contained a list of facts
listOfFacts = mapResponse['facts'];
});
}
}
Note : Don't forget to call the fetchData() method in initState()
Let's take a look at the listOfFacts, this list further contains map as it's elements. To extract image from it we can access it using listOfFacts[index]['image_url'] and similarly for title, it will be listOfFacts[index]['title'].
I used a ListView.builder to iterate through the elements of the listOfFacts and The main title can be fetched using mapResponse['category'] . Take a look at the complete code and That's it! We are able to fetch the data from API and display the useful data in our application.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MaterialApp(
home: HomePage(),
debugShowCheckedModeBanner: false,
));
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Map mapResponse;
List listOfFacts;
Future fetchData() async {
http.Response response;
response = await http.get(
'http://thegrowingdeveloper.org/apiview?id=2&type=application/json');
if (response.statusCode == 200) {
setState(() {
mapResponse = json.decode(response.body);
listOfFacts = mapResponse['facts'];
});
}
}
@override
void initState() {
fetchData();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Fetch Data from Internet'),
backgroundColor: Colors.blue[900],
),
body: mapResponse == null
? Container()
: SingleChildScrollView(
child: Column(
children: <Widget>[
Text(
mapResponse['category'].toString(),
style: TextStyle(fontSize: 30),
),
ListView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return Container(
margin: EdgeInsets.all(10),
child: Column(
children: <Widget>[
Image.network(listOfFacts[index]['image_url']),
Text(
listOfFacts[index]['title'].toString(),
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
Text(
listOfFacts[index]['description'].toString(),
style: TextStyle(
fontSize: 18,
),
)
],
),
);
},
itemCount: listOfFacts == null ? 0 : listOfFacts.length,
)
],
),
),
);
}
}
Read this tutorial and get started with your own COVID-19 Tracker app
Read TutorialSo that's all for the coding part. I hope this will clear most of your queries. We were able to fetch data from the internet by making API calls, extracted useful information out of it and displayed in the form of different widgets. The next part will be uploaded soon where we will learn how we can map the API response with our Models in fluttter.
Happy Coding !
It's been over 2 years since Bloc was mentioned with respect to State Management in Flutter. While it is now widely used in some of the biggest applic...
Models are the core of the data flow in any of the MVC architecture. Learn how to make models in Flutter/Dart in a professional way....
Your Go-to Guide to decide which database to choose and why....
Let's create a Clean and Materialistic UI Design for Login and see how we can implement google signin using Firebase Auth...
A complete guide on using PageView and PageController in Flutter....