The spread operators (... and ...?) are convenient
ways to flatten a collection into a collection literal, that work on multiple types of collections supporting literals: List,
Map, and Set.
When a spread operator is used in a List literal, it looks like the following:
final list = [1, 2, ...anIterable, 3, 4];
which is more concise, readable, and efficient than the equivalent code not using it:
final list = [1, 2]..addAll(anIterable)..addAll([3, 4]);
In the example above, the spread operator will iterate over the elements of anIterable, building the resulting list.
There is no need to call toList on the Iterable before spreading it into the list literal, because the spread operator
will take care of the iteration.
final list = [1, 2, ...anIterable.toList(), 3, 4]; // toList not necessary
In general, once the intent of flatting an Iterable into a collection literal has been expressed by using the ...
operator, it’s best let the compiler figure out what is the best way to achieve that, based on the type of collection literal (List,
Set, Map) and the actual type of provided Iterable.
What is the potential impact?
Calling toList unnecessarily is not only redundant and more verbose: it may result in unnecessary memory allocation and performance
overhead, since an intermediate List instance would be created, just to be thrown away once it is spread into the list literal.