我在 flutter 中遇到了一个奇怪的错误。我正在使用 json 可序列化。
这是我的代码
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>')
这是屏幕截图
JSON 数据
这是json数据格式的截图
最佳答案
改变这一行:
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。
关于dart - Flutter _TypeError 类型 'List<dynamic>' 不是类型 'Map<String, dynamic> 的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55635044/