Check provided Flutter application which makes a Rest Api call and displays some data retrieved as response
http
package can be used to interact with rest APIs with methods like http.post()
, http.get()
Check Flutter installation to setup Flutter
Use flutter create
command to create a Flutter project (here rest_api_app) :
flutter create rest_api_app
http
package is used to make server call and flutter_svg
is used to render flags of countries(which are in svg format) whose url is taken from data received from server
Add flutter_svg
and http
packages to pubspec.yaml
dependencies:
flutter_svg: ^0.17.3+1
http: "^0.12.1"
flutter:
sdk: flutter
Run following command to add dependencies
flutter pub get
import 'package:http/http.dart' as http;
import 'package:flutter_svg/flutter_svg.dart';
http.get
methods makes a server call for the url
argument
Additional data like authentication can be sent with headers
parameter
http.get
is an asynchronous method and returns a Future<http.Response>
datatype
It can be synchronised using await
keyword and the resultant datatype is http.Response
Future<List> getServerData() async {
String url = 'https://restcountries.eu/rest/v2/all';
final response = await http.get(url, headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
print(response.body);
return json.decode(response.body);;
}
else {
print("error from server : $response");
throw Exception('Failed to load post');
}
}
In case json data is expected from server, then json.decode()
can be used to convert json response body to corresponding dart object (List or Map)
Following example app code gets data, in getServerData()
function, from a public rest url https://restcountries.eu/rest/v2/all which returns a list of countries with some information about the countries
This function is called in initState so that it is called once
The response Future
object is stored to a variable serverData
which is used in a FutureBuilder
widget to render name and svg image of flag of countries
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter_svg/flutter_svg.dart';
void main() => runApp(RestApiApp());
class RestApiApp extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
class _AppState extends State<RestApiApp> {
Future<List> serverData;
@override
void initState() {
super.initState();
serverData = getServerData();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Rest Api Example App'),
),
body: Container(
height: 600,
width: double.infinity,
color: Colors.indigo.withOpacity(0.4),
child: Container(
padding: EdgeInsets.only( top: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
new Container(
padding: EdgeInsets.only( bottom: 0),
child: Center(
child: new Text(
'Countries ',
style: new TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold
),
),
),
),
FutureBuilder<List>(
future: serverData, //sets serverData as the expected Future
builder: (context, snapshot) {
CounterUtil.incrementStreamCounterForLabel("futurebuilder");
if (snapshot.hasData) { //checks for non-null return value from serverData
return getListView(snapshot.data, "server"); // snapshot.data is return value of serverData
}
else if (snapshot.hasError) { //checks if the response threw error
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
),
],
),
),
)
),
);
}
Widget getListView(List<dynamic> listData, mapKey) {
return new Container(
color: Colors.white,
height:454,
padding: EdgeInsets.only( top: 10),
child: ListView.separated(
shrinkWrap:true,
itemCount: listData.length,
itemBuilder: (BuildContext context, int index) {
var countryName = listData[index]['name'];
var imageSrc = listData[index]['flag'];
return Container(
height: 30,
child: Row(
children: [
Container(
padding: const EdgeInsets.only(left: 10,),
width: 40,
height: 40,
child: SvgPicture.network('${imageSrc}', fit: BoxFit.fill),
),
Padding(
padding: const EdgeInsets.only(left: 10,),
child: Text('${countryName}')
),],
),
);
},
separatorBuilder: (BuildContext context, int index) => const Divider(),
),
);
}
Future<List> getServerData() async {
String url = 'https://restcountries.eu/rest/v2/all';
final response = await http.get(url, headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
print(response.body);
return json.decode(response.body);;
}
else {
print("error from server : $response");
throw Exception('Failed to load post');
}
}
}
Ensure a supported device is connected or emulator/simulator is started
Go to project directory
Use flutter run
command to run
flutter run
It builds and runs app on an available android/ios device