The HTTP
package in Flutter is a Dart library for making HTTP requests, which is essential for accessing data from APIs, fetching and uploading files, and making other HTTP requests. It provides an easy-to-use API for making requests and handling responses, including support for JSON and other data formats.
In this article, we will discuss how to use the http
package in Flutter, including making GET and POST requests, handling response data, and error handling.
Installation
To use the http
package in your Flutter project, add it to your pubspec.yaml
file under dependencies:
dependencies:
http: ^0.13.4
After adding the dependency, run flutter pub get
to install the package.
Making HTTP Requests
The http
package provides several classes for making HTTP requests, including Client
, Request
, and Response
. However, the easiest way to make HTTP requests is by using the get
and post
methods provided by the http
package.
The get
method is used to make GET requests, and it takes a URL as its argument. Here’s an example of how to use it:
import 'package:http/http.dart' as http;
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
if (response.statusCode == 200) {
print(response.body);
} else {
throw Exception('Failed to fetch data');
}
}
In this example, we are making a GET request to the JSONPlaceholder API to fetch a single todo item. We use the await
keyword to wait for the response to be returned, and then we check the status code of the response. If the status code is 200
, we print the response body, which contains the todo item data. Otherwise, we throw an exception indicating that the request failed.
The post
method is used to make POST requests, and it takes a URL and an optional request body as its arguments. Here’s an example of how to use it:
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> postData() async {
final response = await http.post(Uri.parse('https://jsonplaceholder.typicode.com/posts'),
body: jsonEncode({'title': 'Flutter', 'body': 'Flutter is awesome', 'userId': 1}),
headers: {'Content-type': 'application/json; charset=UTF-8'});
if (response.statusCode == 201) {
print(response.body);
} else {
throw Exception('Failed to post data');
}
}
In this example, we are making a POST request to the JSONPlaceholder API to create a new post. We use the jsonEncode
method to convert the request body to a JSON string, and we also set the Content-type
header to indicate that the request body is in JSON format. If the request is successful, we print the response body, which contains the newly created post data. Otherwise, we throw an exception indicating that the request failed.
Handling Response Data
The http
package provides several methods for handling response data, including jsonDecode
, bodyBytes
, and streamedResponse
. The most commonly used method is jsonDecode
, which is used to parse JSON data returned by the server.
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
final title = data['title'];
final body = data['body'];
print('Title: $title');
print('Body: $body');
} else {
print('Failed to load data');
}
}
In this example, we’re making a GET request to the JSONPlaceholder API to fetch the first post. We check the status code of the response to ensure it’s successful (HTTP 200 OK). If it is, we decode the JSON data in the response body and extract the title
and body
fields. Finally, we print these fields to the console.
Note that we’re using the jsonDecode
function from the dart:convert
library to parse the JSON data in the response body. Also, we’re wrapping our HTTP request in a try-catch
block to handle any exceptions that might occur.
You can use this as a starting point to handle response data from the http
package in your Flutter app.