Getting type 'List<dynamic>' is not a subtype of type 'List<...>' error in JSON Getting type 'List<dynamic>' is not a subtype of type 'List<...>' error in JSON dart dart

Getting type 'List<dynamic>' is not a subtype of type 'List<...>' error in JSON


This code creates a List<dynamic>

parsed.map((i) => Example.fromJson(i)).toList();

You must explicitly cast List<dynamic> to List<Example> like so,

List<Example> list = List<Example>.from(parsed.map((i) => Example.fromJson(i)));

or just

var /* or final */ list = List<Example>.from(parsed.map((i) => Example.fromJson(i)));

See also


Reason for Error:

You get this error when your source List is of type dynamic or Object (let's say) and you directly assign it to a specific type without casting.

List<dynamic> source = [1]; List<int> ints = source; // error

Solution:

You need to cast your List<dynamic> to List<int> (desired type), there are many ways of doing it. I am listing a few here:

  1. List<int> ints = List<int>.from(source);
  2. List<int> ints = List.castFrom<dynamic, int>(source);
  3. List<int> ints = source.cast<int>();
  4. List<int> ints = source.map((e) => e as int).toList();


I was receiving the 'MappedListIterable<dynamic, dynamic>' is not a subtype of type 'Iterable<Example> when i tried Günter's solution.

 var parsed = json.decode(response.body); var list = parsed.map((i) => Example.fromJson(i)).toList();

Casting the parsed data into a List<dynamic> (rather than just letting it go to dynamic) resolved that issue for me.

 var parsed = json.decode(response.body) as List<dynamic>; var list = parsed.map((i) => Example.fromJson(i)).toList();