尝试在 Flutter 中使用 Iterable 解码 json 时出错

Error when trying to decode json with Iterable in Flutter

我试图在 Flutter 中获得这个简单的 json 响应,但收到此错误 type '_InternalLinkedHashMap' is not a subtype of type 'Iterable< dynamic >'。我发现有些人有同样的错误,但我不清楚解决方案。错误发生在jsonDecode(response.body);,在调试模式下,当到达response.body时,出现异常。

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

我的模特:

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

和我的获取方法:

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

那么这里缺少什么?

把你的解码函数改成这个

 final results = [jsonDecode(response.body)];

List<Hashtags> listHashtagTop =
        results.map((model) => Hashtags.fromJson(model)).toList();

试试这个让你知道