prefer_final_locals
Prefer final for variable declarations if they are not reassigned.
Details
#DO prefer declaring variables as final if they are not reassigned later in the code.
Declaring variables as final when possible is a good practice because it helps avoid accidental reassignments and allows the compiler to do optimizations.
BAD:
void badMethod() {
var label = 'hola mundo! badMethod'; // LINT
print(label);
}
GOOD:
void goodMethod() {
final label = 'hola mundo! goodMethod';
print(label);
}
GOOD:
void mutableCase() {
var label = 'hola mundo! mutableCase';
print(label);
label = 'hello world';
print(label);
}
Incompatible rules
#The prefer_final_locals
rule is incompatible with the following rules:
Enable
#To enable the prefer_final_locals
rule,
add prefer_final_locals
under linter > rules in your
analysis_options.yaml
file:
linter:
rules:
- prefer_final_locals
If you're instead using the YAML map syntax to configure linter rules,
add prefer_final_locals: true
under linter > rules:
linter:
rules:
prefer_final_locals: true
除非另有说明,文档之所提及适用于 Dart 3.7.1 版本,本页面最后更新时间: 2025-01-27。 查看文档源码 或者 报告页面问题。