メインコンテンツにスキップ

avoid_equals_and_hash_code_on_mutable_classes

安定版

@immutableとマークされていないクラスでのoperator ==およびhashCodeのオーバーライドを避けてください。

詳細

#

出典: Effective Dart

避けるべきこと: @immutableとマークされていないクラスでのoperator ==およびhashCodeのオーバーライド。

クラスがイミュータブルでない場合、operator ==hashCodeをオーバーライドすると、コレクションで使用されたときに予期しない望ましくない動作につながる可能性があります。

悪い例

dart
class B {
  String key;
  const B(this.key);
  @override
  operator ==(other) => other is B && other.key == key;
  @override
  int get hashCode => key.hashCode;
}

良い例

dart
@immutable
class A {
  final String key;
  const A(this.key);
  @override
  operator ==(other) => other is A && other.key == key;
  @override
  int get hashCode => key.hashCode;
}

注意: このリンターは@immutableアノテーションの使用をチェックし、クラスがそれ以外でミュータブルでない場合でもトリガーされます。したがって、

悪い例

dart
class C {
  final String key;
  const C(this.key);
  @override
  operator ==(other) => other is C && other.key == key;
  @override
  int get hashCode => key.hashCode;
}

有効にする

#

avoid_equals_and_hash_code_on_mutable_classesルールを有効にするには、analysis_options.yamlファイルのlinter > rulesの下にavoid_equals_and_hash_code_on_mutable_classesを追加してください。

analysis_options.yaml
yaml
linter:
  rules:
    - avoid_equals_and_hash_code_on_mutable_classes

代わりにYAMLマップ構文を使用してリンタールールを構成している場合は、linter > rulesの下にavoid_equals_and_hash_code_on_mutable_classes: trueを追加してください。

analysis_options.yaml
yaml
linter:
  rules:
    avoid_equals_and_hash_code_on_mutable_classes: true