You are on page 1of 13

Department of Computing

EC-303: Mobile Application Development


Class: BESE 8AB + BSCS 7ABC

Lab 10: API Calls In Flutter.

Date: 18-05-2021
Time: 10:00 AM - 1:00 PM

Lab Engineer: Mis. Shakeela

EC303: Mobile Application Development Page 1


Lab 10: API Calls In Flutter

Objectives

The objective of this lab is helping students to familiarize themselves that how to calls API’s in
Flutter.

Description

API stands for Application Programming Interface. It can be defined as a set of protocols,
procedures, and tools that allow interaction between two applications.
In a nutshell, an API call is a process that takes place when you send a request after setting up
your API with the correct endpoints. Your information is transferred, processed, and feedback is
returned back.

Let’s consider this scenario, in which you(client) are in a restaurant. You sit on your table and
decide to eat A. You need to call the waiter(API call) and place your order(request) for A. The
waiter gets to the kitchen(server) to prepare A and serves(response) A. Now you get your
delicious food A(JSON or XML data) and everyone is happy. In this case, your interface
between you and the kitchen(Server) is your waiter(API). It’s his responsibility to carry
the request from you to the kitchen(Server), make sure it’s getting done, and you know once it
is ready he gets back to you as a response(JSON or XML data).

Tools/Software Requirement

Flutter, Android Studio, XCode, Any Editor

Helping Material:
- https://flutter.dev/docs/cookbook/networking/fetch-data
- https://flutter.dev/docs/cookbook/networking/send-data
- Flutter official Documentation
- Stack overflow

EC303: Mobile Application Development Page 2


Lab Task : (API calling)
Make a Network Request then Fetch and display the Data :
A). Fetching data from the internet is necessary for most apps. Luckily, Dart and Flutter provide
tools, such as the http package, for this type of work.

Perform the Following steps :

1. Install the http package.

dependencies:
http: <latest_version>

Import the http package.

Import ‘package:http/http.dart’ as http;

2. Make a network request using the http package and call the below API .

https://jsonplaceholder.typicode.com/todos

a). Install the Postman or add Restlet Client chrome extension to test the above API.
b). Check the response of above API by using postman or Restlet Client.

3. Convert the response into a custom Dart Object.

a). get id and title from json response and display it like (shown below).

4. Fetch and display the data with Flutter.

a).before calling API Install flutter plugin  progress_dialog


b). show progress dialog when api call.
c). Hide progress dialog on response of API.
d). If API throw any server error show that error in alert dialog.
e). Alert Dialog should have Retry button and due to any reason API call fails user will
press on retry button to call the api again.
EC303: Mobile Application Development Page 3
5. Create a List view widget to display the data that you get in API response
(as shown below).
a). show id and title from json response.

Solution
Task Code:

EC303: Mobile Application Development Page 4


1)dependencies:

http: 0.12.2

flutter:

sdk: flutter

2) class Data {

final int userId;

final int id;

final String title;

Data({this.userId, this.id, this.title});

factory Data.fromJson(Map<String, dynamic> json) {

return Data(

userId: json['userId'],

id: json['id'],

title: json['title'],

);

Future <List<Data>> fetchData() async {

final response =

EC303: Mobile Application Development Page 5


await http.get('https://jsonplaceholder.typicode.com/albums');

if (response.statusCode == 200) {

List jsonResponse = json.decode(response.body);

return jsonResponse.map((data) => new Data.fromJson(data)).toList();

} else {

throw Exception('Unexpected error occured!');

FutureBuilder <List<Data>>(

future: futureData,

builder: (context, snapshot) {

if (snapshot.hasData) {

List<Data> data = snapshot.data;

return

ListView.builder(

itemCount: data.length,

itemBuilder: (BuildContext context, int index) {

return Container(

height: 75,

color: Colors.white,

child: Center(child: Text(data[index].title),

),);

EC303: Mobile Application Development Page 6


}

);

} else if (snapshot.hasError) {

return Text("${snapshot.error}");

import 'dart:async';

import 'dart:convert';

import 'package:flutter/material.dart';

import 'package:http/http.dart' as http;

Future <List<Data>> fetchData() async {

final response =

await http.get('https://jsonplaceholder.typicode.com/albums');

if (response.statusCode == 200) {

List jsonResponse = json.decode(response.body);

return jsonResponse.map((data) => new Data.fromJson(data)).toList();

} else {

throw Exception('Unexpected error occured!');

EC303: Mobile Application Development Page 7


class Data {

final int userId;

final int id;

final String title;

Data({this.userId, this.id, this.title});

factory Data.fromJson(Map<String, dynamic> json) {

return Data(

userId: json['userId'],

id: json['id'],

title: json['title'],

);

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {

MyApp({Key key}) : super(key: key);

@override

EC303: Mobile Application Development Page 8


_MyAppState createState() => _MyAppState();

class _MyAppState extends State<MyApp> {

Future <List<Data>> futureData;

@override

void initState() {

super.initState();

futureData = fetchData();

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Flutter API and ListView Example',

home: Scaffold(

appBar: AppBar(

title: Text('Flutter ListView'),

),

body: Center(

child: FutureBuilder <List<Data>>(

EC303: Mobile Application Development Page 9


future: futureData,

builder: (context, snapshot) {

if (snapshot.hasData) {

List<Data> data = snapshot.data;

return

ListView.builder(

itemCount: data.length,

itemBuilder: (BuildContext context, int index) {

return Container(

height: 75,

color: Colors.white,

child: Center(child: Text(data[index].title),

),);

);

} else if (snapshot.hasError) {

return Text("${snapshot.error}");

// By default show a loading spinner.

return CircularProgressIndicator();

},

),

EC303: Mobile Application Development Page 10


),

),

);

Task Output Screenshot:

EC303: Mobile Application Development Page 11


EC303: Mobile Application Development Page 12
Deliverable :

Compile a single word document by filling in the solution part and submit this Word file on
LMS. This lab grading policy is as follows: The lab is graded between 0 to 10 marks. The
submitted solution can get a maximum of 5 marks. At the end of each lab or in the next lab, there
will be a viva/quiz related to the tasks. You must show the implementation of the tasks in the
designing tool, along with your complete Word document to get your work graded. You must
also submit this Word document on the LMS. In case of any problems with submissions on
LMS, submit your Lab assignments by emailing it to Mis Shakeela: shakeela.bibi@seecs.edu.pk.

EC303: Mobile Application Development Page 13

You might also like