Rules / Style / prefer-collection-literals

prefer-collection-literals

lint/style/prefer-collection-literals
Same as prefer_collection_literals · Dart lints

Flags no-argument collection constructor calls that a literal would express.

The empty List(), Map(), Set(), LinkedHashMap(), and LinkedHashSet() constructors are more verbose than the equivalent [] or {} literals, which are the idiomatic way to build a fresh collection and read more clearly. The rule matches the unnamed and .new constructors written as a plain call (List(), Set.new()), an explicit new expression (new Map()), or with type arguments (Map<K, V>()). It deliberately spares named constructors such as List.filled or Map.of and any invocation carrying arguments, since those have no literal form.

Invalid

example.dartdart
import 'dart:collection';

void bad() {
  var a = List();
  var b = Map();
  var c = Set();
  var d = LinkedHashMap();
  var e = LinkedHashSet();
  var f = List<int>();
  var g = new Set();
  var h = new Map<String, int>();
}
Use a collection literal instead of a constructor invocation.
3void bad() {
4 var a = List();
Use a collection literal instead of a constructor invocation.
4 var a = List();
5 var b = Map();
Use a collection literal instead of a constructor invocation.
5 var b = Map();
6 var c = Set();
Use a collection literal instead of a constructor invocation.
6 var c = Set();
7 var d = LinkedHashMap();
Use a collection literal instead of a constructor invocation.
7 var d = LinkedHashMap();
8 var e = LinkedHashSet();
Use a collection literal instead of a constructor invocation.
8 var e = LinkedHashSet();
9 var f = List<int>();
Use a collection literal instead of a constructor invocation.
9 var f = List<int>();
10 var g = new Set();
Use a collection literal instead of a constructor invocation.
10 var g = new Set();
11 var h = new Map<String, int>();

Valid

example.dartdart
void good() {
  var a = [];
  var b = {};
  var c = <int>[];
  var d = <String, int>{};
  var e = List.filled(3, 0);
  var f = Map.from(<int, int>{});
  var g = Set.of([1, 2, 3]);
  var h = List.generate(3, (i) => i);
}

How to configure

Set the severity of prefer-collection-literals in your falcon.json:

falcon.jsonjson
{
  "linter": {
    "rules": {
      "style": {
        "prefer-collection-literals": "error"
      }
    }
  }
}