Skip to main content

avoid-late-keyword

added in: 1.0.0 warning

Warns when a field or variable is declared with a late keyword.

late keyword enforces a variable's constraints at runtime instead of at compile time and since the variable is not definitely initialized, every time it is read, a runtime check is inserted to make sure it has been assigned a value. If it hasn’t, an exception will be thrown.

note

Use this rule if you want to avoid unexpected runtime exceptions.

Config

Set allow-initialized (default is false) to allow initialized late variable declarations.

Set ignored-types (default is [AnimationController]) to allow some variables of the given type to be declared with late.

dart_code_linter: ... rules: ...

- avoid-late-keyword:
allow-initialized: true

Example

Bad:

class Test {
late final field = 'string'; // LINT

final String anotherField = '';

String? nullableField;

late String uninitializedField; // LINT

void method() {
late final variable = 'string'; // LINT

final anotherVariable = '';

String? nullableVariable;

late String uninitializedVariable; // LINT
}
}

Good:

class Test {
final field = 'string';

final String anotherField = '';

String? nullableField;

String uninitializedField;

void method() {
final variable = 'string';

final anotherVariable = '';

String? nullableVariable;

String uninitializedVariable;
}
}