Skip to main content

prefer_foreach

Learn about the prefer_foreach linter rule.

Stable
Fix available

Use forEach to only apply a function to all the elements.

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:

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. 

Enable

#

To enable the prefer_foreach rule, add prefer_foreach under linter > rules in your analysis_options.yaml file:

analysis_options.yaml
yaml
linter:  rules:  - prefer_foreach 

If you're instead using the YAML map syntax to configure linter rules, add prefer_foreach: true under linter > rules:

analysis_options.yaml
yaml
linter:  rules:  prefer_foreach: true