prefer_final_in_for_each

Group: style

Maturity: stable

Dart SDK: >= 2.1.1 • (Linter v0.1.78)

Since info is static, may be stale
has-fix

View all Lint Rules

Using the Linter

DO prefer declaring for-each loop variables as final if they are not reassigned later in the code.

Declaring for-each loop variables as final when possible is a good practice because it helps avoid accidental reassignments and allows the compiler to do optimizations.

BAD:

for (var element in elements) { // LINT
  print('Element: $element');
}

GOOD:

for (final element in elements) {
  print('Element: $element');
}

GOOD:

for (var element in elements) {
  element = element + element;
  print('Element: $element');
}

Usage

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

linter:
  rules:
    - prefer_final_in_for_each