You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter报错:_InternalLinkedHashMap非BannerModel子类型,求解决方案

解决Flutter报错:type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'BannerModel'

这个错误的核心原因是你直接将JSON解析后得到的Map<String, dynamic>类型数据,赋值给了BannerModel类型的变量——两者属于不同类型,无法直接转换。下面是两种可靠的解决方式:


方法一:手动实现类型转换构造方法

在你的BannerModel类中添加一个fromJson命名构造方法,负责把Map数据映射为类实例:

class BannerModel {
  final String id;
  final String imageUrl;
  // 根据你的业务需求添加其他属性

  // 默认构造方法
  BannerModel({required this.id, required this.imageUrl});

  // 新增:从Map转换为BannerModel的构造方法
  BannerModel.fromJson(Map<String, dynamic> json)
      : id = json['id'] as String,
        imageUrl = json['imageUrl'] as String;
}

使用时,将解析后的Map传入这个构造方法即可:

// 假设apiResponse是接口返回并解析后的Map数据
BannerModel banner = BannerModel.fromJson(apiResponse);

方法二:用json_serializable自动生成解析代码

如果你的模型类属性较多,手动写转换代码容易出错,推荐使用官方生态的json_serializable库自动生成:

  1. 添加依赖
    在项目的pubspec.yaml中加入以下依赖:
dependencies:
  json_annotation: ^4.8.1

dev_dependencies:
  build_runner: ^2.4.4
  json_serializable: ^6.7.0

执行flutter pub get安装依赖。

  1. 改造模型类
    给BannerModel添加注解并声明序列化方法:
import 'package:json_annotation/json_annotation.dart';

// 生成的代码会存放在这个文件中
part 'banner_model.g.dart';

@JsonSerializable()
class BannerModel {
  final String id;
  final String imageUrl;

  BannerModel({required this.id, required this.imageUrl});

  // 自动生成的fromJson方法
  factory BannerModel.fromJson(Map<String, dynamic> json) => _$BannerModelFromJson(json);
  // 可选:如果需要把模型转为Map,添加toJson方法
  Map<String, dynamic> toJson() => _$BannerModelToJson(this);
}
  1. 生成解析代码
    在终端运行以下命令,自动生成序列化/反序列化代码:
flutter pub run build_runner build

之后就可以像手动实现一样,用BannerModel.fromJson完成类型转换。


额外注意:列表数据的转换

如果接口返回的是Banner列表,不能直接将列表赋值给List<BannerModel>,需要遍历逐个转换:

// 错误示例:直接赋值会触发类型错误
List<BannerModel> banners = apiResponse['banners'];

// 正确示例:遍历列表完成转换
List<BannerModel> banners = (apiResponse['banners'] as List)
    .map((item) => BannerModel.fromJson(item as Map<String, dynamic>))
    .toList();

内容的提问来源于stack exchange,提问作者Mahmoud Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:46:58