Flutter Http :
Flutter Http Network call is used to fetch the data from api, we have discussed a retrofit network call in previous tutorial, in this part of the tutorial we will discuss the usage and implementation.
Http(Hyper Text Transfer Protocol) is a protocol for transmitting data over application layer.
Every app has the internet requirement and using HTTP makes it is much easier in app level data transfer.
In this tutorial we consider a api using which we parse the json and fetch image and description and populate on the screen.
Flutter HTTP Video Tutorial :
Go through the below tutorial for more detailed explanation.
Project Structure :
This image depicts the implementation of flutter http network project structure.
pubspec.yaml :
Add flutter Http dependency to pubspec and specify the version according to avoid code level issues.
dependencies: flutter: sdk: flutter http: ^0.12.1
Photos.dart :
Create a model class for fetching the API and declare variables albumId, title and url these values we are fetching from api so need to parse the same here in model class.
class Photos { final int albumId; final String title; final String url; Photos({this.albumId, this.title, this.url}); factory Photos.fromJson(Map<String, dynamic> json) { return Photos( albumId: json['albumId'], title: json['title'], url: json['url'], ); } }
Network.Dart :
Specify the url to fetch the data and you can increment the last number i.e., ‘1’ to fetch new data on every update.
'https://jsonplaceholder.typicode.com/photos/1'
If success based on the success code parse the data using Photos Model class and if fail handle it properly as stated below.
if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. return Photos.fromJson(json.decode(response.body)); }
import 'dart:convert'; import 'package:http/http.dart' as http; import 'Photos.dart'; Future<Photos> fetchPhoto() async { final response = await http.get('https://jsonplaceholder.typicode.com/photos/1'); if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. return Photos.fromJson(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'); } }
main.dart :
Initialize void main() and consider the default class MyApp().
void main() => runApp(MyApp());
Declare Future<Photos>
Future<Photos> futurePhotos;
then initialize the futurePhotos
@override void initState() { super.initState(); futurePhotos = fetchPhoto(); }
Declare FutureBuilder in body
FutureBuilder<Photos>( future: futurePhotos, builder: (context, snapshot) { // By default, show a loading spinner. return CircularProgressIndicator(); }, ),
Add a image view widget and specify the width and height.
Image.network( snapshot.data.url, width: 200, height: 200, ),
and in Text Widget provide the description and textStyle.
Text("Description : "+snapshot.data.title,style: TextStyle(fontSize: 30),),
Flutter HTTP Full Code :
Providing the full code for flutter http network call implementation.
import 'dart:async'; import 'package:flutter/material.dart'; import 'Photos.dart'; import 'Network.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { MyApp({Key key}) : super(key: key); @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { Future<Photos> futurePhotos; @override void initState() { super.initState(); futurePhotos = fetchPhoto(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Fetch Photos', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('Fetch Data With Http Call'), ), body: FutureBuilder<Photos>( future: futurePhotos, builder: (context, snapshot) { if (snapshot.hasData) { return Padding( padding: const EdgeInsets.all(35.0), child: Column( children: <Widget>[ Padding(padding: EdgeInsets.all(20)), Image.network( snapshot.data.url, width: 200, height: 200, ), Padding(padding: EdgeInsets.all(20)), Text("Description : "+snapshot.data.title,style: TextStyle(fontSize: 30),), ], ), ); } else if (snapshot.hasError) { return Text("${snapshot.error}"); } // By default, show a loading spinner. return CircularProgressIndicator(); }, ), ), ); } }
Flutter HTTP Output :
This screen depicts the usage of Flutter Http network call
If you are having any queries on this tutorial on flutter http network call implementations do let us know in the comment section below.If you like this tutorial do like and share this tutorial for more interesting updates.