prefer_collection_literals
Use collection literals when possible.
Details
#DO use collection literals when possible.
BAD:
dart
var addresses = Map<String, String>();
var uniqueNames = Set<String>();
var ids = LinkedHashSet<int>();
var coordinates = LinkedHashMap<int, int>();
GOOD:
dart
var addresses = <String, String>{};
var uniqueNames = <String>{};
var ids = <int>{};
var coordinates = <int, int>{};
EXCEPTIONS:
When a LinkedHashSet
or LinkedHashMap
is expected, a collection literal is not preferred (or allowed).
dart
void main() {
LinkedHashSet<int> linkedHashSet = LinkedHashSet.from([1, 2, 3]); // OK
LinkedHashMap linkedHashMap = LinkedHashMap(); // OK
printSet(LinkedHashSet<int>()); // LINT
printHashSet(LinkedHashSet<int>()); // OK
printMap(LinkedHashMap<int, int>()); // LINT
printHashMap(LinkedHashMap<int, int>()); // OK
}
void printSet(Set<int> ids) => print('$ids!');
void printHashSet(LinkedHashSet<int> ids) => printSet(ids);
void printMap(Map map) => print('$map!');
void printHashMap(LinkedHashMap map) => printMap(map);
Enable
#To enable the prefer_collection_literals
rule, add prefer_collection_literals
under linter > rules in your analysis_options.yaml
file:
analysis_options.yaml
yaml
linter:
rules:
- prefer_collection_literals
If you're instead using the YAML map syntax to configure linter rules, add prefer_collection_literals: true
under linter > rules:
analysis_options.yaml
yaml
linter:
rules:
prefer_collection_literals: true
Was this page's content helpful?
Thank you for your feedback!
Provide details Thank you for your feedback! Please let us know what we can do to improve.
Provide details Unless stated otherwise, the documentation on this site reflects Dart 3.8.1. Page last updated on 2025-03-07. View source or report an issue.