Rules / Complexity / avoid-function-literals-in-foreach-calls
avoid-function-literals-in-foreach-calls
Flags a function literal passed to forEach, e.g. xs.forEach((e) { ... }).
A for-in loop reads more clearly than forEach with a closure, and unlike
the closure it can await, break, and continue, and it allocates no
per-call function object. The rule fires only for single-parameter
function-literal callbacks, so Map.forEach (which takes two parameters) is
left alone, as are tear-offs like xs.forEach(print) and null-aware
xs?.forEach(...).
Invalid
example.dartdart
void bad() {
items.forEach((e) { print(e); });
list.forEach((x) => print(x));
names.forEach((name) { save(name); });
values.forEach((v) => sink(v));
data.forEach((item) { process(item); log(item); });
}
Avoid using a function literal in a 'forEach' call; use a for-in loop instead.
1void bad() {
2 items.forEach((e) { print(e); });
∙
Avoid using a function literal in a 'forEach' call; use a for-in loop instead.
2 items.forEach((e) { print(e); });
3 list.forEach((x) => print(x));
∙
Avoid using a function literal in a 'forEach' call; use a for-in loop instead.
3 list.forEach((x) => print(x));
4 names.forEach((name) { save(name); });
∙
Avoid using a function literal in a 'forEach' call; use a for-in loop instead.
4 names.forEach((name) { save(name); });
5 values.forEach((v) => sink(v));
∙
Avoid using a function literal in a 'forEach' call; use a for-in loop instead.
5 values.forEach((v) => sink(v));
6 data.forEach((item) { process(item); log(item); });
∙
Valid
example.dartdart
void good() {
items.forEach(print);
list?.forEach((e) => print(e));
map.forEach((k, v) => print('$k$v'));
for (final e in items) {
print(e);
}
numbers.map((e) => e * 2);
}
How to configure
Set the severity of avoid-function-literals-in-foreach-calls in your falcon.json:
falcon.jsonjson
{
"linter": {
"rules": {
"complexity": {
"avoid-function-literals-in-foreach-calls": "error"
}
}
}
}