'dart - how do check id/name if contains in List?

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.



Solution 1:[1]

This solution is the quickest :

final bool _productIsInList = 
    _checkoutList.any((product) => product.name == getSelectedProduct.name);
if (_productIsInList) {
   // Do what you want to do if the list contains the product
} else {
   // Do what you want to do if the list contains 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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jack'