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 (example).
Set ignore-after-if
(default is true
) to disable additional mode for checking if a variable can be moved after the closes if statement (example).
analysis_options.yaml
dart_code_metrics:
rules:
- move-variable-closer-to-its-usage:
ignore-const: false
ignore-after-if: true
Example
❌ Bad:
int withIf(bool condition) {
// LINT: This variable is only used inside the inner block. Try moving this declaration closer to where it is used.
final value = 1;
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;
}
Example with "ignore-const"
Config
analysis_options.yaml
dart_code_metrics:
rules:
- move-variable-closer-to-its-usage:
ignore-const: true
✅ Good:
int withIf(bool condition) {
const value = 1; // Correct, const declarations are ignored
if (condition) {
print(value);
}
}
Example with "ignore-after-if"
Config
analysis_options.yaml
dart_code_metrics:
rules:
- move-variable-closer-to-its-usage:
ignore-after-if: false
❌ Bad:
void withIf(bool condition) {
// LINT: This variable is only used after the if statement. Try moving this declaration closer to where it is used.
final value = 1;
if (condition) {
print('hi');
}
print(value);
}
✅ Good:
void withIf(bool condition) {
if (condition) {
print('hi');
}
final value = 1; // Correct, after the if statement
print(value);
}