Flutter 应用经常需要与 API 进行通信 — 发送 HTTP 请求、解析 JSON 和处理响应/错误。使用 http 或 dio 包、async/await 和 JSON 解析,网络通信是大多数应用的核心部分。
发送 HTTP 请求
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'}),
);
