_TypeError(类型'List <dynamic>'不是类型'List <Topic>'的子类型

时间:2020-03-01 12:34:10

标签: json flutter

所以我不熟悉开发,这是我偶然发现的第一件事。

我想读取一个json文件,并将其“转换”为 dart类

这是我的JSON文件:

[
    {
        "name": "Deutsch",
        "topics": [
            {
                "name": "Rechtschreibung",
                "contents": []
            },
            {
                "name": "Grammatik",
                "contents": []
            },
            {
                "name": "Textanalyse",
                "contents": []
            }
        ]
    },
    {
        "name": "Mathematik",
        "topics": [
            {
                "name": "Vektorrechnung",
                "contents": []
            },
            {
                "name": "Geometrie",
                "contents": []
            },
            {
                "name": "Polynomdivision",
                "contents": []
            }
        ]
    }
]

这是我的主题模型:

import './topic.dart';

class Subject {
  String _name;
  List<Topic> _topics;

  Subject(this._name, this._topics);

  factory Subject.fromJSON(Map<String, dynamic> json) {
    if (json != null) {
      return Subject(json['name'], json['topics']);
    } else {
      return null;
    }
  }

  get name => this._name;
  get topics => this._topics;
}

这是主题模型:

import './content.dart';

class Topic {
  String _name;
  List<Content> _contents;

  Topic(this._name, this._contents);

  factory Topic.fromJSON(Map<String, dynamic> json) {
    if (json != null) {
      return Topic(json['name'], json['contents']);
    } else {
      return null;
    }
  }

  get name => this._name;
  get contents => this._contents;
}

主题模型中 json ['topics'] 处出现错误消息:

_TypeError (type 'List<dynamic>' is not a subtype of type 'List<Topic>')

如果有人知道如何解决这个问题,我将非常感激!

谢谢。

1 个答案:

答案 0 :(得分:0)

如果您确定在Topic中总是有json['topics']

然后您可以在将其添加到主题之前对其进行投射:

return Subject(json['name'], json['topics'] as Topic);