Flutter _TypeError类型'List <dynamic>'不是类型'Map <string,dynamic =“”>的子类型

时间:2019-04-11 14:32:41

标签: dart flutter

我正面临着一个奇怪的错误。我正在使用json serialisable。

这是我的代码

{
    path: '',
    component: SubContainerComponent,
    children: [
      {
        path: 'sub1/:id/',
        component: Sub1Component,


      },
     {
        path: '',
        component: SomeOtherComponent,
     },
    ],

  }

我的网络api这样发送数据

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

}

它是数组的数组。

产生错误的代码是

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

错误提示

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

这是屏幕截图 enter image description here

JSON数据 这是json数据formate的屏幕截图

enter image description here

enter image description here

2 个答案:

答案 0 :(得分: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。

答案 1 :(得分:1)

您可以使用cast<Type>()

import 'dart:convert';

void main() {
  print(getScores());
}

class Score {
  int score;
  Score({this.score});

  factory Score.fromJson(Map<String, dynamic> json) {
    return Score(score: json['score']);
  }
}

List<Score> getScores() {
  var jsonString = '''
  [
    {"score": 40},
    {"score": 80}
  ]
''';

  List<Score> scores = jsonDecode(jsonString)
      .map((item) => Score.fromJson(item))
      .toList()
      .cast<Score>(); // Solve Unhandled exception: type 'List<dynamic>' is not a subtype of type 'List<Score>'

  return scores;
}