Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading