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

Time:01-01

I am learning Dart and I'm following the Codelabs tutorial on iterable collections.

I have just read about the firstWhere method of iterables for finding the first element that satisfies some criterion.

The tutorial gives an example similar to the following:

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);
}

Which would print Popcorn as it is the first string with 6 or more characters.

I'm wondering whether it is possible to pass the minLength argument to predicate when calling items.firstWhere(predicate).

CodePudding user response:

sure, but like this:

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

what you example is doing is just extracting the method (String item) => item.length > minLength; to a separate global variable. which isn't necessary and I wouldn't recommend.

  • Related