[英]Flutter - Multiple HTTP Requests to the same JSON
I have this API where go to fetch data.我有这个 API 其中 go 来获取数据。
For each "date" I have a JSON Object.对于每个“日期”,我都有一个 JSON Object。
What I want to do is fetch objects from let's say 5 years and get them on the same final JSON http response.我想要做的是从假设 5 年获取对象,并在相同的最终 JSON http 响应中获取它们。 So I don't have to display only a day at the time.
所以我不必只显示一天。
Future<List<Schedule>> getFromEspnSchedule(String sport) async {
final url = 'http://myserver.com/api/$date'; //the $date would be e.g. 2010, 2011, 2012, ...
final response = await http.get(url);
if (response.statusCode == 200) {
List jsonResponse = json.decode(response.body);
return jsonResponse.map((data) {
return new Schedule.fromJson(data);
}).toList();
}
}
What is the best way to implement this?实现这一点的最佳方法是什么?
If your API returns just a single Schedule object, you need to modify your method to get a single element.如果您的 API 仅返回单个 Schedule object,则需要修改方法以获取单个元素。
Future<Schedule> getFromEspnSchedule(String sport) async {
final url = 'http://myserver.com/api/$date';
final response = await http.get(url);
if (response.statusCode == 200) {
return Schedule.fromJson(json.decode(response.body));
} else {
// make sure you return API error here
}
}
After you do this, you can go ahead and chain this into multiple calls made at the same time to achieve getting the data faster:完成此操作后,您可以提前 go 并将其链接到同时进行的多个调用中,以更快地获取数据:
List<Schedule> responseList = await Future.wait([
getFromEspnSchedule('football'),
getFromEspnSchedule('volleyball'),
getFromEspnSchedule('basketball'),
getFromEspnSchedule('chess'),
]);
// responseList objects are listed the same way they are called above.
Schedule footballSchedule = responseList[0];
Schedule volleyballSchedule = responseList[1];
Schedule basketballSchedule = responseList[2];
Schedule chessSchedule = responseList[3];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.