Skip to main content

avoid-unnecessary-local-late

added in: 1.10.0
🛠
Pro+
preset: recommended

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) {
late final String foo; // LINT: This local variable is assigned in all code paths before it is accessed. Try removing the 'late' keyword.
if (value == 1) {
foo = 'one';
} else {
foo = 'two';
}
...
}

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

void bad() {
late final String foo; // LINT: This local variable is assigned in all code paths before it is accessed. Try removing the 'late' keyword.
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';
}
...
}