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

Flutter BLoC获取API列表数据报错:List与Map类型不匹配

解决API数据获取的类型不匹配问题

出现Type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'错误的核心原因是:你请求的API返回的是医院对象的数组(List),但你的代码试图把整个数组当成单个医院对象(Map)去解析,自然类型不匹配。

以下是具体修改步骤:

1. 修正模型命名与结构

原来的HospitalListModel其实是单个医院的数据模型,先改名并保持结构不变:

class HospitalModel {
  int? id;
  String? title;
  String? content;
  String? image;
  String? phone;
  String? coordinates;
  String? website;
  String? createdAt;
  String? updatedAt;

  HospitalModel({
    this.id,
    this.title,
    this.content,
    this.image,
    this.phone,
    this.coordinates,
    this.website,
    this.createdAt,
    this.updatedAt,
  });

  HospitalModel.fromJson(Map<String, dynamic> json) {
    id = json['id'] as int?;
    title = json['title'] as String?;
    content = json['content'] as String?;
    image = json['image'] as String?;
    phone = json['phone'] as String?;
    coordinates = json['coordinates'] as String?;
    website = json['website'] as String?;
    createdAt = json['created_at'] as String?;
    updatedAt = json['updated_at'] as String?;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> json = <String, dynamic>{};
    json['id'] = id;
    json['title'] = title;
    json['content'] = content;
    json['image'] = image;
    json['phone'] = phone;
    json['coordinates'] = coordinates;
    json['website'] = website;
    json['created_at'] = createdAt;
    json['updated_at'] = updatedAt;
    return json;
  }
}

2. 修改ApiProvider的请求逻辑

因为API返回的是数组,所以要遍历数组,把每个元素转成HospitalModel对象,最终返回List<HospitalModel>:

class ApiProvider {
  final Dio _dio = Dio();
  final String _url = 'http://lovemonster.my.id/hospital';

  Future<List<HospitalModel>> fetchHospitalList() async {
    try {
      Response response = await _dio.get(_url);
      // 遍历返回的数组,逐个解析为HospitalModel
      return (response.data as List).map((item) => HospitalModel.fromJson(item)).toList();
    } catch (error, stacktrace) {
      print("Exception occurred: $error stackTrace: $stacktrace");
      return Future.error("获取医院列表失败");
    }
  }
}

3. 更新ApiRepository的返回类型

对应修改返回值类型,和Provider保持一致:

class ApiRepository {
  final _provider = ApiProvider();

  Future<List<HospitalModel>> fetchHospitalList() {
    return _provider.fetchHospitalList();
  }
}
class NetworkError extends Error {}

4. 在BLoC中使用

之后在你的BLoC逻辑里,调用apiRepository.fetchHospitalList()就能拿到正确的医院列表了,直接在BLoC Builder里处理这个List即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:25:42