跳到主要內容

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。 檢視原始碼 回報問題