forEach
function in Dart allows to iterate over collection and do some actions with their elements. This is convenient and more
concise if you can pass the reference to the action directly through argument. For example this code:
void actOnList(List<String> list, Function(String) action) {
list.forEach(action);
}
looks more concise than this code:
void actOnList(List<String> list, Function(String) action) {
for(String s in list) {
action(s);
}
}
However, if you want to have a function literal as forEach
argument, you might face some limitations:
- If you place
return
in the function literal, it will only return the value for that iteration, while you might want to return from
the function.
- The bode of the function literal can’t contain
await
, while ordinary for
loop can contain it.
As a consequence, if you want to use forEach
with a function literal as an argument, it’s better to use a simple for
loop
instead.