【问题标题】:How can I search a list of classes for a specific property of the class?如何在类列表中搜索类的特定属性?
【发布时间】:2020-08-26 07:30:54
【问题描述】:

我有一个名为Product 的类,它有两个属性。

class Product {
  final String productName;
  final int expiryTime;

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

然后我列出了Products,如下所示:

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

我想搜索此列表以检查其中是否包含产品。例如,如果我检查“Apple”是否在列表allProducts 中,它应该是true

对于其他列表,我使用了list.contains(),但我不知道如何将它用于此类列表。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    any 如果在 dart 列表中满足给定条件,则返回 true。希望对你有帮助

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

    【讨论】:

    • Zain,你能看看我的问题吗?我正在使用 Flutter 解决问题,现在无法理解我做错了什么 - stackoverflow.com/questions/61711139/… 我将不胜感激有关代码的任何提示
    • 当然让我检查
    【解决方案2】:

    你可以这样做:

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

    在列表中迭代,然后检查res.productName是否等于Apple

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-24
      相关资源
      最近更新 更多