Flutter报错List<String>不是List<Map<dynamic,dynamic>>子类型怎么解决
问题原因
你的movies数组中,标题为A star is born的条目的cast字段格式与其他条目不一致:其他条目的cast是包含name、image键的Map数组,唯独该条目的cast是纯字符串数组。而你在MovieModel中声明cast的类型为List<Map>,解析到该条目时就会触发类型不匹配的运行时错误。
解决方案
方案1:统一数据源格式(推荐)
直接修正A star is born条目的cast格式,和其他条目保持一致:
{ 'title': 'A star is born', 'bannerPath': 'assets/images/star_movie.jpeg', 'id': 8, 'description': 'Der in die Jahre gekommene Rockstar Jackson Maine entdeckt die talentierte Sängerin Ally und verliebt sich in sie. Ally hätte ihren großen Traum von einer Musikkarriere fast aufgegeben. Jackson fördert sie und nimmt sie schließlich sogar mit auf seine Tournee.', 'cast': [ { 'name': 'Lady Gaga', 'image': 'assets/images/actors/lady-gaga.jpg' // 替换为对应演员的实际图片路径 }, { 'name': 'Bradley Cooper', 'image': 'assets/images/actors/bradley-cooper.jpg' // 替换为对应演员的实际图片路径 }, { 'name': 'Sam Elliot', 'image': 'assets/images/actors/sam-elliot.jpg' // 替换为对应演员的实际图片路径 }, ] },
方案2:兼容两种数据格式
如果你需要同时兼容字符串和Map两种cast格式,可以修改模型层的解析逻辑,先定义演员实体类,再在fromJson方法中做类型判断:
- 定义Cast实体类
class Cast { final String name; final String? image; Cast({required this.name, this.image}); }
- 修改MovieModel的cast类型和fromJson方法
class MovieModel { MovieModel({ required this.title, required this.cast, required this.bannerPath, required this.description, required this.id, }); factory MovieModel.fromJson(Map<String, dynamic> json) { final castRaw = json['cast'] as List; final processedCast = castRaw.map((item) { if (item is String) { return Cast(name: item); } else if (item is Map<String, dynamic>) { return Cast( name: item['name'], image: item['image'], ); } else { throw ArgumentError('Unsupported cast data type'); } }).toList(); return MovieModel( title: json['title'] as String, cast: processedCast, bannerPath: json['bannerPath'] as String, description: json['description'] as String, id: json['id'] as int, ); } String title; String bannerPath; String description; List<Cast> cast; int id; }
优化建议
后续开发中尽量避免使用List<Map>这类模糊的类型声明,优先定义明确的实体类,既能减少运行时类型错误,也方便后续代码维护。
内容的提问来源于stack exchange,提问作者Jonas Jacob Biermann
相关产品推荐
相关产品推荐

