Home > Mobile >  How to Remove cart item using provider
How to Remove cart item using provider

Time:05-31

I am using provider class in which i can add items to the cart list using product id but when i use the similar function to remove the item from cart it seems the function dont find the product id.or im doing somting wrong.

The function i used to add items in provider class:

//---------------------------------------add item
  void addItem({
    required CartItem product,
  }) {
    if (items.containsKey(product.id)) {
      final double value = product.price;
      items.update(
        product.id,
        (cartitem) => cartitem.copy(
          qnt: cartitem.qnt   1,
          price: cartitem.price   value,
        ),
      );
    } else {
      items.putIfAbsent(
          product.id,
          () => product.copy(
                id: DateTime.now().toString(),
                qnt: 1,
              ));
    }
    //---------------------------------------------------------total price
    _totalPrice = _totalPrice   product.price;

    notifyListeners();
  }

and the list in my cart:

 //----------- items cart list
  Widget buildCarditems(BuildContext context) {
    final porvidr = Provider.of<ShopProvider>(context, listen: false);

    if (porvidr.items.isEmpty) {
      return Center(
        child: Text(
          'Cart is Empty',
          style: TextStyle(
            color: Colors.white,
            fontSize: 20,
          ),
        ),
      );
    } else {
      return ListView(
        children: porvidr.items.values.map(buildcarditem).toList(),
      );
    }
  }

  //------------cart listtile
  Widget buildcarditem(CartItem c_item) {
    return ListTile(
        leading: CircleAvatar(backgroundImage: AssetImage(c_item.imgUrl)),
        title: Row(
          children: [
            Text(
              '${c_item.qnt}x',
              style: TextStyle(color: Colors.white),
            ),
            SizedBox(
              width: 10,
            ),
            Expanded(
              child: Text(
                c_item.title,
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
              ),
            ),
          ],
        ),
        trailing: Text(
          '\$${c_item.price}',
          style: TextStyle(
            color: Colors.white,
          ),
        ));
  }

where can i use the ontap function to get the product id?

CodePudding user response:

You can add it anywhere you want on each list item, you can wrap the list tile in n gesture detector widget. it depends on the requirement.

  • Related