Flutter _TypeError类型'列表 '不是'Map'类型的子类型

问题描述 投票:-2回答:1

我扑面而来是一个奇怪的错误。我正在使用json serialisable。

这是我的代码

class DivMatches{
  final List<Match> matches;
   DivMatches(this.matches);
  factory DivMatches.fromJson(Map<String, dynamic> json) =>
  _$DivMatchesFromJson(json);
  Map<String, dynamic> toJson() => _$DivMatchesToJson(this);

}

我的web api发送这样的数据

[
 [
   {..},
   {..},
   {..},
   {..}
 ],
[...],
[...],
[...],
[...],
[...],
[...]
]

它是数组的数组。

产生错误的代码是

data = body.map((el) => DivMatches.fromJson(el)).toList(); 

它给出的错误

Exception has occurred.
_TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>')

这是截图enter image description here

这里的JSON DATA是json数据格式的屏幕截图

enter image description here

enter image description here

dart flutter
1个回答
1
投票

改变这一行:

final body = json.decode(res.body);

对此:

final body = json.decode(res.body) as List;

还有这个:

List<DivMatches> data = [];

body.forEach((el) {
   final List<Match> sublist = el.map((val) => Match.fromJson(val)).toList();
   data.add(DivMatches(sublist));
}); 

注意:检查Match.fromJson是否返回Match对象或Map。

© www.soinside.com 2019 - 2024. All rights reserved.