-1

我正在尝试使用以下方法从 Api 获取 json 数据

Future<SubjectList> getsubjectList(
      String userId, String accountId) async {
    final response = await http
        .get(Uri.https(_baseUrl, 'v1/package/subject-details'), headers: {
      'Content-Type': 'application/json',
      'user-id': userId,
      'account-id': accountId,
    });
    SubjectList jsonresponse = json.decode(response.body);   //'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'SubjectList'
    print('This is response =$jsonresponse');
    return jsonresponse;
  }

我已将对象建模如下

class SubjectList {
    SubjectList({
        this.subject,
        this.score,
        this.progress,
    });

    String? subject;
    double? score;
    String? progress;

    factory SubjectList.fromMap(Map<String, dynamic> json) => SubjectList(
        subject: json["subject"],
        score: json["score"].toDouble(),
        progress: json["progress"],
    );

    Map<String, dynamic> toJson() => {
        "subject": subject,
        "score": score,
        "progress": progress,
    };
}

数据如下

{
    "success": true,
    "data": [
        {
            "subject": "Grammar",
            "score": 57.17,
            "progress": "96.77%"
        },
        {
            "subject": "Maths",
            "score": 52.12,
            "progress": "73.08%"
        },
        {
            "subject": "EVS",
            "score": 55.75,
            "progress": "97.96%"
        },
        {
            "subject": "Social Studies",
            "score": -1,
            "progress": "-1%"
        },
        {
            "subject": "Hindi",
            "score": 51.36,
            "progress": "60.87%"
        },
        {
            "subject": "Vocabulary",
            "score": 62.55,
            "progress": "68.12%"
        },
]

当我尝试使用模型访问时,我收到错误“_InternalLinkedHashMap<String, dynamic>”不是“SubjectList”类型的子类型。如何正确获取数据?

4

1 回答 1

1

更改此行

SubjectList jsonresponse = json.decode(response.body);

类似于

List<SubjectList> list = json.decode(response.body)['data'].map((d) => SubjectList.fromMap()).toList();

您可以为响应本身创建一个类并在其上执行 fromMap。

于 2021-08-25T20:20:38.373 回答