Getting Data from Internet in Flutter | Androidmonks

Getting Data from the Internet in Flutter – Http Package

In this tutorial, we will look at how to make use of HTTP Package in Flutter to get Data from the internet. There cannot be any real-time application without the use of Http and internet to communicate back and forth. Even though, the use of Firebase is much helpful and recommended, there might be use cases to call a server that has been set up already.

In order to do that, we will take a look at the HTTP package that Flutter is offering. The tutorial covers, all the basics as to how to create and use the Server to render and make use of JSON data in the Flutter application.

YOU ARE YOUR BOSS
I agree to have my personal information transfered to MailChimp ( more information )
Join over 5.000 visitors who are receiving our free content and learn how to program with Android. The growth of Android is estimated to reach a whooping 83% by 2020. Hop on the train and start making money!
We hate spam. Your email address will not be sold or shared with anyone else.

Using HTTP package

Before we jump on to making the connection with the HTTP server, we will import and make use of the HTTP package in Flutter. Go to the pubspec.yaml and add the below dependency inside the dependencies section

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.0+2

The sdk will already be present, add the http alone. Once done, time to import the HTTP package inside the main.dart file.

The main method required to make the Http request is the

http.get()

The method takes in a URL as its value and expects a JSON response in return. In order to make use of this effectively, the return value should be

Future<http.Response>

The main use of the Future is that and http.Response is that,

  • Future is a core Dart class for working with async operations. It is used to represent a potential value or error that will be available at some time in the future.
  • The http.Response class contains the data received from a successful http call.

Once, this is introduced, we can look at how to parse the response that is received from the Server.

Parse Data from HTTP.Response

There are two techniques as part of the JSON serialization that is available. In order to make better usage of the Data that is obtained as the Http response, we will look at the second way to create a Custom Dart object and parsing this data.

This is possible by introducing a simple Model in Flutter(Follows the same syntax as that of JAVA)

class Todos {
  final int user;
  final int id;
  final String title;
  final bool completed;

  Todos({this.title, this.completed, this.user, this.id});

  factory Todos.fromJson(Map<String, dynamic> json) {
    return Todos(
      user: json['userId'],
      id: json['id'],
      title: json['title'],
      completed: json['completed'],
    );
  }
}

There are 4 variables that are part of the UserId class. They are

  • user
  • id
  • title
  • completed

The main reason for creating this Class is explained below(We can go with any other custom class depending on what format the data is going to be received)

The important method is the use of the factory to convert the JSON response to the custom dart Object which is the UserId object.

Once, this is done, its a matter of constructing the rest of the App to receive data from the Internet.

Convert the JSON response to the Custom Dart Object

The next part of the process is to convert the JSON response into the Custom Dart object that we require. This is possible by making use of the Future operator and using the http.get() method we saw initially.

Check out that portion below,

Future<Todos> getData() async {
  final response = await http.get("https://jsonplaceholder.typicode.com/todos/1");
  if (response.statusCode == 200)
    {
      return Todos.fromJson(json.decode(response.body));
    }

}

The main reason for using the Todos class is that we can make use of some of the available servers that provide test JSON responses. One of the servers that provide the Test JSON response is the jsonplaceholder website.

You can check out various options that are available in the jsonplaceholder
Once that is done, it is pretty straightforward to use the fromJson method and decoding the response.body and storing the value to the Todos class.

Stitching it all together

Once all the parts are created, it is time to stitch it all together. We are using a lot of operators that denote that an action will be performed in Future. In Flutter, there is a Widget to do this exactly called the FutureBuilder widget. It takes in the Custom Dart class we created.

The FutureBuilder widget takes in two attributes primarily,

  • future – What custom Object should we expect in the future.
  • builder – Method takes in 2 parameters – context, snapshot.
    Snapshot will hold the future data as the custom dart object. It can be accessed by snapshot.data.<VARIABLE_NAME>

Additionally FutureBuilder Widget returns a ProgressBarWidget which will fill the screen still the Custom Object is populated with Data. It can also return None if required.

Lets try to stitch it together and see how the final app structure is.

import 'dart:convert';
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Todos> getData() async {
  final response = await http.get("https://jsonplaceholder.typicode.com/todos/1");
  if (response.statusCode == 200)
    {
      return Todos.fromJson(json.decode(response.body));
    }
    else
      {
        throw Exception("Error occured");
      }

}
void main()
{
  runApp(MaterialApp(
    title:'Androidmonks',
    home: Scaffold(
      body: HttpWidget(todos: getData(),),

    ),
  ));
}

class Todos {
  final int user;
  final int id;
  final String title;
  final bool completed;

  Todos({this.title, this.completed, this.user, this.id});

  factory Todos.fromJson(Map<String, dynamic> json) {
    return Todos(
      user: json['userId'],
      id: json['id'],
      title: json['title'],
      completed: json['completed'],
    );
  }
}
class HttpWidget extends StatelessWidget
{
  final Future<Todos> todos;
  HttpWidget({Key key, this.todos}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(title:Text("Sample HTTP Call")),
      body: Center(
        child: FutureBuilder<Todos>(
          future: todos,
          builder: (context, snapshot){
            if(snapshot.hasData) {
              return Text(snapshot.data.title);
            }
            return CircularProgressIndicator();
          },
        ),
      ),
    );
  }

}

The application is done. Even though it looks complex enough, the application contains nothing more than simple Future callbacks of the http.get() and JSON parsing the data to the custom object we have.

We make use of the Scaffold Widget as the base widget to render the application UI.

The final application looks like below.

JSON Data from the Sample Server looks like

JSON Data from Server
JSON Data from Server
Final HTTP package Flutter App
Final HTTP package Flutter App

Final Application

Final Application GIF
Final Application GIF

Drop in Any Queries in the comment section below.

“Happy Coding”

Also Read  Android Studio - Knowing your IDE | AndroidMonks

Leave a Comment

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