跳到主要内容

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