我是新手,正在学习一门关于Udemy的课程.我有一个名为Item的模型,它有final
个属性,如下所示:
class Item {
final String id;
final String title;
final int quantity;
final double price;
Item({
required this.id,
required this.title,
required this.quantity,
required this.price,
});
}
Item
由另一个类Cart
使用,它在 map 中存储一个Item
的列表,它有一个removeSingleItem
方法,它如下所示地减少数量:
class Cart with ChangeNotifier {
Map<String, Item> _items = {};
void removeSingleItem(String productId) {
if (!_items.containsKey(productId)) {
return;
}
if (_items[productId]!.quantity > 1) {
_items.update(
productId,
(existingCartItem) => Item(
id: existingCartItem.id,
price: existingCartItem.price,
quantity: existingCartItem.quantity - 1,
title: existingCartItem.title,
));
} else {
_items.remove(productId);
}
notifyListeners();
}
正如我们所看到的,购物车是一个提供者.我的问题是,为什么我们要用_items.update
来创建一个新的Item
?在将属性设置为非最终属性后,不像这样直接修改Item对象的内容:
_Items[ProductID]!.Quantity-=1;
这会不会给国家管理带来问题?因为在演示应用程序中,即使我们没有创建一个完整的新Item对象,Orders屏幕(新的Scaffold)似乎也会正确更新.
课程的 comments 部分不再处于活动状态,因此请在此处提问.谢谢你的帮助!