有没有办法将参数传递给可迭代的`firstWhere`方法的`test`函数

Is there a way to pass an argument to the `test` function of the `firstWhere` method of an iterable

我正在学习 Dart,我正在关注 Codelabs tutorial on iterable collections

我刚刚阅读了有关迭代器的 firstWhere 方法,用于查找满足某些条件的第一个元素。

教程给出了一个类似下面的例子:

bool predicate(String item, {int minLength = 6}) => item.length > minLength;

void main() {
  const items = ['Salad', 'Popcorn', 'Toast', 'Lasagne'];
  var foundItem = items.firstWhere(predicate);
  print(foundItem);
}

这将打印 Popcorn,因为它是具有 6 个或更多字符的第一个字符串。

我想知道是否可以在调用 items.firstWhere(predicate) 时将 minLength 参数传递给 predicate

当然可以,但是像这样:

final minLength = 6;
final foundItem = items.firstWhere((String item) => item.length > minLength));

您的示例所做的只是将方法 (String item) => item.length > minLength; 提取到一个单独的全局变量中。这不是必需的,我也不推荐。