目錄

collection_methods_unrelated_type

使用不相關型別的引數調用各種集合方法。

此規則自 Dart 2.19 起提供。

規則集:核心建議flutter

詳細資訊

#

不要使用不相關型別的引數調用某些集合方法。

這樣做會在集合的元素上調用 ==,並且很可能會傳回 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