prefer_final_locals
Prefer final for variable declarations if they are not reassigned.
This rule is available as of Dart 2.0.
This rule has a quick fix available.
Incompatible rules: unnecessary_final
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:
dart
void badMethod() {
var label = 'hola mundo! badMethod'; // LINT
print(label);
}
GOOD:
dart
void goodMethod() {
final label = 'hola mundo! goodMethod';
print(label);
}
GOOD:
dart
void mutableCase() {
var label = 'hola mundo! mutableCase';
print(label);
label = 'hello world';
print(label);
}
Usage
#To enable the prefer_final_locals
rule,
add prefer_final_locals
under linter > rules in your
analysis_options.yaml
file:
analysis_options.yaml
yaml
linter:
rules:
- prefer_final_locals
除非另有说明,文档之所提及适用于 Dart 3.5.4 版本,本页面最后更新时间: 2024-08-02。 查看文档源码 或者 报告页面问题。