Reputation: 1217
I have a case when the user wants to add a product to the cart, before that I want to check the id/name
product whether or not he was in the cart.
if not then I will add it to the cart, if its already there I will just do edit (adding qty and price)
I have tried using the code below:
Future checkIfProductHasAdded(String uid) async {
for (var i = 0; i < _checkoutList.length; i++) {
print(_checkoutList[i].name);
if (_checkoutList[i].productName == getSelectedProduct.name) {
selectedProductCheckout(i);
print(getSelectedProduct.name +
"PRODUCT CHECKOUT HAS ADDED" +
_checkoutList[i].productName);
// await updateProductCheckout(uid);
break;
} else {
print(getSelectedProduct.name + "NOT FOUND AT PRODUCT CHECKOUT");
//await addProductToCheckout(uid);
break;
}
}
}
when I print()
value i
does not specify the position on the List
, but stays in position 0
.
how to make it work?
any answer will be appreciated.
Upvotes: 10
Views: 11147
Reputation: 2526
This solution is the quickest :
final bool _productIsInList =
_checkoutList.any((product) => product.name == getSelectedProduct.name);
if (_productIsInList) {
// The list contains the product
} else {
// The list does not contain the product
}
Note :
If you don't need to compare IDs/names, but you just want to check if a specific item is in a list, you can use _checkoutList.contains(item)
Upvotes: 8
Reputation: 678
You should check if a product exists in firstWhere clause. Something like this:
var product = _checkoutList.firstWhere((product) => product.productName == getSelectedProduct.name, orElse: () => null);
if (product == null) addProductToCheckout(uid);
else updateProductCheckout(uid);
Upvotes: 16