prefer_ final_ fields
Private field could be final
.
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:
class BadImmutable {
var _label = 'hola mundo! BadImmutable'; // LINT
var label = 'hola mundo! BadImmutable'; // OK
}
BAD:
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:
class GoodImmutable {
final label = 'hola mundo! BadImmutable', bla = 5; // OK
final _label = 'hola mundo! BadImmutable', _bla = 5; // OK
}
GOOD:
class GoodMutable {
var _label = 'hola mundo! GoodMutable';
void changeLabel() {
_label = 'hello world! GoodMutable';
}
}
BAD:
class AssignedInAllConstructors {
var _label; // LINT
AssignedInAllConstructors(this._label);
AssignedInAllConstructors.withDefault() : _label = 'Hello';
}
GOOD:
class NotAssignedInAllConstructors {
var _label; // OK
NotAssignedInAllConstructors();
NotAssignedInAllConstructors.withDefault() : _label = 'Hello';
}
Enable
#
To enable the
prefer_final_fields
rule, add
prefer_final_fields
under
linter > rules
in your
analysis_options.yaml
file:
linter:
rules:
- prefer_final_fields
If you're instead using the YAML map syntax to configure linter rules,
add
prefer_final_fields: true
under
linter > rules:
linter:
rules:
prefer_final_fields: true
Unless stated otherwise, the documentation on this site reflects Dart 3.9.2. Report an issue.