To perform HTTP requests in Dart, the most common and straightforward way is by using the http package โ itโs an official and lightweight library that makes it really easy to send GET, POST, PUT, DELETE, and other HTTP requests.
First, you add the dependency in your pubspec.yaml file:
dependencies:
http: ^1.2.0
Then you import it in your Dart file:
import 'package:http/http.dart' as http;
import 'dart:convert';
For example, a simple GET request looks like this:
Future fetchUserData() async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/users/1');
final response = await http.get(url);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
print("User name: ${data['name']}");
} else {
print("Failed to fetch data. Status code: ${response.statusCode}");
}
}
Hereโs whatโs happening โ
- The
http.get()sends the request asynchronously and returns aFuture<Response>. - We
awaitthat response so it pauses until the data is received. - Then we check the status code and decode the JSON using
jsonDecode()fromdart:convert.
For POST requests, itโs just as simple:
Future createUser() async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/users');
final response = await http.post(
url,
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'name': 'Aswini', 'email': 'aswini@example.com'}),
);
if (response.statusCode == 201) {
print("User created successfully!");
} else {
print("Failed to create user.");
}
}
In one of my Flutter projects, I used this approach to connect the frontend with a REST API for fetching user data and submitting forms. A challenge I faced was handling timeouts and network errors, especially on poor connections. I solved it by using try-catch with http.Client().get() and adding timeout handling like:
await http.get(url).timeout(Duration(seconds: 10));
Another limitation is that the http package doesnโt support advanced features like interceptors or request cancellation. When I needed that, I switched to the Dio package, which is more powerful for large-scale projects because it supports interceptors, logging, and file uploads easily.
So, to sum up โ the http package is perfect for simple and clean HTTP requests in Dart, and with async/await it feels very natural and readable, similar to how network requests are handled in JavaScript or Python async code.
