Skip to main content

prefer_spread_collections

Details about the 'prefer_spread_collections' diagnostic produced by the Dart analyzer.

The addition of multiple elements could be inlined.

Description

#

The analyzer produces this diagnostic when addAll is used to add the items of another collection to a list created by a list literal, in a situation where a spread element could be used instead.

Examples

#

The following code produces this diagnostic because the items of the numbers list are added to a new list using addAll:

dart
List<int> f(List<int> numbers) {
  return [0, 1]..addAll(numbers);
}

The following code produces this diagnostic because the items of the nullable numbers list are added to a new list using addAll:

dart
List<int> f(List<int>? numbers) {
  return [0, 1]..addAll(numbers ?? const []);
}

Common fixes

#

If the collection being added isn't nullable, then use a spread element (...) to include its items in the new list:

dart
List<int> f(List<int> numbers) {
  return [0, 1, ...numbers];
}

If the collection being added is nullable, then use a null-aware spread element (...?) to conditionally include its items in the new list if it's not null:

dart
List<int> f(List<int>? numbers) {
  return [0, 1, ...?numbers];
}