Flutter:如何根据对象的字段值在对象的“集合”中搜索

时间:2019-11-30 03:02:32

标签: flutter dart set contains

按照标题,如何通过对象字段值在“设置”中搜索对象。以下是错误的代码,但希望能给出想法。我能找到的最接近的是How to search for an object in List<object> having its field value,但似乎并不适用。

class MyClass {
  final String a;
  final int b;
  final double c;
  MyClass({this.a, this.b, this.c});
}

class Check{
   Set<MyClass> mSet = new Set<MyClass>();
   contains() {
     mSet.add(new MyClass(a: "someString1", b:3, c:2.0));
     mSet.add(new MyClass(a: "someString2", b:1, c:3.0));
     mSet.add(new MyClass(a: "someString3", b:2, c:1.0));
     //following is not correct, but to get the idea...
     print(mSet.contains((item) => item.a == "someString1"));
     //need to return true
   }
}

>FALSE

例如,如果我添加,则同一问题可能适用于Set.where,Set.remove等。

var b = mSet.where((item) => item.a == "someString1");

b导致具有Set的所有值的迭代。

2 个答案:

答案 0 :(得分:0)

在飞镖中,Set扩展了Iterable。 There are lots of useful methods that you can call on an iterable that effectively sort the iterable according to some value

例如,您可以说:

unset NODE_ENV

答案 1 :(得分:0)

要总结然后遵循Kris的注释,要从对对象字段的查询中返回布尔值,不能使用“ 包含 ”。相反,您可以使用 where Set 类中的其他采用测试元素的方法,例如 (bool test(E element), { E orElse() }) → E)https://api.dartlang.org/stable/2.6.1/dart-core/Set-class.html), 并添加三元运算符以返回所需的布尔结果。

void main() {
  print(Check().contains());
}

class MyClass {
  final String a;
  final int b;
  final double c;
  MyClass({this.a, this.b, this.c});
}

class Check{
   Set<MyClass> mSet = new Set<MyClass>();
   bool contains() {
     mSet.add(new MyClass(a: "someString1", b:3, c:2.0));
     mSet.add(new MyClass(a: "someString2", b:1, c:3.0));
     mSet.add(new MyClass(a: "someString3", b:2, c:1.0));
     return mSet.where((item) => item.a  == "someString1").length > 0;
   }
}

>>true

编辑:尝试了其他一些“测试元素”方法(例如, firstWhere lastWhere > ),似乎“ 其中 ”是我测试过的唯一一种在没有匹配项时不会失败的方法。如果使用其他,则需要捕获,然后返回false。我坚持使用' where '和按照上述修改后的代码的最干净的解决方案三元组。如果只有“ 包含 ”包含测试元素。