prefer_final_fields

Group: style

Maturity: stable

Dart SDK: >= 2.0.0 • (Linter v0.1.27)

View the Project on GitHub dart-lang/linter

DO prefer declaring private fields as final if they are not reassigned later in the class.

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';
  }
}