Search code examples
flutterdartdio

Get an error when getting data from the server in flutter


I have an AchievementResponse model with a fromJson method. I receive data from the server and I want to place this data in a list of type AchievementResponse. But when I get the data and add it to the list, I get the error _TypeError (type '_Map<String, dynamic>' is not a subtype of type 'String'). If I add the toString() method, I also get an error (screenshots below). Tell me how to fix the error?

model

  factory AchievementResponse.fromJson(Map<String, dynamic> json) {
    return AchievementResponse(
      id: json['id'],
      title: json['title'],
      description: json['description'],
      status: json['status'],
    );
  }

response

Future<List<AchievementResponse>?> getInfo
...
if (response is dio.Response) {
  final data = response.data;
  print(data['achievementsProgress']);

  return jsonDecode(data['achievementsProgress'].toString())
      .map(AchievementResponse.fromJson)
      .toList();

enter image description here

error

enter image description here

error withou toString() method

enter image description here


Solution

  • You don't need to use jsonDecode on data['achievementsProgress'], it's already decoded.

    Looking at the exception, it seems data['achievementsProgress'] is a map with a data list in it. Try this:

    return data['achievementsProgress']['data']
        .map(AchievementResponse.fromJson)
        .toList();