avoid_ function_ literals_ in_ foreach_ calls
Function literals shouldn't be passed to 'forEach'.
Description
#
The analyzer produces this diagnostic when the argument to
Iterable.forEach
is a closure.
Example
#
The following code produces this diagnostic because the argument to the
invocation of
forEach
is a closure:
void f(Iterable<String> s) {
s.forEach((e) => print(e));
}
Common fixes
#If the closure can be replaced by a tear-off, then replace the closure:
void f(Iterable<String> s) {
s.forEach(print);
}
If the closure can't be replaced by a tear-off, then use a
for
loop to
iterate over the elements:
void f(Iterable<String> s) {
for (var e in s) {
print(e);
}
}
Unless stated otherwise, the documentation on this site reflects Dart 3.9.2. Page last updated on 2025-9-1. View source or report an issue.