Every client side application require connection to server to share the data and get most updated data from server. In the same way flutter also require to call the APIs’ and get data from server and also store the data in server. So in this article i will show you to use Http Request using get and post method.
Http Request are used to communicate between client and server applications. In Flutter we use Http package.
Let’s call APIs in flutter using http package step by step
Step 1 : Create flutter project
First step is to create the fluter application using command line tool or in Android studio.
flutter create example_app
This will create a new project with name example_app then go in to the folder.
Step 2 : Add http package in application
We are going to use http request so we need to add http package first. so add http package in pubspec.yaml
name: example_app
description: A new Flutter project.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.15.1 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
http: ^0.13.4
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^1.0.0
flutter:
uses-material-design: true
assets:
- assets/images/
here we added http: ^0.13.4 in dependencies block
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
http: ^0.13.4
Also make sure to add latest version always from https://pub.dev/packages/http.
Then run command
flutter --no-color pub get
Step 3 : Import and use http package in widget
After adding the http package now we can use it in our dart file so import the http package
File : lib/HttpDemo.dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Here we imported package:http/http.dart and given an alias as http so now lets’s make a http get request and parse the JSON
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
class HttpDemo extends StatefulWidget {
const HttpDemo({Key? key}) : super(key: key);
@override
_HttpDemoState createState() => _HttpDemoState();
}
class _HttpDemoState extends State<HttpDemo> {
List jsonData=[];
@override
void initState() {
super.initState();
getJsonData();
}
getJsonData() async{
final response = await http
.get(Uri.parse('https://jsonplaceholder.typicode.com/albums'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
setState(() {
jsonData = json.decode(response.body);
});
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
buildLayout(){
if(jsonData.isEmpty) {
return Center(
child: SizedBox(
child: CircularProgressIndicator(
backgroundColor: Theme
.of(context)
.primaryColor,
strokeWidth: 2,
),
height: 25.0,
width: 25.0,
),
);
}
else{
return ListView(
children: jsonData.map((e){
return Container(
margin: const EdgeInsets.all(5),
child: "Title : "+Text(e['title'] )
);
}
).toList(),
);
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Readerstacks Http Demo'),
),
body:buildLayout()
)
);
}
}
Here we used getJsonData to fetch http request and then on response setState again to rebuild the widget.
getJsonData() async{
final response = await http
.get(Uri.parse('https://jsonplaceholder.typicode.com/albums'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
setState(() {
jsonData = json.decode(response.body);
});
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
Here we used json.decode to decode the response in List using package import ‘dart:convert’.
we also create a method buildLayout to show loading indicator until jsonData variable is empty once its filled with data then we are showing list view as below
buildLayout(){
if(jsonData.isEmpty) {
return Center(
child: SizedBox(
child: CircularProgressIndicator(
backgroundColor: Theme
.of(context)
.primaryColor,
strokeWidth: 2,
),
height: 25.0,
width: 25.0,
),
);
}
else{
return ListView(
children: jsonData.map((e){
return Container(
margin: const EdgeInsets.all(5),
child: "Title : "+Text(e['title'] )
);
}
).toList(),
);
}
}
Step 3 : Add Page to main file
Add you new pages to main.dart
and start tabbing.
import 'package:flutter/material.dart';
import 'package:example_app/HttpDemo.dart';
void main() => runApp(HttpDemo());
Step 4: Run the project
Simply run the project using command line or in android studio to check the implementation.
flutter run lib/main.dart
Live Preview: