Learn how to perform HTTP requests in Flutter using the http package to connect your app to web APIs. This guide covers GET, POST, PUT, DELETE methods, handling responses, and asynchronous programming.
In the world of mobile app development, connecting your application to the internet is a crucial aspect that allows it to interact with web services, fetch data, and provide dynamic content. In Flutter, the http
package is a powerful tool that simplifies making HTTP requests. This section will guide you through the process of using the http
package to perform various HTTP operations, such as GET and POST requests, and handle responses effectively.
HTTP (Hypertext Transfer Protocol) is the foundation of any data exchange on the Web and a protocol used for fetching resources. It is the protocol used by the World Wide Web and this protocol defines how messages are formatted and transmitted, and what actions web servers and browsers should take in response to various commands.
HTTP requests are essential for connecting your Flutter app to external web services. They allow your app to:
These operations are typically performed using different HTTP methods, each serving a specific purpose:
Understanding these methods is fundamental to interacting with web APIs.
Before you can start making HTTP requests, you need to add the http
package to your Flutter project. This package provides a simple way to perform HTTP requests and handle responses.
Open your Flutter project in your preferred IDE or text editor.
Locate the pubspec.yaml
file in the root directory of your project.
Add the http
package under the dependencies section:
dependencies:
flutter:
sdk: flutter
http: ^0.13.5
Run flutter pub get
in the terminal to install the package.
This will download the http
package and make it available for use in your project.
Once the http
package is added to your project, you need to import it into your Dart files where you intend to use it. This is done by adding the following import statement at the top of your Dart file:
import 'package:http/http.dart' as http;
This import statement allows you to use the http
package’s functionalities by prefixing them with http.
.
GET requests are used to retrieve data from a server. They are the most common type of HTTP request and are used to fetch resources such as JSON data, images, or HTML files.
Let’s demonstrate how to perform a GET request to fetch a list of posts from a public API, such as JSONPlaceholder.
Future<void> fetchPosts() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
final data = response.body;
// Process data
} else {
// Handle error
throw Exception('Failed to load posts');
}
}
In this example:
http.get
to perform a GET request.Uri
object.statusCode
of the response to determine if the request was successful.response.body
, which contains the data returned by the server.When handling HTTP responses, it’s important to check the status code to determine the outcome of the request:
By checking the status code, you can implement appropriate error handling in your app.
POST requests are used to send data to a server, typically to create a new resource. They are commonly used in forms, where user input is sent to a server for processing.
Let’s see how to perform a POST request to send data to a server.
Future<void> createPost(String title, String body) async {
final response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': title,
'body': body,
}),
);
if (response.statusCode == 201) {
final data = response.body;
// Process success
} else {
// Handle error
throw Exception('Failed to create post');
}
}
In this example:
http.post
to perform a POST request.Content-Type
header to indicate that we are sending JSON data.jsonEncode
to convert the data into a JSON string.statusCode
to determine if the request was successful.When sending data to a server, it’s important to set the appropriate headers and encode the body data correctly. Common headers include:
application/json
).Bearer token
).Handling responses involves parsing the data returned by the server and checking for errors.
Most APIs return data in JSON format, which needs to be parsed into Dart objects. You can use the dart:convert
library to decode JSON data.
import 'dart:convert';
void parseJson(String responseBody) {
final parsed = jsonDecode(responseBody);
// Process parsed data
}
Always check the status code of the response to determine if the request was successful. Implement error handling to manage different scenarios, such as network errors or server issues.
Network calls are inherently asynchronous, meaning they take time to complete. In Flutter, you use the async
and await
keywords to handle asynchronous operations.
Future<void> fetchData() async {
try {
final response = await http.get(Uri.parse('https://example.com/data'));
if (response.statusCode == 200) {
// Process data
} else {
// Handle error
}
} catch (e) {
// Handle exception
}
}
Let’s put everything together with a practical example of fetching a list of posts from JSONPlaceholder.
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<List<Post>> fetchPosts() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
final List<dynamic> jsonData = jsonDecode(response.body);
return jsonData.map((json) => Post.fromJson(json)).toList();
} else {
throw Exception('Failed to load posts');
}
}
class Post {
final int id;
final String title;
final String body;
Post({required this.id, required this.title, required this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
In this example:
Post
class to represent the data structure.Post
objects.To better understand the flow of an HTTP GET request, let’s visualize it using a Mermaid.js sequence diagram.
sequenceDiagram participant App participant Server App->>Server: HTTP GET /posts Server-->>App: Response with data (status 200)
This diagram illustrates the interaction between the app and the server during a GET request.
In this section, we’ve covered how to perform HTTP requests in Flutter using the http
package. You’ve learned about different HTTP methods, handling responses, and asynchronous programming. By following these guidelines, you can effectively connect your Flutter app to web APIs and provide dynamic content to your users.