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

纵然是瞬间 提交于 2021-01-27 04:10:31

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/41890394/google-dart-how-does-where-function-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!