type 'List<dynamic>' is not a subtype of type 'List<int>' where

JsonListFlutterDartDynamic

Json Problem Overview


I am new to Flutter, I try to run one GitHub project but got an error like type List dynamic is not a subtype of type List int where. Github Link

Error Line

List<int> genreIds;

MediaItem._internalFromJson(Map jsonMap, {MediaType type: MediaType.movie})
      :
        type = type,
        id = jsonMap["id"].toInt(),
        voteAverage = jsonMap["vote_average"].toDouble(),
        title = jsonMap[(type == MediaType.movie ? "title" : "name")],
        posterPath = jsonMap["poster_path"] ?? "",
        backdropPath = jsonMap["backdrop_path"] ?? "",
        overview = jsonMap["overview"],
        releaseDate = jsonMap[(type == MediaType.movie
            ? "release_date"
            : "first_air_date")],

        genreIds = jsonMap["genre_ids"];//in this line


}

Above code File

Any help will be appreciated, thank you in advance.

Json Solutions


Solution 1 - Json

Change

genreIds = jsonMap["genre_ids"];

to

genreIds = jsonMap["genre_ids"].cast<int>();

types in JSON maps or lists don't have concrete generic types. genreIds requires a List<int> not a List (or List<dynamic>), therefore you need to bring the value to its required type before you can assign it.

If you haven't seen this error earlier for the same code, then it's probably because you upgraded to a Dart version where --preview-dart-2 became the default (it was opt-in previously)

Solution 2 - Json

A more elegant way could also be initialising new List instead of casting.

var genreIdsFromJson = jsonMap['genre_ids'];
List<int> genreIdsList = new List<int>.from(genreIdsFromJson);

// then you can use gendreIdsList to the mapping function
// ...

gendreIds = genreIdsList
...

Update: As per the documentation

`` All the elements should be instances of E. The elements iterable itself may have any element type, so this constructor can be used to down-cast a List, for example as:

List<SuperType> superList = ...;
List<SubType> subList =
    new List<SubType>.from(superList.whereType<SubType>());

This constructor creates a growable list when growable is true; otherwise, it returns a fixed-length list. ``

Update: Why is it better to initialize than to cast? (Pros / Cons)

Explicit Conversions (Casting): The process is usually associated with information loss or failure to convert between types

Creating new immutable elements is better than casting. Revealing type-related bugs at compile time, more readable code, more maintainable code, better ahead of time (AOT) compilation.

i.e. it is better to try parse or parse a value with predefined method because if the type does not match the value will be null. On the other hand explicitly casting an object or value can throw errors at runtime.

Solution 3 - Json

I did what suggested with the cast<Type>() and it was working nicely for a while. Though I encountered an error where if the value for the key in the map was null (e.g. not found and threw the error)

To fix this you can make an ugly inline null check:

Here is The cleaner and more Dartful way of accomplishing this is with the null-aware ?. operator:

Try doing this (this typing cast fixes and also fixes the null problem):

genreIds = jsonMap["genre_ids"]?.cast<int>()

instead of

genreIds = jsonMap["genre_ids"].cast<int>();

Solution 4 - Json

A shorter way to handle is

genreIds = (jsonMap["genre_ids"] as List)?.map((e) => e as int)?.toList();

Solution 5 - Json

I hit this problem because I used generics in my api lib. Here's how I worked around it:

// I've simplified the get for clarity.  My production lib wraps http so I can set / handle base url, headers, time out, and throw when error codes are returned.

Future<T> get<T>(String resource) async {
  var c = Completer<T>();
  try {
    var uri = Uri.parse('$baseUrl/$resource');
    var response = await http.get(uri);
    T result = json.decode(response.body);
    c.complete(result);
  } catch (e) {
    c.completeError(e);
  }
  return c.future;
}

// Service from my feature lib
Future<Iterable<MyDTO>> fetch() async {
  var c = Completer<Iterable<MyDTO>>();
  try {
    List<MyDTO> result = [];        
    // Use Iterable<dynamic> since we cannot use generics to cast when decoding the response body
    var body = await api.get<Iterable<dynamic>>('my-resource');
    
    // cast to List<Map<String, dynamic>
    var myDTOMaps = List<Map<String, dynamic>>.from(body);

    for (var e in myDTOMaps) {
      MyDTO dto = MyDTO.fromMap(e);
      result.add(dto);
    }
    c.complete(result);
  } catch (e) {
    c.completeError(e);
  }
  return c.future;
}

Solution 6 - Json

If you still unsuccess like me, try:

List<int> genreIds = List<int>.from(json.decode(jsonMap["genre_ids"]));

Solution 7 - Json

I got a similar error using json setting properties. I fixed it with this:

jsonMap["propId"][0] as int

They are single properties, so the 0 is always correct.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMagesh PandianView Question on Stackoverflow
Solution 1 - JsonGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - JsonEdiView Answer on Stackoverflow
Solution 3 - JsonParesh MangukiyaView Answer on Stackoverflow
Solution 4 - Jsonthien nguyenView Answer on Stackoverflow
Solution 5 - JsonNathan AgerseaView Answer on Stackoverflow
Solution 6 - JsonnguyênView Answer on Stackoverflow
Solution 7 - JsonGeorgeView Answer on Stackoverflow