Flutter HTTP Requests
Making network calls in Flutter applications
🌐 What are HTTP Requests?
HTTP requests allow Flutter apps to communicate with web servers and APIs. Using the http package, you can fetch data, send information, and interact with online services easily.
// Import the http package
import 'package:http/http.dart' as http;
// Simple GET request
final response = await http.get(
Uri.parse('https://api.example.com/data')
);
Output:
Status Code: 200
Data fetched successfully!
HTTP Request Types
GET Request
Retrieve data from server
final response = await http.get(
Uri.parse('https://api.example.com/users')
);
POST Request
Send data to server
final response = await http.post(
Uri.parse('https://api.example.com/users'),
body: {'name': 'John'}
);
PUT Request
Update existing data
final response = await http.put(
Uri.parse('https://api.example.com/users/1'),
body: {'name': 'Jane'}
);
DELETE Request
Remove data from server
final response = await http.delete(
Uri.parse('https://api.example.com/users/1')
);
🔹 Setting Up HTTP Package
Add the http package to your Flutter project:
# pubspec.yaml
dependencies:
flutter:
sdk: flutter
http: ^1.1.0
Installation Steps:
- Add http package to pubspec.yaml
- Run: flutter pub get
- Import in your Dart file
- Start making requests!
🔹 Complete GET Request Example
Fetch data from an API and display it:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class UserList extends StatefulWidget {
@override
_UserListState createState() => _UserListState();
}
class _UserListState extends State<UserList> {
List users = [];
Future<void> fetchUsers() async {
final response = await http.get(
Uri.parse('https://jsonplaceholder.typicode.com/users')
);
if (response.statusCode == 200) {
setState(() {
users = json.decode(response.body);
});
}
}
@override
void initState() {
super.initState();
fetchUsers();
}
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(users[index]['name']),
subtitle: Text(users[index]['email']),
);
},
);
}
}
Output:
🔹 POST Request with Headers
Send data with custom headers:
Future<void> createUser() async {
final response = await http.post(
Uri.parse('https://api.example.com/users'),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your_token_here',
},
body: json.encode({
'name': 'John Doe',
'email': '[email protected]',
'age': 25,
}),
);
if (response.statusCode == 201) {
print('User created successfully!');
} else {
print('Failed to create user');
}
}
Output:
✓ User created successfully!
🔹 Error Handling
Handle network errors gracefully:
Future<void> fetchData() async {
try {
final response = await http.get(
Uri.parse('https://api.example.com/data')
).timeout(Duration(seconds: 10));
if (response.statusCode == 200) {
// Success
print('Data: ${response.body}');
} else {
// Server error
print('Error: ${response.statusCode}');
}
} catch (e) {
// Network error
print('Network error: $e');
}
}
Possible Outputs:
✓ Data: {"status": "success"}
⚠ Error: 404
✗ Network error: Connection timeout