Flutter调用TMDB API时出现Unexpected instance of model class错误
问题原因
你看到的[Instance of 'TrendingModel'...]输出不是解析异常,属于Dart语言的默认行为:
- 自定义类如果没有重写
toString()方法,直接打印类实例时,控制台只会输出Instance of '类名'的固定格式,不会自动展示实例内部的字段赋值情况。 - 你当前的JSON解析逻辑本身可以正常运行,只是打印方式不对导致看不到具体字段值。额外注意你贴的接口返回示例里写的列表键是
result,实际TMDB trending接口返回的列表键是results,和你代码里的取值键一致,注意不要写错键名即可。
解决方案
方案1:重写模型类的toString()方法(最常用)
在TrendingModel类中重写toString()方法,自定义实例打印时的输出格式,修改后的模型类代码如下:
class TrendingModel { int? id; String? title; String? originalTitle; String? overview; String? posterPath; String? bannerPath; String? releaseDate; TrendingModel({ this.id, this.title, this.originalTitle, this.overview, this.posterPath, this.bannerPath, this.releaseDate, }); // 重写toString,自定义打印内容 @override String toString() { return 'TrendingModel(id: $id, title: $title, originalTitle: $originalTitle, overview: $overview, posterPath: $posterPath, bannerPath: $bannerPath, releaseDate: $releaseDate)'; } factory TrendingModel.fromJson(Map<String, dynamic> json) { return TrendingModel( bannerPath: json["backdrop_path"], id: json["id"], // 适配电影、电视剧两种条目的字段差异 title: json["title"] ?? json["name"], originalTitle: json["original_title"] ?? json["original_name"], overview: json["overview"], posterPath: json["poster_path"], releaseDate: json["release_date"] ?? json["first_air_date"], ); } }
重写完成后再打印解析得到的列表,控制台就会输出每个实例的具体字段值。
方案2:打印时手动转换为可输出结构
如果不想修改模型类,打印时不要直接输出实例列表,手动把实例字段拼成Map/字符串再打印即可:
// 替换原有的print(movie); print(movie.map((item) => { 'id': item.id, 'title': item.title, 'poster': item.posterPath }).toList());
方案3:调试断点查看
开发阶段可以直接在解析完成的代码行打调试断点,在IDE调试面板或Flutter DevTools中直接展开列表内的实例,可视化查看所有字段的赋值情况,比打印日志更适合排查解析问题。
补充提示:TMDB的trending/all接口会同时返回电影和电视剧两类数据,两类数据的标题、原名、发布日期字段名不一致,上面的fromJson代码已经加了空值兜底,避免电视剧类型的对应字段解析为空。
内容的提问来源于stack exchange,提问作者saurabh raturi
相关产品推荐
相关产品推荐

