嗨,大家好,我在从JSON API获取数据时遇到了问题。我有这个结构:
{
"team": {
"team_name": "Team Name",
"team_quantity": 10,
"team_victory": 2,
}
}
我正在尝试使用Flutter获取数据:
class Team{
final String name;
final int quantity;
final int victory;
Team({this.name, this.quantity, this.victory});
factory Team.fromJson(Map<String, dynamic> json){
return Team(
name: json['team_name'] as String,
quantity: json['team_quantity'] as int,
victory: json['team_victory'] as int,
);
}
}
Future<List<Team>> fetchTeam(http.Client client) async {
final response =
await http.get('url');
return compute(parseTeam, response.body);
}
List<Team> parseTeam(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Team>((json) => Team.fromJson(json)).toList();
}
我收到此错误:
I/flutter (25834): Exception: NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
I/flutter (25834): Receiver: _LinkedHashMap len:1
I/flutter (25834): Tried calling: cast<Map<String, dynamic>>()
I/flutter (25834): Found: cast<RK, RV>() => Map<RK, RV>
您能帮我解释一下错误吗?非常感谢!
也许我的问题可能是api中的“团队”?我将在Flutter中获取具有相同结构的数据:
{
"team": {
"team_name": "Team Name",
"team_quantity": 10,
"team_victory": 2,
}
}
or
{
"team_name": "Team Name",
"team_quantity": 10,
"team_victory": 2,
}
尝试更换
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
与
final Map<String, dynamic> parsed = jsonDecode(responseBody);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句