Skip to main content

prefer-moving-to-variable

added in: 1.6.0
⚙️🛠

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, like:

final name = getUser().name;
final age = getUser().age;

the rule will suggest to move getUser() call to a single variable.

Additionally, this rule highlights expressions that can be replaced with an existing variable.

info

Quick fix for this rule works only for replacing expressions with existing variables.

⚙️ Config

Set allowed-duplicated-chains (default is none) to configure a threshold after which the rule should trigger on duplicated lines.

dart_code_metrics:
...
rules:
...
- prefer-moving-to-variable:
allowed-duplicated-chains: 3

Example

❌ Bad:

return Container(
color: Theme.of(context).colorScheme.secondary, // LINT
child: Text(
'Text with a background color',
style: Theme.of(context).textTheme.headline6, // LINT
),
);

✅ Good:

final theme = Theme.of(context);

return Container(
color: theme.colorScheme.secondary,
child: Text(
'Text with a background color',
style: theme.textTheme.headline6,
),
);