Search code examples
flutterflutter-httpfluttermap

Flutter API Call using http


I'm trying to get json data from Api by using the following

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

I have modelled the object as follows

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

The Data is as follows

{
    "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%"
        },
]

When ever i try to access using the model i'm receiving the error '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'SubjectList'. How do I get the data properly ?


Solution

  • Change this line

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

    to something like

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

    You can create a class for the response itself and the do the fromMap on it.