user16651444
user16651444

Reputation:

Failing to parse my response body in flutter web

I have a response body in the following format below:

Response body: [[{"fraud_cnt":0,"total_cnt":55364},{"fraud_cnt":1694,"total_cnt":1694}]]

i tried creating and object below

class Album {
  final String fraud_cnt;
  final int total_cnt;

  Album({
    required this.fraud_cnt,
    required this.total_cnt,
  });

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      fraud_cnt: json['fraud_cnt'],
      total_cnt: json['total_cnt'],
    );
  }
}

return Album.fromJson(jsonDecode(response.body));

but I get the error

Error: Expected a value of type 'Map<String, dynamic>', but got one of type 'List<dynamic>'

I have tried everything to loop through it and get the values inside but it's not working, does anyone know how I can loop through this and get the values

Upvotes: 0

Views: 228

Answers (2)

iStornZ
iStornZ

Reputation: 848

your json looks like have two arrays (notice the two [[).

So you have 2 solutions:

1 - Change the JSON (if you can) to look like (seems to be the best one):

[{"fraud_cnt":0,"total_cnt":55364},{"fraud_cnt":1694,"total_cnt":1694}]

2 - Get the Map<String, dynamic> from the JSON you have (not the recommended one):

factory Album.fromJson(List<dynamic> json) {
    Map<String, dynamic> json = json.first; // need to be improved
    return Album(
      fraud_cnt: json['fraud_cnt'],
      total_cnt: json['total_cnt'],
    );
  }

Upvotes: 2

Benyamin
Benyamin

Reputation: 1144

to build UI based upon a response from the future you have to use future builder widget. so the error is telling you that you are returning a list and not a map which is obvious. what you are returning from this is a list of Maps. to print the values by future builder and to see what it prints you can use unspecified types in your function then use it in your future builder to see what it looks like. so here is an example:

FutureBuilder(
        future: YOUR_FUTURE_RESPONSE_HERE, // a previously-obtained Future or null
        builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.hasdata) {
print(snapshot.data.tostring());
}
}

Upvotes: -1

Related Questions