prefer_final_parameters
Prefer final for parameter declarations if they are not reassigned.
This rule is available as of Dart 2.14.
This rule has a quick fix available.
Incompatible rules: unnecessary_final, avoid_final_parameters
Details
#DO prefer declaring parameters as final if they are not reassigned in the function body.
Declaring parameters as final when possible is a good practice because it helps avoid accidental reassignments.
BAD:
dart
void badParameter(String label) { // LINT
print(label);
}
GOOD:
dart
void goodParameter(final String label) { // OK
print(label);
}
BAD:
dart
void badExpression(int value) => print(value); // LINT
GOOD:
dart
void goodExpression(final int value) => print(value); // OK
BAD:
dart
[1, 4, 6, 8].forEach((value) => print(value + 2)); // LINT
GOOD:
dart
[1, 4, 6, 8].forEach((final value) => print(value + 2)); // OK
GOOD:
dart
void mutableParameter(String label) { // OK
print(label);
label = 'Hello Linter!';
print(label);
}
Usage
#To enable the prefer_final_parameters
rule,
add prefer_final_parameters
under linter > rules in your
analysis_options.yaml
file:
analysis_options.yaml
yaml
linter:
rules:
- prefer_final_parameters
除非另有说明,文档之所提及适用于 Dart 3.5.4 版本,本页面最后更新时间: 2024-08-02。 查看文档源码 或者 报告页面问题。