'_CastError (type '_CompactIterable<dynamic>' is not a subtype of type 'List<dynamic>' in type cast)
I want to deserialize JSON files using this model but this problem occurred. If I am wrong deserialize the file. What is the proper technique to deserialize the file and show the key name like (Thriller, Actions,..) in list-view and by clicking that listview It would display movies-name in grid-view.
This is a local json file structure
{
"Thriller": [
{
"Death Clique": "https://www.youtube.com/watch?v=4Q9lTjqQeBU&ab_channel=VMovies"
},
{
"CID": "https://www.youtube.com/watch?v=4Q9lTjqQeBU&ab_channel=VMovies"
},
{
"Wrong Turn": "https://www.youtube.com/watch?v=9spc-dExLH0&ab_channel=SagarForever"
},
],
"Action Movie": [
{
"Nobody": "https://nobodymovie.com"
},
{
"Tenet": "https://tenetmovie.com"
},
],
"Romantic Movie": [
{
"Titanic": "https://titanicmovie.com"
},
{
"The Vow": "https://thevowmovie.com"
},
]
}
This is the model of the json file.
class MovieCategories {
final String? title;
final List<Movie>? subServices;
MovieCategories({ this.title, this.subServices});
factory MovieCategories.fromJson(Map<String, dynamic> json) {
var list = json.values as List;
List<Movie> imagesList = list.map((i) => Movie.fromJson(i)).toList();
return MovieCategories(
title: json.keys.toString(),
subServices: imagesList,
);
}
}
class Movie {
final String? title;
final String? url;
Movie({this.title, this.url});
factory Movie.fromJson(Map<String, dynamic> parsedJson){
return Movie(
title:parsedJson.keys.toString(),
url:parsedJson.values.toString()
);
}
}
API call :
class FetchData {
static final List<MovieCategories> data = [];
static Future<String> _loadAddressAsset() async {
return await rootBundle.loadString('assets/json/movie-categories.json');
}
static Future<List<MovieCategories>> loadAddress() async {
data.clear();
final jsonAddress = await _loadAddressAsset();
final jsonResponse = json.decode(jsonAddress);
data.add(MovieCategories.fromJson(jsonResponse));
print(data);
return data;
}
}
Solution 1:[1]
Your problem is this line:
var list = json.values as List;
Map.values isn't a List, it's an Iterable. If you want it as a list, you need to convert it:
var list = json.values.toList();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abion47 |
