When you are developing a mobile app at times you will need to use API. Most of the times you will need a backend to work with the app.
There is plenty of backends that you can use. You can use the likes of Firebase or any other Database of your choice.
In this tutorial of “Learn HTTP request in FLutter with API Call”, we will develop an app from scratch using the “http” flutter plugin. By developing this app we will learn the following things:
- How to use “HTTP” flutter plugin
- Make API calls
- Develop a Model for the request and response
- Refresh the data on Pull Down gesture.
Using API you will have more control over how to display each element on the app. If you are looking at something basic like WebView, you can check my other Flutter tutorial in the link below:
Getting Started
Firstly to develop the app we will need an API where we can make the calls. For this tutorial, we will develop an app and call it InstaJoke. Before proceeding with the creating of an app, we will check some API that is readily available for free.
For this tutorial I will be using the API from following URL.
https://sv443.net/jokeapi/v2/
You can go through the terms and condition of the usage of the API as provided on the page. The page also shows usage and examples on how to make the calls. So you can explore more on how to use it.
Create New Flutter Project
As usual, we will start by creating a new flutter project. We will call the project “InstaJoke”. I will be using VS Code for this tutorial. You can use any IDE of your choice. If you face any issue you can ask me in the comment or contact me.
Open your terminal and create new flutter project:
flutter create InstaJoke
Including dependency in pubspec.yaml file
dependencies:
flutter:
sdk:
flutter
http:
^0.12.0+2
Once the app is created we will remove everything from the
main.dart file and enter following code.
import 'package:flutter/material.dart';
import
'package:flutter_joke/pages/home_page.dart';
void main() {
runApp(InstaJokeApp());
}
class InstaJokeApp extends StatelessWidget {
// This
widget is the root of your application.
@override
Widget
build(BuildContext context) {
return
MaterialApp(
debugShowCheckedModeBanner: false,
home:
HomePage(),
);
}
}
You will see some errors, but do not worry. We will need to
create other pages and error will be resolved.
Formatting The API URL
In this part,
we will format the API call as mentioned on the API website. The website
provides the tool to generate an API URL based on your choices.
We
will create a new file called config.dart under
our lib directory.
In this
configuration, we will create different variables to make it easier to control
the parameters. You can edit this parameter and change the requirements.
class Config {
// Setting
the API url and parameters as provided by website
static
String url = '<https://sv443.net/jokeapi/v2/joke/>';
static
String categories = 'Any';
static
String language = 'en';
static
String flags = 'nsfw,racist,sexist';
static
String jokeType = 'twopart';
static
String amount = '1';
//
Formatting the final URL, So we can use it directly on our app
static
String apiUrl =
'<https://sv443.net/jokeapi/v2/joke/$categories?blacklistFlags=$flags&type=$jokeType>';
}
Creating The Model For The Joke Response
After the
configuring the web URL above, creating a model is an essential thing. You will
all the time need to create a model when dealing with the API request.
For
this tutorial, we will create a new directory under lib and call it models.
Inside this model directory, we will create a new file called joke.dart.
In
this model, we will take those parameters we get in the response. While making
the API call, the response will be in JSON format.
Here we
make a model out of this JSON response in the method ModelJoke.fromJson().
class ModelJoke {
bool
error;
String
category;
String
setup;
String
delivery;
String
message;
ModelJoke(
{this.error, this.category, this.setup, this.delivery, this.message});
ModelJoke.fromJson(Map<String, dynamic> json) {
error =
json['error'];
// If no
error is there get the Joke
if
(!error) {
category = json['category'];
setup
= json['setup'];
delivery = json['delivery'];
} else {
// If
there is error get error message
message = json['message'];
}
}
}
Developing The UI For InstaJoke App
Next,
we need to develop the User Interface of the InstaJoke App. For this first, we
will create a new directory under lib and called it pages.
We will
now create a new file and call it home_page.dart.
In
this Home Page, we will import our http
plugin and other necessary modules. To import http plugin
you can add following line:
import 'package:http/http.dart' as http;
Next we will need to get the joke content from the API. For
that we will first initialize the variable then use Future method to get the
content.
static List<ModelJoke> _jokes =
List<ModelJoke>();
static List<ModelJoke> _jokesInApp =
List<ModelJoke>();
// Get the Joke from the API
Future<List<ModelJoke>> comingJokes() async {
var url
= Config.apiUrl;
var
response = await http.get(url);
var joke
= List<ModelJoke>();
if
(response.statusCode == 200) {
var
notesJson = json.decode(response.body);
joke.add(ModelJoke.fromJson(notesJson));
}
return
joke;
}
If you look into the method comingJoke() which
uses the MoldelJoke in Future method as we are doing API calls.
Here we will call the URL that we have in our config.dart file,
then use the await method to call the URL
and get a response.
We then check if the response is successful with the status code
200. If it is successful we then pass the joke to the ModelJoke.fromJson() method, which was defined
earlier in our model.
That is all for getting joke from API and formatting it with the
HTTP request plugin of flutter. Next is designing the UI.
You can find complete code below for home_page.dart file with simple UI and refresh
method used.
import 'dart:convert';
import 'package:flutter/material.dart';
import '../config.dart';
import '../models/joke.dart';
import 'package:http/http.dart' as http;
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage>
{
//Swipe to
Refresh
final
GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
GlobalKey<RefreshIndicatorState>();
static
List<ModelJoke> _jokes = List<ModelJoke>();
static
List<ModelJoke> _jokesInApp = List<ModelJoke>();
// Get the
Joke from the API
Future<List<ModelJoke>> comingJokes() async {
var url
= Config.apiUrl;
var
response = await http.get(url);
var joke
= List<ModelJoke>();
if
(response.statusCode == 200) {
var
notesJson = json.decode(response.body);
joke.add(ModelJoke.fromJson(notesJson));
}
return
joke;
}
// Pull to
refresh and get New Jokes
Future<Null> _refresh() {
// Clear
the old data
_jokes.clear();
//Add
the new data
return comingJokes().then((value) {
setState(() {
_jokes.addAll(value);
_jokesInApp = _jokes;
});
});
}
@override
void
initState() {
// Get
the Joke when the App initialize
comingJokes().then((value) {
setState(() {
_jokes.addAll(value);
_jokesInApp = _jokes;
});
});
super.initState();
}
@override
Widget
build(BuildContext context) {
return
Scaffold(
appBar: AppBar(
title: Text(
'Insta
Joke',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
centerTitle: true,
backgroundColor: Colors.deepOrange,
),
body:
RefreshIndicator(
key:
_refreshIndicatorKey,
onRefresh: _refresh,
child: ListView.builder(
itemBuilder: (context, index) {
return Column(
children: [
_jokesInApp[index].error
? Column(
mainAxisAlignment:
MainAxisAlignment.center,
crossAxisAlignment:
CrossAxisAlignment.center,
children:
[Text('${_jokesInApp[index].message}')],
)
: Center(
child: Padding(
padding: const
EdgeInsets.only(
top: 120, left:
25, right: 25),
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
crossAxisAlignment:
CrossAxisAlignment.center,
children: [
Text(
'${_jokesInApp[index].category}',
style:
TextStyle(
fontSize: 20,
color:
Colors.black54,
),
textAlign:
TextAlign.center,
),
SizedBox(
height: 30,
),
Text(
'${_jokesInApp[index].setup}',
style: TextStyle(
fontSize: 25,
color:
Colors.deepOrange,
),
textAlign:
TextAlign.center,
),
SizedBox(
height: 30,
),
Text(
'${_jokesInApp[index].delivery}',
style:
TextStyle(
fontSize: 25,
color:
Colors.lightBlue,
),
textAlign:
TextAlign.center,
),
],
),
),
),
],
);
},
itemCount: _jokesInApp.length,
),
),
);
}
}
Conclusion
In this tutorial, we have used the HTTP flutter plugin to call an API, create model decode the JSON response and display it on the User Interface of App. Well, that was quite a work and great thing is you developed everything from scratch.