use_existing_variable
v0.4.0 Warning Fix Pattern Matching
When an expression duplicates the initializer of an existing final or const variable in the same scope, you should reference the variable instead. Repeating the expression creates a maintenance risk where only one copy gets updated during refactoring.
Why use this rule
Section titled “Why use this rule”Duplicated expressions are easy to introduce and hard to spot during code review. If the expression changes, you need to update every occurrence. Using the existing variable avoids this inconsistency and makes refactoring safer.
See also: Dart patterns
// Repeating an expression that is already stored in a variablevoid badPropertyAccess(String value) { final isOdd = value.length.isOdd; print(value.length.isOdd);}
// Repeating a method callvoid badMethodCall(List<int> list) { final copy = list.toList(); print(list.toList());}
// Duplicate in a second variable initializervoid badSecondVariable(String value) { final a = value.length.isOdd; final b = value.length.isOdd; print(b);}// Using the existing variablevoid goodReuse(String value) { final isOdd = value.length.isOdd; print(isOdd);}
// No variable exists for the expression (no lint)void goodNoVariable(String value) { print(value.length.isOdd); print(value.length.isOdd);}
// Different expression (isEven vs isOdd) — no lintvoid goodDifferentExpression(String value) { final isOdd = value.length.isOdd; print(value.length.isEven);}
// Non-final variable — value may have changedvoid goodNonFinal(String value) { var isOdd = value.length.isOdd; print(value.length.isOdd); isOdd = false;}
// Expression appears before the variable declarationvoid goodBeforeDeclaration(String value) { print(value.length.isOdd); final isOdd = value.length.isOdd; print(isOdd);}
// Inside a nested function (different execution context)void goodNestedFunction(String value) { final isOdd = value.length.isOdd; void inner() { print(value.length.isOdd); } inner();}
// Trivial expressions (literals, identifiers) are not flaggedvoid goodTrivial() { final x = 42; print(42);}Configuration
Section titled “Configuration”To disable this rule:
plugins: many_lints: diagnostics: use_existing_variable: false