dartdart-http

Dart cast using wrong type?


I'm new to Dart and was wondering over how the .cast() method works with dynamic types and lists.

This is a working example from the Flutter documentation on how to parse JSON manually in Dart:

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

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

where responseBody is some JSON array previously fetched from a HTTP endpoint.

I don't understand why the result of json.decode(responseBody) is cast to Map<String, dynamic> when logically it should be List<Map<String, dynamic>>. I've debugged the code and in fact the variable parsed is a list subtype.

What am I getting wrong here?

Thanks in advance.


Solution

  • It looks like it is correct. cast is a method of Iterable. The type in angle brackets is the type of each element in the iterable.

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