collection_methods_unrelated_type
Invocation of various collection methods with arguments of unrelated types.
此规则自 Dart 2.19 版本起可用。
_规则集:core , recommended , flutter _
详情
#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:
dart
void someFunction() {
var list = <int>[];
if (list.contains('1')) print('someFunction'); // LINT
}BAD:
dart
void someFunction() {
var set = <int>{};
set.remove('1'); // LINT
}GOOD:
dart
void someFunction() {
var list = <int>[];
if (list.contains(1)) print('someFunction'); // OK
}GOOD:
dart
void someFunction() {
var set = <int>{};
set.remove(1); // OK
}使用方法
#要启用 collection_methods_unrelated_type 规则,请在你的 analysis_options.yaml 文件中,在 linter > rules 下添加 collection_methods_unrelated_type :
analysis_options.yaml
yaml
linter:
rules:
- collection_methods_unrelated_type除非另有说明,否则本网站上的文档反映的是 Dart 3.6.0。页面最后更新于 2025-02-05。 查看源代码 或 报告问题.