Doing HTTP Calls in Flutter and Parsing Data

By | October 7, 2018

Here is a simple example of doing Http calls in Flutter.

In this example we will try to fetch some JSON value from the below url

https://jsonplaceholder.typicode.com/posts/1

You can read more from here.

Add Dependencies

First you need to add the http plugin in dependencies.

[java]
dependencies:
http: <latest_version>
[/java]

The latest version of http can be found here (https://pub.dartlang.org/packages/http).

Example

Lets look at a simple example where we fetch some data and show it in the UI.

[java]
import ‘package:flutter/material.dart’;
import ‘dart:async’;
import ‘dart:convert’;

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

Future<Post> fetchPost() async {
final response =
await http.get(‘https://jsonplaceholder.typicode.com/posts/1’);

if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception(‘Failed to load post’);
}
}

class Post {
final int userId;
final int id;
final String title;
final String body;

Post({this.userId, this.id, this.title, this.body});

factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json[‘userId’],
id: json[‘id’],
title: json[‘title’],
body: json[‘body’],
);
}
}

class ServiceCall extends StatefulWidget {
ServiceCall({Key key, this.title}) : super(key: key);
final String title;

@override
_ServiceCallState createState() => _ServiceCallState();
}

class _ServiceCallState extends State<ServiceCall> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: FutureBuilder<Post>(
future: fetchPost(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return new Padding(
padding: new EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(‘USER ID : ${snapshot.data.userId}’),
Text(‘TITLE : ${snapshot.data.title}’),
Text(‘BODY : ${snapshot.data.body}’),
],
));
} else if (snapshot.hasError) {
return Text("Error : ${snapshot.error}");
}
// By default, show a loading spinner
return CircularProgressIndicator();
},
),
),
);
}
}
[/java]

One thought on “Doing HTTP Calls in Flutter and Parsing Data

  1. Pingback: GridView Demo in Flutter – CODERZHEAVEN

Leave a Reply

Your email address will not be published. Required fields are marked *