How to fetch Data using API calls in Flutter?
What is an API? How we can use this in our code? What, why, how .. blah blah. All of these question roam in our mind when we first interatc with API and you can count me in. Believe me, after reading this blog — you’ll handle all of these questions easily.
What is an API?
API is the acronym for Application Programming Interface and it is widely used for fetching data and allows the application to talk to each other. Everytime you use an app like Instagram, or check weather on your phone, you’re using an API.
How API works?
Let’s get into it 🎉
When we first create a new project, flutter by default creates a “main” file. So, to make our code clearer, we will create another file with the name of “dummmy.dart”. You can choose any name you like.
The idea is, we are going to fetch COVID-19 data of Pakistan in card widget!
- main.dart file
import 'package:covid_19/ui/Screens/stats/dummmy.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Dummy(),
);
}
}
2. dummmy.dart file
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
class Dummy extends StatefulWidget {
@override
_DummyState createState() => _DummyState();
}
class _DummyState extends State<Dummy> {
final String allCustomerURL =
"https://api.apify.com/v2/datasets/9eUGCilmJ8HDf60mL/items?format=json&clean=1";
List data;
@override
// ignore: must_call_super
void initState() {
this.getJsonData();
super.initState();
}
// ignore: missing_return
Future<String> getJsonData() async {
var response = await http.get(
// Encoding URL
Uri.encodeFull(allCustomerURL),
headers: {"Accept": "application/json"});
print(response.body);
setState(() {
var convertDataToJson = jsonDecode(response.body);
data = convertDataToJson;
});
return "Success";
}
@override
Widget build(BuildContext context) {
SystemChrome.setEnabledSystemUIOverlays([]);
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
// backgroundColor: Colors.blueGrey.shade300,
body: SafeArea(
child: Scrollbar(
child: ListView.builder(
scrollDirection: Axis.vertical,
itemCount: data == null ? 0 : data.length,
itemBuilder: (context, int index){
return Container(
margin: EdgeInsets.symmetric(horizontal: 10),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)
),
elevation: 20,
child: Column(
children: <Widget>[
Text('COVID 19 - Pakistan Stats'.toUpperCase(),style: GoogleFonts.alegreya(fontSize: 20, color: Colors.black),),
Text("Last Updated: " + data[index]['lastUpdatedAtSource'].toString().substring(0,16), style: TextStyle(fontSize: 18, color: Colors.red),),
Divider(color: Colors.black12),
Text("Infected: " + data[index]['infected'].toString(), style: TextStyle(fontSize: 18, color: Colors.red),),
Text("Recovered: " + data[index]['recovered'].toString(), style: TextStyle(fontSize: 18, color: Colors.green)),
Text("Deceased: " + data[index]['deceased'].toString(), style: TextStyle(fontSize: 18, color: Colors.red)),
Text("Critical: " + data[index]['critical'].toString(), style: TextStyle(fontSize: 18, color: Colors.red))
],
),
),
);
}),
),
),
),
);
}
}
Output
Let’s break it down
In my first step i just created a StatefulWidget.
final String allCustomerURL =
"https://api.apify.com/v2/datasets/9eUGCilmJ8HDf60mL/items?format=json&clean=1";
List data;
In above code, allCustomersURL is just like a holder which is holding all our API data into a single variable.
@override
// ignore: must_call_super
void initState() {
this.getJsonData();
super.initState();
}
initState() is a function which is called when StatefulWidget is inserted into the tree. I just initialized initState() with super keyword.
Future<String> getJsonData() async {
var response = await http.get(
// Encoding URL
Uri.encodeFull(allCustomerURL),
headers: {"Accept": "application/json"});
print(response.body);
setState(() {
var convertDataToJson = jsonDecode(response.body);
data = convertDataToJson;
});
return "Success";
}
A future represents the result of an asynchronous operation, and can have two states: uncompleted or completed. Async means that this function is asynchronous and you might need to wait a bit to get its result. Await literally means — wait here until this function is finished and you will get its return value.
In above code, we are just encoding data which we are fecthing from our URL and just after encoding we are decoding it into another variable.
Afterwards, we just used a ListView.builder into our app and boom 🎉
Thank you soo much for investing your time. You can follow me on github.
Happy Coding ❤