move-variable-closer-to-its-usage
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.
⚙️ Config
Set ignore-const
(default is false
) to ignore constant variables.
Set ignore-after-if
(default is true
) to disable additional mode for checking if a variable can be moved after the closes if statement.
dart_code_metrics:
...
rules:
...
- move-variable-closer-to-its-usage:
ignore-const: true
ignore-after-if: false
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;
}