Flutter解析API数据时遇类型转换错误:String无法转为int
类型转换错误问题分析与修复
核心错误原因
报错type 'String' is not a subtype of type 'int' in type cast,本质是你定义为int类型的字段,API返回了字符串格式的值,或转换逻辑存在错误,结合代码具体问题如下:
1. 强制类型转换不安全
在Product.fromJson中,你直接使用json['id'] as int这类强转操作。如果API返回的id、product_price等字段是字符串格式(比如"100"而非100),强转就会触发类型错误。
2. 数据结构处理混乱
- 你在
fetchProducts中同时做了三种矛盾的数据处理:先尝试把data转成单个Product,再用键值对方式循环(假设data是Map),最后又用数组map转换(假设data是List),说明你没明确API返回的data到底是单个对象还是数组。 - 如果
data是数组,extractedData.forEach((prodId, prodData) {...})的写法完全错误——List的forEach只有单个元素参数,没有键值对。 prodData.shop_id的点访问方式错误,prodData是Map类型,必须用prodData['shop_id']的键值对方式访问。
3. 字段赋值错误
fromJson中把json['store_name']赋值给了imagename,但构造函数里同时存在store_name参数,属于明显的赋值错误。
修复方案
第一步:明确API返回结构
先打印response.body确认data的结构:是产品数组(List)还是单个产品对象(Map)。以下假设data是产品数组,给出对应修复:
第二步:修改Product.fromJson,使用安全转换
将强转改为兼容字符串/int的安全转换,同时修复字段赋值错误:
factory Product.fromJson(Map<String, dynamic> json) { return Product( id: json['id'] is int ? json['id'] as int : int.tryParse(json['id'].toString()), shop_id: json['shop_id']?.toString(), category_id: json['category_id']?.toString(), sub_cat_id: json['sub_cat_id']?.toString(), product_title: json['product_title']?.toString(), product_Description: json['product_Description']?.toString(), product_image: json['product_image']?.toString(), product_price: json['product_price'] is int ? json['product_price'] as int : int.tryParse(json['product_price'].toString()), discount: json['discount'] is int ? json['discount'] as int : int.tryParse(json['discount'].toString()), quantity: json['quantity'] is int ? json['quantity'] as int : int.tryParse(json['quantity'].toString()), uom_id: json['uom_id'] is int ? json['uom_id'] as int : int.tryParse(json['uom_id'].toString()), in_stock: json['in_stock']?.toString(), created_at: json['created_at']?.toString(), updated_at: json['updated_at']?.toString(), imagename: json['imagename']?.toString(), // 修复原赋值错误 store_name: json['store_name']?.toString(), uom_name: json['uom_name']?.toString(), ); }
第三步:简化fetchProducts函数,删除冗余逻辑
保留正确的数组转换逻辑,去掉多余的错误处理:
Future<List<Product>> fetchProducts() async { final http.Response response = await http.get( Uri.parse('$productUrl/product_details/8'), headers: { HttpHeaders.acceptHeader: 'application/json', HttpHeaders.authorizationHeader: 'Bearer $token' }, ); // 打印响应确认数据结构,调试完成后可删除 print(response.body); final List<dynamic> productsData = jsonDecode(response.body)['data']; return productsData.map((productJson) => Product.fromJson(productJson as Map<String, dynamic>)).toList(); }
额外注意事项
- 如果API返回的
data是单个对象,需将返回类型改为Future<Product>,并调整转换逻辑。 - 所有可选字段(带
?的类型)都要处理null情况,避免空指针错误。 - 长期来看,推荐使用
json_serializable包自动生成序列化代码,减少手动转换的出错概率。
内容的提问来源于stack exchange,提问作者jacksparrow
相关产品推荐
相关产品推荐

