Most apps fetch data from a server. Flutter uses the http package for HTTP requests.
Setup
YAML
# pubspec.yaml
dependencies:
http: ^1.1.0Bash
flutter pub getGET request
Dart
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<List<dynamic>> fetchUsers() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to load users');
}
}POST request
Dart
Future<Map<String, dynamic>> createUser(String name, String email) async {
final response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/users'),
headers: {'Content-Type': 'application/json'},
body: json.encode({'name': name, 'email': email}),
);
if (response.statusCode == 201) {
return json.decode(response.body);
} else {
throw Exception('Failed to create user');
}
}Tips
- Always handle errors — network requests fail.
- Use
FutureBuilderto show loading states. - Add a timeout to prevent hanging requests.
🎉 You have completed the Flutter course!