Skip to main content

avoid-unnecessary-local-late

Warns when a variable is assigned in all code branches before use.

The analyzer can determine statically whether a final local variable is assigned in all code paths before it is accessed. For that reason, it is not necessary to mark the variable as late.

Removing the late keyword can help you during a refactoring if you accidentally forget to assign a value to the variable. The variable will be highlighted by the analyzer.

Example

❌ Bad:

void bad(int value) {
// LINT: This local variable is assigned in all code paths before it is accessed.
// Try removing the 'late' keyword.
late final String foo;
if (value == 1) {
foo = 'one';
} else {
foo = 'two';
}
...
}

int bad() {
// LINT: This local variable is assigned in all code paths before it is accessed.
// Try removing the 'late' keyword.
late int bar = 0;
...
return bar;
}

void bad() {
// LINT: This local variable is assigned in all code paths before it is accessed.
// Try removing the 'late' keyword.
late final String foo;
try {
foo = 'value';
} catch (_) {
throw '1';
}
...
}

✅ Good:

void good(int value) {
final String foo;
if (value == 1) {
foo = 'one';
} else {
foo = 'two';
}
...
}

int good() {
int bar = 0;
...
return bar;
}

void good() {
final String foo;
try {
foo = 'value';
} catch (_) {
throw '1';
}
...
}