Installing http

Install the http package:

dependencies:
  http: <latest_version>

then import the package:

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

Go to the Http official website to know more.

Get Request

The method http.get() is used to make a get request. It returns a Future that contains a Response

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

The http.Response class contains the data received from a successful http call.

http.Response

The http.Response class has a statusCode property which contains the status of the request. For example, on successful of fetching the data, the statusCode becomes 200, or if you have any error in the server side it will contain 500 or if the api is invalid you might get statusCode 404.

You can use body property to obtain the response data.

Here is an example:

final response = await http.get('https://jsonplaceholder.typicode.com/albums/1');

if (response.statusCode == 200) {
	// Do something
	// Parse the data
} else {
	// Do something
	// throw Exception('Failed');
}

Converting the Response Data

The body property of http.Response object contains the response result which is in string format. You can convert this data to Map<String, dynamic> using the following code:

String result = response.body;
Map<String, dynamic> mapResult = json.decode(result);

To use the method json.decode you need to import convert package.

import 'dart:convert';

You can also use jsonDecode method:

String result = response.body;
Map<String, dynamic> mapResult = jsonDecode(res.body);

Making Post Request

Using http.post method you can make a post request to the server. It returns a Future that contains Response.

Future<http.Response> createAlbum(String title) {
  return http.post(
    'https://jsonplaceholder.typicode.com/albums',
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'title': title,
    }),
  );
}

The first argument is url to which the data will be sent.

The named argument headers takes a Map<String, String> that defines the request header.

The named argument body takes a string data that will be sent to the server. The method jsonEncode() takes a map and converts it into a string which will be sent to the server. To use this method you need to import convert package.

This method returns http.Response data. That means you can convert the response data and check for status code the same way you would do for get request.