Skip to main content

move-variable-closer-to-its-usage

added in: 1.9.0
preset: recommended

Warns when a variable is declared in the outer block, but used only in the inner one.

Declaring variables too early can result in additional memory being allocated and potentially heavy calculations being performed.

Example

❌ Bad:

int withIf(bool condition) {
final value = 1; // LINT
if (condition) {
print(value);
}
}

✅ Good:

int withIf(bool condition) {
if (condition) {
final value = 1;
print(value);
}

final another = 1;
if (condition) {
print(another);
}

return another;
}