Flutter apps frequently communicate with APIs — making HTTP requests, parsing JSON, and handling responses/errors. Using the http or dio packages, async/await, and JSON parsing, networking is a core part of most apps.
Making HTTP requests
import 'package:http/http.dart' as http;
// GET request
Future<List<User>> fetchUsers() async {
final response = await http.get(Uri.parse('https://api.example.com/users'));
if (response.statusCode == 200) {
final List data = jsonDecode(response.body); // parse JSON
return data.map((json) => User.fromJson(json)).toList();
} else {
throw Exception('Failed to load users'); // handle errors
}
}
// POST request
await http.post(
Uri.parse('https://api.example.com/users'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'name': 'Ann'}),
);
