Flutter JSON解析类型不匹配异常问题求助
问题分析与解决方案
异常原因
报错type '(dynamic) => ProductItem' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform'的核心原因:你在对Map类型的对象调用map方法,但传入的转换函数是为List设计的(仅接受单个dynamic参数)。也就是说,代码中jsonResponse['products']被识别为Map,而非预期的List<dynamic>。
针对性修复步骤
1. 修正HTTP请求头
你的请求头设置Accept: text/plain不符合API返回的JSON格式,会导致服务器返回的数据解析异常,改为JSON格式的请求头:
final response = await http.get( Uri.parse(HomeApi().getWatchesCategoryProducts), headers: {'Accept': 'application/json'}, // 修改此处 );
2. 显式强制转换JSON数组类型
在解析products列表时,显式将jsonResponse['products']转为List类型,避免dynamic类型推断错误:
if (response.statusCode == 200) { final jsonResponse = jsonDecode(response.body); // 强制转换为List,避免类型推断错误 final List<dynamic> productsJson = jsonResponse['products'] as List; List<ProductItem> productsList = productsJson .map((item) => ProductItem.fromJson(item as Map<String, dynamic>)) .toList(); return productsList; }
3. 增强模型类的空安全与健壮性
在ProductItem.fromJson中,对pictures数组做非空判断,避免空数组导致的索引越界:
factory ProductItem.fromJson(Map<String, dynamic> json) { final List<dynamic> pictures = json['pictures'] as List? ?? []; final Map<String, dynamic>? firstPicture = pictures.isNotEmpty ? pictures[0] as Map<String, dynamic> : null; return ProductItem( id: json['id'] as int, productName: json['productName'] as String, productDescription: json['productDescription'] as String, unitPrice: json['unitPrice'] as int, color: json['color'] as String, categoryName: json['categoryName'] as String, supplierHandle: json['supplierHandle'] as String, frontImage: firstPicture?['front'] as String ?? '', backImage: firstPicture?['back'] as String?, ); }
4. 调试验证(可选)
如果问题仍存在,在解析前打印jsonResponse['products']的类型,确认是否为List:
print('products type: ${jsonResponse['products'].runtimeType}');
如果输出为Map类型,说明API返回的products字段格式不符合预期,需要对接后端确认接口返回结构。
内容的提问来源于stack exchange,提问作者Ebram Shereen
相关产品推荐
相关产品推荐

