collection_ methods_ unrelated_ type
Learn about the collection_methods_unrelated_type linter rule.
Invocation of various collection methods with arguments of unrelated types.
Details
#DON'T invoke certain collection method with an argument with an unrelated type.
Doing this will invoke == on the collection's
elements and most likely will return false.
An argument passed to a collection method should relate to the collection type as follows:
-
an argument to
Iterable<E>.containsshould be related toE -
an argument to
List<E>.removeshould be related toE -
an argument to
Map<K, V>.containsKeyshould be related toK -
an argument to
Map<K, V>.containsValueshould be related toV -
an argument to
Map<K, V>.removeshould be related toK -
an argument to
Map<K, V>.[]should be related toK -
an argument to
Queue<E>.removeshould be related toE -
an argument to
Set<E>.lookupshould be related toE -
an argument to
Set<E>.removeshould be related toE
BAD:
void someFunction() {
var list = <int>[];
if (list.contains('1')) print('someFunction'); // LINT
}
BAD:
void someFunction() {
var set = <int>{};
set.remove('1'); // LINT
}
GOOD:
void someFunction() {
var list = <int>[];
if (list.contains(1)) print('someFunction'); // OK
}
GOOD:
void someFunction() {
var set = <int>{};
set.remove(1); // OK
}
Enable
#
To enable the
collection_methods_unrelated_type rule, add
collection_methods_unrelated_type
under
linter > rules in your
analysis_options.yaml
file:
linter:
rules:
- collection_methods_unrelated_type
If you're instead using the YAML map syntax to configure
linter rules, add
collection_methods_unrelated_type: true under
linter > rules:
linter:
rules:
collection_methods_unrelated_type: true
除非另有说明,文档之所提及适用于 Dart 3.12.2 版本报告页面问题.