Empty collection built by constructor instead of a literal

ID

dart.performance.prefer_collection_literals

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Idiom

Language

Dart

Description

Reports an argument-less Map, Set, List, LinkedHashMap or LinkedHashSet constructor call, with or without type arguments, where an empty collection literal says the same thing. Constructors that take arguments - Map.from, Set.of, List.filled, LinkedHashMap(equals: …​) - are not reported, since no literal replaces them.

Rationale

A literal is the only form that can be const, so an argument-less constructor call forces a fresh allocation on every evaluation even for a collection that never changes - inside a build method or a hot loop that is a repeated allocation for a value that could have been created once at compile time. The literal is also the form the type inference and the collection-element syntax are built around: spreads, collection if and collection for can only be added to a literal, so code that starts from a constructor call has to be rewritten before any of them can be used. Map() and Set() additionally hide which implementation is produced, while {} and <T>{} are defined to give insertion-ordered ones.

The following code illustrates the pattern detected by this rule:

class Registry {
  void build() {
    // FLAGGED: Empty collection built by constructor instead of a literal
    final addresses = Map();
    // FLAGGED: Empty collection built by constructor instead of a literal
    final names = Set();
    // FLAGGED: Empty collection built by constructor instead of a literal
    final counters = Map<String, int>();
    // FLAGGED: Empty collection built by constructor instead of a literal
    final tags = Set<String>();
    // FLAGGED: Empty collection built by constructor instead of a literal
    final ordered = LinkedHashMap<String, int>();
    // FLAGGED: Empty collection built by constructor instead of a literal
    final seen = LinkedHashSet();
    print([addresses, names, counters, tags, ordered, seen]);
  }
}

Remediation

Use the literal - <String, int>{} for a map, <String>{} for a set, <String>[] for a list - and drop the type arguments where the target type already supplies them. Add const where the collection is never mutated.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved