目录

prefer_final_in_for_each

目录

Prefer final in for-each loop variable if reference is not reassigned.

This rule is available as of Dart 2.1.

This rule has a quick fix available.

Incompatible rules: unnecessary_final

Details

#

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:

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

GOOD:

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

GOOD:

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

Usage

#

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

analysis_options.yaml
yaml
linter:
  rules:
    - prefer_final_in_for_each