prefer-moving-to-variable
Warns when a property access or a method invocation start with duplicated chains of other invocations / accesses inside a single function or method block.
For instance, you have a function getUser()
that returns a class instance with two fields: name
and age
. If you call this function twice inside another function body:
final name = getUser().name;
final age = getUser().age;
the rule will suggest to move getUser()
call to a single variable.
⚙️ Config
Set allowed-duplicated-chains
(default is none) to configure a threshold after which the rule should trigger on duplicated lines (example).
Set ignored-invocations
(default is empty) to configure a list of methods that should be excluded (example).
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-moving-to-variable:
allowed-duplicated-chains: 3
ignored-invocations:
- indexOf
- someMethod
Example
❌ Bad:
return Container(
color: Theme.of(context).colorScheme.secondary, // LINT: Prefer moving repeated invocations to a variable and use it instead.
child: Text(
'Text with a background color',
style: Theme.of(context).textTheme.headline6, // LINT: Prefer moving repeated invocations to a variable and use it instead.
),
);
✅ Good:
final theme = Theme.of(context);
return Container(
color: theme.colorScheme.secondary, // Correct, replaced by a variable
child: Text(
'Text with a background color',
style: theme.textTheme.headline6,
),
);
Example with "allowed-duplicated-chains"
Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-moving-to-variable:
allowed-duplicated-chains: 3
✅ Good:
return Container(
color: Theme.of(context).colorScheme.secondary, // Correct, repeated only 2 times
child: Text(
'Text with a background color',
style: Theme.of(context).textTheme.headline6,
),
);
Example with "ignored-invocations"
Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-moving-to-variable:
ignored-invocations:
- of
✅ Good:
return Container(
color: Theme.of(context).colorScheme.secondary, // Correct, 'of' is ignored
child: Text(
'Text with a background color',
style: Theme.of(context).textTheme.headline6, // Correct, 'of' is ignored
),
);