/// 领域模型:购物车条目。 /// /// 不变(immutable):Riverpod 依赖"状态替换"而不是"状态修改"来触发更新, /// 所以模型类最好全是 final 字段。 library; import 'package:flutter/foundation.dart' show immutable; @immutable class CartItem { const CartItem({ required this.sku, required this.name, required this.cents, this.quantity = 1, }); final String sku; final String name; final int cents; final int quantity; int get subtotalCents => cents * quantity; CartItem copyWith({int? quantity}) => CartItem( sku: sku, name: name, cents: cents, quantity: quantity ?? this.quantity, ); /// 值语义:Riverpod/ChangeNotifier 的去重与测试都靠它。 @override bool operator ==(Object other) => other is CartItem && other.sku == sku && other.name == name && other.cents == cents && other.quantity == quantity; @override int get hashCode => Object.hash(sku, name, cents, quantity); @override String toString() => '$name ×$quantity'; } /// 演示用的商品目录。 const List catalog = [ CartItem(sku: 'coffee', name: '咖啡豆', cents: 8800), CartItem(sku: 'tea', name: '茉莉花茶', cents: 4500), CartItem(sku: 'mug', name: '马克杯', cents: 3200), ];