【发布时间】:2019-05-25 17:38:29
【问题描述】:
我想在 listview 中显示我正在使用此 api 的玩家统计数据:https://cricapi.com/api/playerStats?apikey=apikey&pid=pid
上述api的输出为:
{
"pid": xxxx,
"profile": "profile description",
"imageURL": "https://www.cricapi.com/playerpic/xxxx.jpg",
pid 为每个玩家从另一个 api 检索:
https://cricapi.com/api/playerFinder?apikey=apikey&name=playerName
上述api的输出为:
{
"data": [
{
"pid": xxxx,
"fullName": "Firstname Lastname",
目前,我在第一个 api 中通过硬编码 pid 来显示玩家的统计数据,其代码是:
FetchJson() async {
var response = await http.get(
'https://cricapi.com/api/playerStats?apikey=apikey&pid=1111');
if (response.statusCode == 200) {
String responseBody = response.body;
var responseJson = jsonDecode(responseBody);
pid = responseJson['pid'];
name = responseJson['name'];
playingRole = responseJson['playingRole'];
battingStyle = responseJson['battingStyle'];
country = responseJson['country'];
imageURL = responseJson['imageURL'];
data = responseJson;
var stats = data['data']['batting'];
var testStats = stats['tests'];
var odiStats = stats['ODIs'];
var tStats = stats['T20Is'];
// T20 Stats
matches_t = tStats['Mat'];
runs_t = tStats['Runs'];
half_t = tStats['50'];
century_t = tStats['100'];
highest_t = tStats['HS'];
avg_t = tStats['Ave'];
我在initState() 内打电话给FetchJson()。
我尝试了针对类似/之前的问题How to fetch api data by passing variables (parameters)? 给出的解决方案,但这导致我走上了不同的道路。我无法实施该解决方案,因为我无法通过FetchJson() 接收的第一个api 返回pid。
我的问题是:
如何从第二个 api (playerFinder) 检索 pid 并将其提供给第一个 api (playerStats) 以及如何利用该 pid 以便我可以传递 pid 而不是硬编码 pid作为变量并且可以在 UI 中显示多个玩家的统计数据?
需要的代码在这里:https://pastebin.com/iU8x9U8z
我想在 UI 中显示球员统计数据,但目前我正在传递硬编码的 playerid,它只显示一个球员的统计数据,但我想显示不同球员的统计数据。
**********更新 *************
作为替代解决方案,我现在使用 pids 的列表并使用 map 解析那些并将它们传递给 for 循环内的 FetchJson(),如下所示:
var playerIds = [{"pid":35320},{"pid":28114},{"pid":28779},{"pid":28763},{"pid":30176},{"pid":7133},{"pid":5390}]
@override
void initState() {
var intIds = playerIds.map<int>((m) => m['pid'] as int).toList();
for (int i = 0; i < intIds.length; i++) {
FetchJson(intIds[i]);
}
}
FetchJson(int ids) async {
print(ids);
var response = await http.get(
'https://cricapi.com/api/playerStats?apikey=apikey&pid=$ids');
....
}
我现在使用这种方法面临的问题是,它从列表中取出最后一个 pid 并在 UI 中重复显示其数据。我希望看到的预期输出是:UI 中所有pids 的玩家数据,我不知道如何实现这一点。
此处参考完整代码:https://pastebin.com/kFYBfHuf
【问题讨论】: