Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Dart : How does .where() function work?

Tags:

dart

var fruits = ['apples', 'oranges', 'bananas'];
fruits[0]; // apples
fruits.add('pears');
fruits.length == 4;
fruits.where((f) => f.startsWith('a')).toList();

The example in the documentation shows the above. I dont really understand the documentation of the method either.

https://api.dartlang.org/stable/1.21.1/dart-collection/IterableMixin/where.html

I currently see a lambda function as a parameter inside where, with where having the argument f. What is f though? Im a bit confused.

It would be great if I could see a working example. As it stands now I dont really get it. I dont know how it works or what it really does apart from that it acts as some sort of filter.

like image 709
Asperger Avatar asked Jan 27 '17 09:01

Asperger


1 Answers

Is an anonymous function and f is the parameter it accepts

(f) => f.startsWith('a')

where(...) calls that passed function for each element in fruits and returns an iterable that only emits the values where the function returned true

where(...) is lazy, therefore the iteration and call of the passed function will only happen when the result is actually accessed, like with .toList().

DartPad example

update

"anonymous" means the function has no name in contrary to a named function like

myFilter(f) => f.startsWith('a');

main() {
  fruits.where(myFilter).toList();
}

also

myFilter(f) => f.startsWith('a');

is just a shorter form of

myFilter(f) {
  return f.startsWith('a');
}
like image 187
Günter Zöchbauer Avatar answered Oct 19 '22 22:10

Günter Zöchbauer