问题描述
这是我的课程,显示我的购物车中的总重量。我正在制作一种不同类型的应用程序,它需要显示总重量而不是放入购物车的物品的价格。为此,我正在使用 Riverpod。
class CartTotal extends ConsumerWidget {
@override
Widget build(BuildContext context,ScopedReader watch) {
final cart = watch(cartRiverpodProvider);
var f = new NumberFormat("#,###","en_US");
return Container(
padding: EdgeInsets.all(25),decoration: Boxdecoration(
color: AppColors.WHITE,border: Border(
top: BorderSide(
color: AppColors.LIGHT,width: 1,style: BorderStyle.solid,),child: SafeArea(
child: Row(
children: <Widget>[
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,crossAxisAlignment: CrossAxisAlignment.start,children: <Widget>[
Text(
"TOTAL",style: TextStyle(
fontSize: 12,color: AppColors.DARK,fontWeight: FontWeight.bold,// Obx(
// () =>
Text(
f.format(cart.totalWeight()),style: TextStyle(
fontSize: 26,color: AppColors.LIGHT_GREEN,// )
],Expanded(
child: Text("PURCHASE"),/*OrganicButton(
controller.placeOrder,"PURCHASE",Feather.chevron_right,*/
),],);
}
}
这是我的 StateNotifier。
class CartRiverpod extends StateNotifier<List<CartItemmodel>> {
CartRiverpod([List<CartItemmodel> products]) : super(products ?? []);
void add(ProductModel addProduct) {
bool productExists = false;
for (final product in state) {
if (product.id == addProduct.id) {
print("not added");
productExists = true;
OneContext().showSnackBar(
builder: (_) => SnackBar(content: Text('Item is already in shopping cart and cannot be added again!'),backgroundColor:Colors.red)
);
}
else {
}
}
if (productExists==false)
{
state = [
...state,new CartItemmodel(product: addProduct),];
print("added");
}
}
double totalWeight() {
double weight = 0;
for (final product in state) {
weight += product.product.weight;
}
return weight;
}
void remove(String id) {
List newList = state.where((product) => product.id != id).toList();
state = [...newList];
}
}
添加新产品时,一切正常。问题是当我从购物车中移除产品时,总重量不会更新。
这是为什么?
解决方法
StateNotifier 在获得新引用时触发更新。 例如,如果您正在使用 StateNotifier 下的列表并执行以下操作:
list.add(...) // not notifying the update
list = new List() // notifying the new reference
所以这发生在您的代码中:
// New reference thanks to the state = [...]
state = [
...state,new CartItemModel(product: addProduct),];
...
// Not giving a new reference to the list because you are setting state = state.
state = state.where((product) => product.id != id).toList();