Rules / Style / prefer-spread-collections

prefer-spread-collections

lint/style/prefer-spread-collections
recommended
Same as prefer_spread_collections · Dart lints

Flags an addAll cascade on a collection literal that a spread would express.

The spread operator ([a, b, ...x]) folds another collection's elements into a literal in one expression, so [a, b]..addAll(x) is unnecessarily verbose and reads as a construction followed by mutation rather than a single collection. The rule matches each ..addAll(...) section cascaded onto a list, set, or map literal that takes exactly one positional argument and no named arguments; other shapes and non-literal receivers are ignored.

Invalid

example.dartdart
void bad() {
  var a = [1, 2]..addAll([3, 4]);
  var b = <int>[]..addAll([5]);
  var c = {1, 2}..addAll({3});
  var d = <String>{}..addAll({'a'});
  var e = []..addAll([1])..addAll([2]);
}
Use the spread operator '...' instead of 'addAll'.
1void bad() {
2 var a = [1, 2]..addAll([3, 4]);
Use the spread operator '...' instead of 'addAll'.
2 var a = [1, 2]..addAll([3, 4]);
3 var b = <int>[]..addAll([5]);
Use the spread operator '...' instead of 'addAll'.
3 var b = <int>[]..addAll([5]);
4 var c = {1, 2}..addAll({3});
Use the spread operator '...' instead of 'addAll'.
4 var c = {1, 2}..addAll({3});
5 var d = <String>{}..addAll({'a'});
Use the spread operator '...' instead of 'addAll'.
5 var d = <String>{}..addAll({'a'});
6 var e = []..addAll([1])..addAll([2]);
Use the spread operator '...' instead of 'addAll'.
5 var d = <String>{}..addAll({'a'});
6 var e = []..addAll([1])..addAll([2]);

Valid

example.dartdart
void good() {
  final other = [3, 4];
  final first = [1];
  final second = [2];
  final someList = <int>[];
  var a = [1, 2, ...other];
  var b = <int>[...first, ...second];
  someList.addAll([3, 4]);
  var c = someList..sort();
  var d = someList..addAll([1]);
}

How to configure

Set the severity of prefer-spread-collections in your falcon.json:

falcon.jsonjson
{
  "linter": {
    "rules": {
      "style": {
        "prefer-spread-collections": "error"
      }
    }
  }
}