collection_methods_unrelated_type
使用不相关类型的参数调用各种集合方法。
详情
#不要使用不相关类型的参数调用某些集合方法。
这样做将会在集合的元素上调用 ==
,并且很可能会返回 false
。
传递给集合方法的参数应按如下方式与集合类型相关:
Iterable<E>.contains
的参数应与E
相关List<E>.remove
的参数应与E
相关Map<K, V>.containsKey
的参数应与K
相关Map<K, V>.containsValue
的参数应与V
相关Map<K, V>.remove
的参数应与K
相关Map<K, V>.[]
的参数应与K
相关Queue<E>.remove
的参数应与E
相关Set<E>.lookup
的参数应与E
相关Set<E>.remove
的参数应与E
相关
错误
dart
void someFunction() {
var list = <int>[];
if (list.contains('1')) print('someFunction'); // LINT
}
错误
dart
void someFunction() {
var set = <int>{};
set.remove('1'); // LINT
}
正确
dart
void someFunction() {
var list = <int>[];
if (list.contains(1)) print('someFunction'); // OK
}
正确
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
如果您改为使用 YAML 映射语法来配置 linter 规则,请在 linter > rules 下添加 collection_methods_unrelated_type: true
analysis_options.yaml
yaml
linter:
rules:
collection_methods_unrelated_type: true
除非另有说明,否则本网站上的文档反映了 Dart 3.7.1 版本。页面最后更新于 2025-03-07。 查看源代码 或 报告问题。