Flutter API 使用http调用

Flutter API Call using http

我正在尝试使用以下方法从 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”不是 'SubjectList' 类型的子类型。如何正确获取数据?

更改此行

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

类似于

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

您可以为响应本身创建一个 class 并对其执行 fromMap。