Почему не обновляется общий вес, когда я убираю товары из корзины в Riverpod?

Это мой класс, который показывает общий вес моей тележки. Я делаю приложение другого типа, которое должно показывать общий вес, а не цену товаров, помещенных в корзину. Для этого я использую 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,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
               //  )
                ],
              ),
            ),
            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) {
      state = state.where((product) => product.id != id).toList();
    }
  }

При добавлении новых товаров все работает нормально. Проблема в том, что когда я удаляю товары из корзины, общий вес не обновляется.

Это почему?

2 ответа

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();

Это работает для моего проекта.

      void deleteProduct(String id) {
    state.removeWhere((element) => element.id == id);
    state = [...state];
}

состояние = [... состояние]; оператор распространения с текущим состоянием, которое переназначается, вызывая обновление

Другие вопросы по тегам