prefer_foreach
Use forEach
to only apply a function to all the elements.
This rule is available as of Dart 2.0.
Details
#DO use forEach
if you are only going to apply a function or a method
to all the elements of an iterable.
Using forEach
when you are only going to apply a function or method to all
elements of an iterable is a good practice because it makes your code more
terse.
BAD:
for (final key in map.keys.toList()) {
map.remove(key);
}
GOOD:
map.keys.toList().forEach(map.remove);
NOTE: Replacing a for each statement with a forEach call may change the behavior in the case where there are side-effects on the iterable itself.
for (final v in myList) {
foo().f(v); // This code invokes foo() many times.
}
myList.forEach(foo().f); // But this one invokes foo() just once.
Usage
#To enable the prefer_foreach
rule,
add prefer_foreach
under linter > rules in your
analysis_options.yaml
file:
linter:
rules:
- prefer_foreach
除非另有说明,文档之所提及适用于 Dart 3.5.4 版本,本页面最后更新时间: 2024-08-02。 查看文档源码 或者 报告页面问题。