Flutter开发:ListView加载数据时int与double类型不匹配错误求助
解决Flutter中type 'int' is not a subtype of type 'double?'错误
问题根源是接口返回的kcal、fats、carbs、protein字段为整数类型(int),但你的FoodModel中这些字段定义为double?,直接赋值会触发类型不兼容错误。之前接口返回字符串时,Flutter会隐式处理类型转换,现在返回原始数值类型就暴露了这个问题。
修复方案
修改FoodModel的fromJson构造函数,对数值字段进行显式类型转换,确保int类型能转为double类型,同时兼容null的情况:
class FoodModel { int? foodId; String? foodNameEn; String? foodNameAr; double? kcal; double? fats; double? carbs; double? protein; String? createTime; int? foodTypeId; String? foodImage; FoodModel( {this.foodId, this.foodNameEn, this.foodNameAr, this.kcal, this.fats, this.carbs, this.protein, this.createTime, this.foodTypeId, this.foodImage}); FoodModel.fromJson(Map<String, dynamic> json) { foodId = json['food_id']; foodNameEn = json['food_name_en']; foodNameAr = json['food_name_ar']; // 显式转换数值类型,兼容int和double,同时处理null kcal = json['kcal']?.toDouble(); fats = json['fats']?.toDouble(); carbs = json['carbs']?.toDouble(); protein = json['protein']?.toDouble(); createTime = json['create_time']; foodTypeId = json['food_type_id']; foodImage = json['food_image']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['food_id'] = foodId; data['food_name_en'] = foodNameEn; data['food_name_ar'] = foodNameAr; data['kcal'] = kcal; data['fats'] = fats; data['carbs'] = carbs; data['protein'] = protein; data['create_time'] = createTime; data['food_type_id'] = foodTypeId; data['food_image'] = foodImage; return data; } }
说明
- 使用
?.toDouble()操作符:先判断字段是否为null,不为null则调用toDouble()将int转为double,避免空指针异常。 - 这种写法同时兼容接口返回int、double或null的情况,彻底解决类型不匹配问题。
内容的提问来源于stack exchange,提问作者Toxicless
相关产品推荐
相关产品推荐

