Flutter getMyPoint方法类型转换异常:String无法转为int?
问题原因与修复方案
问题原因
核心问题是接口返回的max_product_point_discount字段值变为了空字符串"",但你的Point实体类中该字段定义为int?类型。JSON解析时,空字符串无法直接转换为int?类型,触发type 'String' is not a subtype of type 'int?'异常,导致积分数据获取失败,最终购物车积分不显示。
之前应用运行正常是因为接口该字段始终返回数字或null,近期接口逻辑变更后出现了空字符串的情况,触发了未处理的类型转换边界场景。
修复方案
方案1:手动修改实体类解析逻辑
如果是手动编写JSON转实体的代码,在解析max_product_point_discount时增加空字符串判断,将其转为null或符合业务需求的数字(比如0):
假设你的Point类解析代码如下:
Point.fromJson(Map<String, dynamic> json) { maxProductPointDiscount = json['max_product_point_discount'] as int?; // 其他字段解析逻辑 }
修改为:
Point.fromJson(Map<String, dynamic> json) { final discountVal = json['max_product_point_discount']; if (discountVal is String) { maxProductPointDiscount = discountVal.isEmpty ? null : int.tryParse(discountVal); } else { maxProductPointDiscount = discountVal is int ? discountVal : null; } // 其他字段解析逻辑 }
方案2:用json_serializable添加自定义转换器
如果使用json_serializable生成解析代码,需要自定义转换器处理字符串转int的边界情况:
- 先创建转换器类:
class StringToNullableIntConverter implements JsonConverter<int?, dynamic> { const StringToNullableIntConverter(); @override int? fromJson(dynamic json) { if (json is String) { return json.isEmpty ? null : int.tryParse(json); } return json is int ? json : null; } @override dynamic toJson(int? value) => value; }
- 在
Point实体类的对应字段上添加注解:
class Point { @StringToNullableIntConverter() final int? maxProductPointDiscount; // 其他字段定义 Point({required this.maxProductPointDiscount, /* 其他参数 */}); factory Point.fromJson(Map<String, dynamic> json) => _$PointFromJson(json); Map<String, dynamic> toJson() => _$PointToJson(this); }
方案3:协调后端修复接口(可选)
如果有权限对接后端开发,可以要求后端将max_product_point_discount的空值统一返回null或数字0,而非空字符串,从源头避免类型转换问题。
修复完成后,重新调用getMyPoint方法,验证控制台无类型转换异常,确认购物车积分正常显示。
内容的提问来源于stack exchange,提问作者Panagiotis
相关产品推荐
相关产品推荐

