Flutter项目中int?无法赋值给num类型的错误求助
Flutter类型错误:int?无法赋值给num的解决方法
报错信息
报错代码行:
total += double.parse(value.price!) * value.quantity;
错误提示:
参数类型'int?'无法赋值给参数类型'num'。
cart_provider.dart 代码
import 'package:flutter/foundation.dart'; import 'package:myproject/model/CartModel.dart'; class Cart with ChangeNotifier { Map<String, CartModel> _items = {}; Map<String, CartModel> get items { return {..._items}; } void addItem({required String productId,price,title,name,image,quantity}){ if(_items.containsKey(productId)){ _items.update(productId, (value) => CartModel( key: value.key, name:value.name, image:value.image, price:value.price, quantity:value.quantity! + 1, totalPrice:value.totalPrice, )); notifyListeners(); }else{ _items.putIfAbsent(productId, () => CartModel( key:DateTime.now().toString(), name:name, image:image, price:price, totalPrice:0, quantity: 1, )); notifyListeners(); }; } double get totalToPay{ double total = 0.0; _items.forEach((key, value) { total += double.parse(value.price!) * value.quantity; }); return total; } }
cartModel.dart 代码
class CartModel { String? key; String? name; String? image; String? price; int? quantity; double? totalPrice; CartModel( {required this.key, required this.name, required this.image, required this.price, required this.quantity, required this.totalPrice}); CartModel.fromJson(Map<String, dynamic> json) { key = json['key']; name = json['name']; image = json['image']; price = json['price']; quantity = json['quantity'] as int; totalPrice = double.parse(json['totalPrice']); } Map<String,dynamic> toJson(){ final Map<String,dynamic> data = new Map<String,dynamic>(); data['key'] = this.key; data['name'] = this.name; data['image'] = this.image; data['price'] = this.price; data['quantity'] = this.quantity; data['totalPrice'] = this.totalPrice; return data; } }
问题原因
CartModel类中的quantity字段定义为可空类型int?,而double.parse(value.price!)返回的是double类型。Dart类型系统不允许可空的int?直接参与数值运算,因此抛出类型不匹配错误。
从业务逻辑看,购物车项的数量在初始化(addItem中设为1)和更新(quantity! + 1)时都确保了非空,实际不会出现null,但可空的类型定义导致了编译报错。
解决方案
方案1:临时修复(空断言)
直接在quantity后添加空断言!,告知编译器该值一定非空:
total += double.parse(value.price!) * value.quantity!;
方案2:默认值兜底
如果担心极端场景下quantity为空,可使用空合并运算符设置默认值:
total += double.parse(value.price!) * (value.quantity ?? 0);
方案3:优化类型定义(推荐)
修改CartModel,将quantity改为非空类型,从根源解决可空问题:
- 更新
cartModel.dart的字段定义:
int quantity; // 去掉?,改为非空int类型
- 调整
fromJson方法,确保解析时不会出现空值:
quantity = json['quantity'] as int? ?? 0;
此方案更符合业务逻辑,购物车项数量不可能为null,类型定义更严谨。
内容的提问来源于stack exchange,提问作者Mohammed Malek
相关产品推荐
相关产品推荐

