使用“ where”在dart中搜索对象列表以查找特定对象

Raj*_*war 5 dart

我想根据其成员变量的特定搜索条件从列表中获取一个对象

这是我正在使用的代码

class foo
{
  foo(this._a);
  int _a;
}

List<foo> lst = new List<foo>();

main()
{
  foo f = new foo(12);

  lst.add(f);
  List<foo> result = lst.where( (foo m) {
    return m._a == 12;
  });

  print(result[0]._a);
}
Run Code Online (Sandbox Code Playgroud)

我遇到错误,不确定如何解决

未捕获的异常:

TypeError: Instance of 'WhereIterable<foo>': type 'WhereIterable<foo>' is not a subtype of type 'List<foo>'
Run Code Online (Sandbox Code Playgroud)

我正在尝试搜索其成员变量为对象的对象a == 12。关于我可能做错了什么建议?

lrn*_*lrn 9

Iterable.where方法返回一个满足您测试的所有成员的可迭代对象,而不仅仅是一个,并且它是一个延迟计算的可迭代对象,而不是列表。您可以lst.where(test).toList()用来创建列表,但是如果只需要第一个元素,那就太过分了。

您可以lst.firstWhere(test)改为只返回第一个元素,也可以lst.where(test).first有效地执行相同的操作。无论哪种情况,如果测试没有匹配的元素,代码都会抛出。

为了避免抛出,可以使用var result = lst.firstWhere(test, orElse: () => null)so,以便null在没有此类元素的情况下获取。

另一种选择是

foo result;
int index = lst.indexWhere(test); 
if (index >= 0) result = lst[index];
Run Code Online (Sandbox Code Playgroud)