使用错误类型的飞镖?

Dart cast using wrong type?

我是 Dart 的新手,想知道 .cast() 方法如何处理动态类型和列表。

这是 Flutter 文档中关于如何在 Dart 中手动解析 JSON 的工作示例:

List<Photo> parsePhotos(String responseBody) {
  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

  return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}

其中 responseBody 是之前从 HTTP 端点获取的一些 JSON 数组。

我不明白为什么 json.decode(responseBody) 的结果在逻辑上应该是 List<Map<String, dynamic>> 而被强制转换为 Map<String, dynamic>。我调试了代码,实际上变量 parsed 是一个列表子类型。

我在这里弄错了什么?

提前致谢。

看来是对的。 castIterable 的一种方法。尖括号中的类型是iterable中每个元素的类型。

https://api.dart.dev/stable/2.7.1/dart-core/Iterable/cast.html