Skip to main content

avoid-late-keyword

added in: 1.6.0
⚙️🛠
Free+

Warns when a field or variable is declared with the 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 (example).

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

analysis_options.yaml
dart_code_metrics:
rules:
- avoid-late-keyword:
allow-initialized: false
ignored-types:
- AnimationController

Example

❌ Bad:

class Test {
late final field = 'string'; // LINT: Avoid using the 'late' keyword. Try removing it.
late String uninitializedField; // LINT: Avoid using the 'late' keyword. Try removing it.

void method() {
late final variable = 'string'; // LINT: Avoid using the 'late' keyword. Try removing it.
late String uninitializedVariable; // LINT: Avoid using the 'late' keyword. Try removing it.
}
}

✅ Good:

class Test {
final field = 'string'; // Correct, not a 'late' field
String? nullableField;

void method() {
final variable = 'string';
String uninitializedVariable;
}
}

Example with "allow-initialized"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-late-keyword:
allow-initialized: true

✅ Good:

class Test {
late final field = 'string'; // Correct, initialized
}

Example with "ignored-types"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-late-keyword:
ignored-types:
- AnimationController

✅ Good:

class Test {
late final AnimationController controller; // Correct, ignored
}

Additional Resources