prefer-moving-to-variable
added in: 1.0.0 warning
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.
Config
Set allowed-duplicated-chains
(default is none
) to configure a threshold after which the rule should trigger on duplicated lines.
dart_code_linter:
...
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,
),
);