prefer_final_parameters
Prefer final for parameter declarations if they are not reassigned.
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:
void badParameter(String label) { // LINT
print(label);
}
GOOD:
void goodParameter(final String label) { // OK
print(label);
}
BAD:
void badExpression(int value) => print(value); // LINT
GOOD:
void goodExpression(final int value) => print(value); // OK
BAD:
[1, 4, 6, 8].forEach((value) => print(value + 2)); // LINT
GOOD:
[1, 4, 6, 8].forEach((final value) => print(value + 2)); // OK
GOOD:
void mutableParameter(String label) { // OK
print(label);
label = 'Hello Linter!';
print(label);
}
Incompatible rules
#The prefer_final_parameters
rule is incompatible with the following rules:
Enable
#To enable the prefer_final_parameters
rule,
add prefer_final_parameters
under linter > rules in your
analysis_options.yaml
file:
linter:
rules:
- prefer_final_parameters
If you're instead using the YAML map syntax to configure linter rules,
add prefer_final_parameters: true
under linter > rules:
linter:
rules:
prefer_final_parameters: true
除非另有说明,文档之所提及适用于 Dart 3.7.1 版本,本页面最后更新时间: 2025-01-27。 查看文档源码 或者 报告页面问题。