Search code examples
jsonflutteriterable

Error when trying to decode json with Iterable in Flutter


I'm trying to get this simple json response in Flutter, but getting this error type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable< dynamic >'. I found some people with the same error but the solutions it's not clearly to me. The error occurs on jsonDecode(response.body);, in debug mode, when reachs the response.body, the exception occurs.

{
"#bom": 4,
"#jantar": 3,
"#paris": 2,
}

My model:

import 'dart:convert';

List<Hashtags> hashtagsFromJson(String str) => List<Hashtags>.from(json.decode(str).map((x) => Hashtags.fromJson(x)));

String hashtagsToJson(List<Hashtags> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Hashtags {
Hashtags({
    this.hashtag,
});

int? hashtag;

factory Hashtags.fromJson(Map<String, dynamic> json) => Hashtags(
    hashtag: json["hashtag"],
);

Map<String, dynamic> toJson() => {
    "hashtag": hashtag,
};
}

and my get method:

Future<List<Hashtags>> getHashtagTop() async {

var url = Uri.parse(baseUrl + 'hashtagTop');

final Map<String, String> dataBody = new Map<String, String>();
dataBody['uid'] = appController.currentUser.value.id.toString();

try {
  http.Response response = await http.post(
    url,
    headers: headers,
    body: jsonEncode(dataBody),
  );

  if (response.statusCode == 200 || response.statusCode == 201) {
    Iterable jsonResponse = jsonDecode(response.body);
    List<Hashtags> listHashtagTop =
        jsonResponse.map((model) => Hashtags.fromJson(model)).toList();

    return listHashtagTop;
  } else {
    return [];
  }
} catch (e) {
  print("ERRO_______________" + e.toString());
  return [];
}
}

So what is missing here?


Solution

  • Change your decoding function to this

     final results = [jsonDecode(response.body)];
    
    List<Hashtags> listHashtagTop =
            results.map((model) => Hashtags.fromJson(model)).toList();
    

    Try this and let you know