Home > Blockchain >  List contains method returns false despite object having the same value - Dart
List contains method returns false despite object having the same value - Dart

Time:08-06

I'm developing a 'cart to add' functionality. So there is a list named cartList which stores cartModel data. What I'm trying to do here is that once user has added the item to cartList, next time, when user tries to add the same item again, it would throw a message that item has already added to the cart

here is the code

ElevatedButton(
                        onPressed: (){
                          CartModel cartModel = CartModel(
                              productId: widget.productModel.productId,
                              productTitle: widget.productModel.productTitle,
                              productVariant: widget.productModel.productVariant,
                              productType: widget.productModel.productType,
                              images: widget.productModel.images,
                              options: widget.productModel.options,
                              selectedValue: selectedValue,
                              cartQuantity: 1
                          );
                          value.addProduct(cartModel, context);
                        },
                        child: Text('ADD TO CART', style: GoogleFonts.oswald(color: Colors.white))
                    ),

  void addProduct(CartModel cartModel, BuildContext context){
    if(cartList.contains(cartModel)){ // returns false 
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('ALREADY ADDED TO THE CART', style: GoogleFonts.oswald(color: Colors.white)), backgroundColor: Colors.redAccent));
    } else {
      cartList.add(cartModel);
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('ADDED TO THE CART', style: GoogleFonts.oswald(color: Colors.white)), backgroundColor: Colors.redAccent));
    }
    notifyListeners();
  }

CodePudding user response:

contains uses == operator.

To check if an item exist in a list, you can use any operator. The correct way for your case would be:

bool exist = cartList.any((item) => {item.productId == cartModel.productId && item.productVariant == cartModel.productVariant})
if (exist) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('ALREADY ADDED TO THE CART', style: GoogleFonts.oswald(color: Colors.white)), backgroundColor: Colors.redAccent));
} else {
    cartList.add(cartModel);
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('ADDED TO THE CART', style: GoogleFonts.oswald(color: Colors.white)), backgroundColor: Colors.redAccent));
}
  • Related