toList on the operand of a spread element
ID |
dart.performance.unnecessary_to_list_in_spreads |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Redundancy |
Language |
Dart |
Description
Reports a toList() call that is the whole operand of a spread element in a list or set literal, including the null-aware …? form.
Rationale
A spread element iterates whatever it is given, so it needs an Iterable and not a List. The toList() call therefore allocates a list and copies every element into it, purely so the spread can walk that copy and copy the elements a second time into the literal - twice the allocation and twice the copying for no change in the result. In Flutter this pattern usually sits on a children: list inside build, where it runs on every rebuild.
The following code illustrates the pattern detected by this rule:
class ItemList extends StatelessWidget {
final List<String> items;
const ItemList(this.items, {super.key});
@override
Widget build(BuildContext context) {
// FLAGGED: toList on the operand of a spread element
return Column(children: [
const Text('header'),
...items.map((i) => Text(i)).toList(),
]);
}
}