Skip to main content

avoid-unnecessary-local-late

added in: 1.10.0
🛠
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
if (value == 1) {
foo = 'one';
} else {
foo = 'two';
}
...
}

int bad() {
late int bar = 0; // LINT
...
return bar;
}

void bad() {
late final String foo; // LINT
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';
}
...
}