【问题标题】:Flutter _TypeError type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>Flutter _TypeError type 'List<dynamic>' 不是类型 'Map<String, dynamic> 的子类型
【发布时间】:2019-09-02 05:45:32
【问题描述】:

我在颤振中遇到了一个奇怪的错误。我正在使用可序列化的 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数据格式的截图

【问题讨论】:

    标签: dart flutter


    【解决方案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。

    【讨论】:

    • 不幸的是同样的问题。
    • 你检查我上一个答案了吗?
    • 这一行给出错误 data.add(DivMatches(sublist)); _TypeError (type 'List&lt;dynamic&gt;' is not a subtype of type 'List&lt;Match&gt;') 我想要解析嵌套数据。
    • hmm 这应该可以工作:final List sublist = el.map((val) => Match.fromJson(val)).toList();
    • 我现在只是这样使用它,但它一直给我Exception has occurred. _TypeError (type 'List&lt;dynamic&gt;' is not a subtype of type 'List&lt;Match&gt;')
    【解决方案2】:

    你可以使用cast&lt;Type&gt;():

    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;
    }
    
    
    

    【讨论】:

    • 当我包含相关模型的 ID 并在从 FireBase 数据库中获取时从 ID 构建新对象时,这对我有用。需要一种具有多个模型关系的 Object.fromJson() 的简单方法,并且效果很好,谢谢。
    猜你喜欢
    • 2019-08-18
    • 2021-09-12
    • 2021-02-25
    • 2020-06-21
    • 2020-01-18
    • 2019-05-02
    • 2023-01-07
    • 2020-05-30
    • 2021-06-09
    相关资源
    最近更新 更多