skip to Main Content

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

3

Answers


  1. Change code of return

      List<AchievementResponse> achievementResponse = AchievementResponse.fromJson(response.data);
            
      return achievementResponse;
    
    Login or Signup to reply.
  2. As you pay attention to your error, you will see the data that you are getting from your server is Map<String, dynamic> but you are decoding the response as String. anyway to fix this problem you can pass achievementsProgress map to fromJson witout any converting to String:

    Future<List<AchievementResponse>?> getInfo() async {
      final response = await _dio.get(url);
    
      if (response is dio.Response) {
        final data = response.data;
        final List<dynamic> achievementsProgress = data['achievementsProgress'];
    
        return achievementsProgress
            .map((achievement) => AchievementResponse.fromJson(achievement))
            .toList();
      } else {
        throw Exception('failed in loading data');
      }
    }
    

    happy coding…

    Login or Signup to reply.
  3. 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search