prefer_foreach
Use forEach
to only apply a function to all the elements.
此规则自 Dart 2.0 版本起可用。
详情
#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:
dart
for (final key in map.keys.toList()) {
map.remove(key);
}
GOOD:
dart
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.
dart
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.
使用方法
#要启用 prefer_foreach
规则,请在你的 analysis_options.yaml
文件中,在 linter > rules 下添加 prefer_foreach
:
analysis_options.yaml
yaml
linter:
rules:
- prefer_foreach
除非另有说明,否则本网站上的文档反映的是 Dart 3.6.0。页面最后更新于 2025-02-05。 查看源代码 或 报告问题.