February 16, 2021

How to make HTTP Get request in Flutter

By Mohit Agrawal

Learn HTTP get request API call

Nowadays it is impossible to develop a mobile app without any HTTP network call. That’s why I have decided to cover this topic in today’s Flutter tutorial.

I will show you how you can make simple API call, get the data and parse it to your custom class model.

For the demo purpose we will be using the below free API which return the chunk of data in the form of JSON array.

API url, which return the data in JSON array.

https://jsonplaceholder.typicode.com/albums/1
flutter-json-1

Implementation

To implement the http get call in Flutter we need to do the following steps:

  • Create a new Flutter project
  • Need to add the HTTP library
  • Hit the API request using HTTP library
  • Convert the response into custom class model
  • Display the data as per the requirement

Devs, since our goal is clear now, so let’s start with coding part.

Create a new Project

You can either create a new Flutter project or use your existing one. I am using the android studio as my IDE, you can use visual code as well 😎.

Setup the HTTP package

Flutter and dart provide the HTTP package to do the network related stuff, but this package does not come with Flutter by default. So let’s add it.

Get the latest version of the HTTP package and paste it in your pubspec.yaml.

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.2

Now just import the this line wherever you want to use this package.

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

Make network call using HTTP

We have added the required package into our project now let’s make use of it.

The http.get() method returns the data using GET method.

Future<http.Response> fetchAlbum() {
  return http.get(Uri.https('jsonplaceholder.typicode.com', 'albums/1'));
}

Convert the data into custom model class

The http.get() returns the data in simple JSON format. To make use of this data we need to parse the JSON to our custom model class.

class Album {
  int userId;
  int id;
  String title;

  Album({this.userId, this.id, this.title}) ;

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

As you can see in above code, I have created a our model class Album.

Now, I will show you how to parse the received data into our custom model class.

Code to convert http.get() response to Album is below.

Future<Album> fetchAlbum() async {
  final response = await http.get('https://jsonplaceholder.typicode.com/albums/1');

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

Display the data

We will use the FutureBuilder widget to display our data. It comes with the flutter the automatically updates the view for the asynchronous data sources.

FutureBuilder<Album>(
  future: futureAlbum,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data.title);
    } else if (snapshot.hasError) {
      return Text("${snapshot.error}");
    }

    // By default, show a loading spinner.
    return CircularProgressIndicator();
  },
);

Complete code

import 'dart:convert';

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


void main() {
  runApp(MyApp());
}
//Custom model for JSON
class Album {
  int userId;
  int id;
  String title;

  Album({this.userId, this.id, this.title}) ;

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

//Future method to hit API
Future<Album> fetchAlbum () async {
  var response = await http.get('https://jsonplaceholder.typicode.com/albums/1');
  if (response.statusCode == 200) {
    return Album.fromJson(jsonDecode(response.body));
  } else {
    //return error
  }
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future<Album> futureAlbum;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    futureAlbum = fetchAlbum();
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text('Json Parsing'),
      ),
      body: Center(
        child: FutureBuilder<Album> (
          future: futureAlbum,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Text(snapshot.data.title);
            } else {
              return Text('Still Loading');
            }
          },
        )
      ),
    );
  }
}

Video Tutorial