Codementor Events

Making a network call in Flutter

Published Jul 16, 2018

Hi Folks! I am back with a brand new article featuring one of the most important task in Flutter framework i.e making a network call or HTTP request. As an Android developer I know how much code I need to write to make a simple GET request in native android app development. Uff! I know the pain so as you do. But with Flutter making a HTTP request is like a cake walk. Let me show you how to make app development simple with Flutter.

Before diving into the actual code. Let me just give you some description about the library we will be using to make the HTTP request. This library comes with the Flutter framework itself. The name of the library is:

http.dart

This library comes with the Flutter framework and lives inside the http package. This dart file has all the methods to make a HTTP request. You can read about this library in great detail through the Flutter website.

Before reading further I assume that you have some basic knowledge about Flutter and can create a simple project. If you say YES then lets do it. Making your first GET request:

We will be using the famous JSONPlaceHolder site to make a request to a fake REST API provided by them.

Lets hit the /photos resource which is a GET request.

This is the body of the /photos resource which returns 5000 items:

[
  {
    "albumId": 1,
    "id": 1,
    "title": "accusamus beatae ad facilis cum similique qui sunt",
    "url": "http://placehold.it/600/92c952",
    "thumbnailUrl": "http://placehold.it/150/92c952"
  },
  {
    "albumId": 1,
    "id": 2,
    "title": "reprehenderit est deserunt velit ipsam",
    "url": "http://placehold.it/600/771796",
    "thumbnailUrl": "http://placehold.it/150/771796"
  },
  {
    "albumId": 1,
    "id": 3,
    "title": "officia porro iure quia iusto qui ipsa ut modi",
    "url": "http://placehold.it/600/24f355",
    "thumbnailUrl": "http://placehold.it/150/24f355"
  }
]

Open up the main.dart file in your Flutter project. Just remove all the code inside it.

The very first thing we will be doing in the main.dart file is importing the must have packages.

import 'package:flutter/material.dart';
import 'package:http/http.dart' show get;

The first statement is to import the Flutter material features which will be used to build the app. This material.dart file consist of the most important classes i.e MaterialApp and Scaffold. The second import is getting only the GET method from the http.dart file.

Now check the below code which is making the GET request:

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("GET Request"),
        ),
        floatingActionButton: FloatingActionButton(onPressed: () {
          fetchData();
        }),
      ),
    );
  }

  void fetchData() async {
    var result = await get('https://jsonplaceholder.typicode.com/photos');
    print(result.body);
  }
}

In the above code the main logic which is making the GET request is inside the fetchData() method. Let me break it down into steps:

  1. You write the get(url) method which expects a URL to fetch the data from.
  2. async and await allows us to write asynchronous code that looks like synchronous code.
  3. The variable result will hold the NetworkResponse. It will have many things in it like headers, statusCode etc which includes the body as well. result.body will be holding the JSON body.
  4. print(result.body) will print the whole JSON if the request was successful.

There is also another way apart from async and await to get the response from the request made. Here is another way:

void fetchData() {
  get('https://jsonplaceholder.typicode.com/photos').then((result){
    print(result.body);
  });

In most of the Flutter documentation you will finding this then(result) method being used which will give us the result back after the request has been done.

So this is all it takes to make a simple GET request in Flutter. You can even make other type of request like POST, PUT etc. You can read in detail about them in the Flutter documentation . Hope you liked the article. Peace out and have a great day folks. I will be back soon with another brand new article.

Discover and read more posts from sagar suri
get started