Flutter项目运行报错:List<dynamic>无法转为List<int>求助
Hey there! I’ve run into this exact type mismatch issue before when working with JSON in Flutter—let’s get this sorted for you.
The Root Cause
Looking at the line where the error hits:
genreIds = jsonMap["genre_ids"];
The problem is that when Dart parses JSON, arrays are always returned as List<dynamic> by default. But your genreIds variable is declared as List<int>, and Dart won’t automatically cast this dynamic list to a list of integers for you. That’s why you’re seeing the subtype error.
Quick Fixes
You have two straightforward ways to fix this line:
1. Use cast<int>()
This is the simplest approach if you’re confident that all elements in genre_ids are integers (which they should be, since this is coming from TMDB’s API):
genreIds = (jsonMap["genre_ids"] as List).cast<int>();
2. Use List<int>.from()
This method creates a new list and explicitly converts each element to an int—great if you want a bit more control (like handling potential non-int values, though that’s unlikely here):
genreIds = List<int>.from(jsonMap["genre_ids"]);
Updated Code Snippet
Here’s what the corrected constructor line should look like (using the first fix as an example):
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"] as List).cast<int>();
Why This Works
Both methods tell Dart exactly how to convert the dynamic list from JSON into a strongly-typed list of integers, resolving the subtype mismatch that was causing your error.
Give either fix a try, and your project should run without that error!
内容的提问来源于stack exchange,提问作者Magesh Pandian

