How can I search a list of classes for a specific property of the class?

Viewed 315

I have a class called Product which has two properties.

class Product {
  final String productName;
  final int expiryTime;

  Product(this.productName, this.expiryTime);
}

I then made a list of Products like below:

List<Product> allProducts = [
  Product('Apple', 5),
  Product('Banana', 3),
  Product('Pear', 7),
];

I want to search this list to check if a product is in it. For example, if I check if 'Apple' is in the list allProducts, it should be true.

For other lists I have used list.contains() but I cannot see how to use it for this type of list.

2 Answers

any returns true if the given condition is met in dart list. Hope it helps

var found = allProducts.any((e) => e.productName == "Apple");
print(found);

You can do:

  allProducts.forEach((res){
    if(res.productName == "Apple"){
      print("True");
    }
  });

Iterate inside the list, then check if res.productName is equal to Apple

Related