prefer_final_fields
Private field could be final
.
This rule is available as of Dart 2.0.
Rule sets: recommended, flutter
This rule has a quick fix available.
Details
#From Effective Dart:
DO prefer declaring private fields as final
if they are not reassigned
later in the library.
Declaring fields as final
when possible is a good practice because it helps
avoid accidental reassignments and allows the compiler to do optimizations.
BAD:
dart
class BadImmutable {
var _label = 'hola mundo! BadImmutable'; // LINT
var label = 'hola mundo! BadImmutable'; // OK
}
BAD:
dart
class MultipleMutable {
var _label = 'hola mundo! GoodMutable', _offender = 'mumble mumble!'; // LINT
var _someOther; // LINT
MultipleMutable() : _someOther = 5;
MultipleMutable(this._someOther);
void changeLabel() {
_label= 'hello world! GoodMutable';
}
}
GOOD:
dart
class GoodImmutable {
final label = 'hola mundo! BadImmutable', bla = 5; // OK
final _label = 'hola mundo! BadImmutable', _bla = 5; // OK
}
GOOD:
dart
class GoodMutable {
var _label = 'hola mundo! GoodMutable';
void changeLabel() {
_label = 'hello world! GoodMutable';
}
}
BAD:
dart
class AssignedInAllConstructors {
var _label; // LINT
AssignedInAllConstructors(this._label);
AssignedInAllConstructors.withDefault() : _label = 'Hello';
}
GOOD:
dart
class NotAssignedInAllConstructors {
var _label; // OK
NotAssignedInAllConstructors();
NotAssignedInAllConstructors.withDefault() : _label = 'Hello';
}
Usage
#To enable the prefer_final_fields
rule,
add prefer_final_fields
under linter > rules in your
analysis_options.yaml
file:
analysis_options.yaml
yaml
linter:
rules:
- prefer_final_fields
除非另有说明,文档之所提及适用于 Dart 3.5.4 版本,本页面最后更新时间: 2024-08-02。 查看文档源码 或者 报告页面问题。