Let’s explore HTTP requests in Flutter
Handling HTTP requests is an essential skill for any Flutter developer working with web APIs. Flutter provides a robust and widely-used library called the HTTP package, which simplifies making network calls such as GET, POST, PUT, DELETE, and more.
This blog dives deep into how to use the HTTP package effectively, complete with examples, error handling, and best practices.
Table of Contents
- Introduction to the HTTP Package
- Adding the HTTP Package to Your Project
- Making HTTP GET Requests
- Making HTTP POST Requests
- Updating Data with PUT Requests
- Deleting Data with DELETE Requests
- Handling Errors in HTTP Requests
- Best Practices for HTTP Requests in Flutter
- Conclusion

1. Introduction to the HTTP Packag
The HTTP package in Dart provides an easy-to-use API for sending HTTP requests and handling responses. It supports common operations like fetching JSON data, sending form data, and handling authentication headers.
Key benefits of using the HTTP package include:
- Lightweight and simple to use.
- Built-in support for handling JSON.
- Extensively documented and maintained.
2. Adding the HTTP Package to Your Project
To get started, add the HTTP package to your pubspec.yaml
file:
dependencies:
http: ^1.1.0
Then, run the following command to install it:
flutter pub get
Import the package in your Dart file:
import 'package:http/http.dart' as http;
3. Making HTTP GET Requests
GET requests are used to fetch data from a server. Here’s an example of how to make a GET request and parse the JSON response:
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> fetchUserData() async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/users/1');
try {
final response = await http.get(url);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
print('User Data: $data');
} else {
print('Failed to load data: ${response.statusCode}');
}
} catch (e) {
print('Error: $e');
}
}
Key Points
- Use
Uri.parse()
to convert the URL string into aUri
object. - Always handle HTTP responses based on the status code.
- Parse JSON data using Dart’s
dart:convert
library.
4. Making HTTP POST Requests
POST requests are used to send data to the server. Here’s an example:
Future<void> createUser() async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/users');
try {
final response = await http.post(
url,
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'name': 'John Doe',
'email': 'john.doe@example.com',
}),
);
if (response.statusCode == 201) {
print('User Created: ${response.body}');
} else {
print('Failed to create user: ${response.statusCode}');
}
} catch (e) {
print('Error: $e');
}
}
Key Points
- Always specify
Content-Type
in the headers when sending JSON data. - Use
jsonEncode()
to convert a Dart object to a JSON string.
5. Updating Data with PUT Requests
PUT requests are used to update data on the server. Here’s how:
Future<void> updateUser() async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/users/1');
try {
final response = await http.put(
url,
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'name': 'Jane Doe',
'email': 'jane.doe@example.com',
}),
);
if (response.statusCode == 200) {
print('User Updated: ${response.body}');
} else {
print('Failed to update user: ${response.statusCode}');
}
} catch (e) {
print('Error: $e');
}
}
6. Deleting Data with DELETE Requests
DELETE requests are used to remove data from the server:
Future<void> deleteUser() async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/users/1');
try {
final response = await http.delete(url);
if (response.statusCode == 200) {
print('User Deleted');
} else {
print('Failed to delete user: ${response.statusCode}');
}
} catch (e) {
print('Error: $e');
}
}
7. Handling Errors in HTTP Requests
Common Errors
- Network Errors: Handle with
try-catch
. - Timeouts: Set a timeout using
http.get().timeout
. - Invalid Responses: Check
statusCode
.
Example
Future<void> fetchWithErrorHandling() async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/invalid-endpoint');
try {
final response = await http.get(url).timeout(Duration(seconds: 5));
if (response.statusCode == 200) {
print('Data: ${response.body}');
} else {
print('Error: ${response.statusCode}');
}
} on http.ClientException {
print('Client error occurred');
} on TimeoutException {
print('Request timed out');
} catch (e) {
print('Unexpected error: $e');
}
}
8. Best Practices for HTTP Requests in Flutter
- Use Constants for URLs: Store API URLs and endpoints as constants for maintainability.
- Use Dio for Advanced Features: If you need features like interceptors, consider the Dio package.
- Leverage Async/Await: Always use
async/await
for cleaner, more readable code. - Handle Errors Gracefully: Inform users of issues like failed requests or timeouts.
- Use Secure Connections: Always use HTTPS instead of HTTP.
- Avoid Blocking the Main Thread: Perform HTTP requests in async functions to keep the UI responsive.
9. Conclusion
Handling HTTP requests in Flutter is straightforward with the HTTP package. By mastering GET, POST, PUT, DELETE, and error handling, you can build robust apps that seamlessly interact with web APIs. Follow best practices, and you’ll ensure your app delivers a smooth and efficient user experience.
Let us know your thoughts or questions in the comments below, and stay tuned for more Flutter tutorials on Widget Wisdom!


Explore Other Flutter Topics…
- Introduction to Flutter and Dart
- Why choose Flutter
- Installing Flutter On Your Windows Mac And Linux System
- Your first Flutter app
- Flutter project structure
- Building blocks of Flutter
- Stateful vs. Stateless Widgets Explained
- Flutter layout system
- Flutter text widget
- Creating Buttons in Flutter: ElevatedButton, TextButton, and IconButton
- Handling User Input with Flutter Forms
- Container class in Flutter
- Flutter Navigation
- Flutter – Pass Data One Screen To Another Screen
- Managing Device Orientation in Flutter
- Stateful widget lifecycle in Flutter
- Future of Flutter
- Flutter Themes
- Flutter Animations
- Flutter AppBar Customization
- ListView in Flutter
- Flutter GridView
- Flutter Expanded Widget
- Flutter BottomNavigation Bar
- Floating Action Button
- Drawer Widgets in Flutter
- Form Validation in Flutter
- Flutter TextField
- Adding AdMob ads to a Flutter app
- Building Flutter Web & Desktop Applications
- What is Async and Await in Flutter
- HTTP requests in Flutter
- Parsing JSON in Flutter
- Tinder-Style Swipe Cards in Flutter
- Flutter Tic Tac Toe Game Tutorial
- Flutter Login UI Tutorial
- Flutter Card Widget Tutorial
- Flutter music player app tutorial
- Flutter introduction screens
- Shared Preferences in Flutter
- SQLite Database in Flutter
- Firebase Authentication in Flutter
- Firebase Firestore in Flutter
- Push Notifications in Flutter
- Handling File Uploads in Flutter
- Responsive Design in Flutter
- Provider in Flutter
- Riverpod in Flutter
- Flutter BLoC Pattern Tutorial