Flutter/Dart中类的使用及购物车打印显示Instance of Product问题求助
购物车商品打印显示异常解决方法
问题说明
创建product类并定义空购物车列表cart后,向购物车添加商品并打印时,控制台仅输出Instance of Product,无法查看商品具体信息,需要确保购物车可正常使用。
相关代码
Product类
class product { late String name; late int id,size,price; product(String name,int id,int size,int price){ this.name=name; this.size=size; this.id=id; this.price=price; } }
购物车定义
List cart=[];
商品列表页面(cpproducts1)关键代码
onTap: (){ cart.add(prod[index]); print(cart); },
解决步骤
1. 重写product类的toString()方法
Dart默认打印对象时会输出Instance of [类名],重写该方法可返回商品的具体属性信息:
class product { late String name; late int id, size, price; product(String name, int id, int size, int price) { this.name = name; this.size = size; this.id = id; this.price = price; } @override String toString() { return '商品信息:名称=$name,ID=$id,尺码=$size,价格=\$$price'; } }
2. 给购物车列表指定类型
将无类型的List cart=[];改为明确的泛型列表,避免类型错误,提升代码可读性:
List<product> cart = [];
3. 验证功能正常
修改后再次添加商品并打印cart,控制台会输出每个商品的详细信息,后续也可正常操作购物车中的商品,比如遍历计算总价:
// 示例:计算购物车总金额 int total = 0; for (var item in cart) { total += item.price; } print('购物车总价:\$$total');
代码规范优化(可选)
- Dart类名建议首字母大写,将
product改为Product,符合行业规范 - 使用简化构造函数写法,精简代码:
class Product { late String name; late int id, size, price; Product(this.name, this.id, this.size, this.price); @override String toString() { return 'Product{name: $name, id: $id, size: $size, price: $price}'; } }
内容的提问来源于stack exchange,提问作者Farjaad Waseem
相关产品推荐
相关产品推荐

