【问题标题】:Is there a way to pass an argument to the `test` function of the `firstWhere` method of an iterable有没有办法将参数传递给可迭代的`firstWhere`方法的`test`函数
【发布时间】:2021-12-31 12:16:54
【问题描述】:

我正在学习 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

【问题讨论】:

    标签: dart iterable


    【解决方案1】:

    当然,但是像这样:

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

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

    【讨论】:

    • 或者:final foundItem = items.firstWhere((item) => predicate(item, minLength: 6));,如果你想使用现有的功能。
    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    相关资源
    最近更新 更多