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

Flutter解析API返回的空Map类型features字段报错求助

处理Flutter中JSON空Map字段features的解析问题

问题根源

你遇到的_TypeError (type '_Map<String, dynamic>' is not a subtype of type 'Iterable')错误,是因为误将features对应的Map类型数据当成了List(Iterable)去调用map()方法。API返回的features是键值对结构的Map(即使是空对象{}),而非数组,所以不能用List的map.toList()写法。

解决方案

根据features字段的实际业务用途,选择以下两种处理方式:

方式1:直接保留为Map<String, dynamic>

如果features中的值都是简单类型(字符串、布尔、数字等),无需额外封装为实体类,直接在PropertyInformation中定义为Map<String, dynamic>:

class PropertyInformation {
  final String addressLine1;
  final String city;
  // 其他字段...
  final Map<String, dynamic> features;

  PropertyInformation({
    required this.addressLine1,
    required this.city,
    // 其他字段...
    required this.features,
  });

  factory PropertyInformation.fromJson(Map<String, dynamic> json) {
    return PropertyInformation(
      addressLine1: json['addressLine1'],
      city: json['city'],
      // 其他字段赋值...
      // 处理空Map或null的情况,给默认空Map避免错误
      features: json['features'] as Map<String, dynamic>? ?? {},
    );
  }
}

方式2:映射为Map<String, Features>实体类

如果需要将features中的每个值封装为Features实体类,需使用Map的map()方法处理键值对:
首先定义Features类(根据实际字段调整):

class Features {
  final dynamic value; // 根据实际数据类型替换,比如bool、int等

  Features({required this.value});

  factory Features.fromJson(dynamic json) {
    return Features(value: json);
  }
}

然后在PropertyInformation.fromJson中处理:

factory PropertyInformation.fromJson(Map<String, dynamic> json) {
  return PropertyInformation(
    // 其他字段...
    features: (json['features'] as Map<String, dynamic>? ?? {}).map(
      (key, value) => MapEntry(key, Features.fromJson(value)),
    ),
  );
}

关键注意点

  • 先确认JSON字段类型:features是Map,不是List,不要混用List的遍历方法
  • 处理空值:通过?? {}给features设置默认空Map,避免null导致的异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 10:44:51