网络请求
如果是JSON格式的请求,可以直接套用下面的代码
// 超时3秒会自动执行catch
// 你需要根据实际情况来确定返回值
Future<Map<String, dynamic>> httpRequest(String url, {int timeoutInSeconds = 3}) async {
try {
final response = await http.get(Uri.parse(url)).timeout(Duration(seconds: timeoutInSeconds));
if (response.statusCode == 200) {
String responseBody = utf8.decode(response.bodyBytes);
Map<String, dynamic> data = json.decode(responseBody);
return data;
} else {
Map<String, dynamic> data = {};
throw Exception(data);
}
} on TimeoutException {
// 请求超时处理逻辑
Map<String, dynamic> data = {};
return data;
} catch (error) {
// 其他错误处理逻辑
Map<String, dynamic> data = {};
return data;
}
}