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();

use instead

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

or just

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

See also

  • In Dart, what's the difference between List.from and .of, and between Map.from and .of?
  • https://api.dartlang.org/stable/2.0.0/dart-core/List/List.from.html
  • https://api.dartlang.org/stable/2.0.0/dart-core/List/List.of.html
  • Dart 2.X List.cast() does not compose

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();

Tags:

Json

Dart

Flutter