For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/dart-code-quality/hash-and-equals.md. A documentation index is available at /llms.txt.

Override hashCode when overriding ==

This product is not supported for your selected Datadog site. ().

Metadata

ID: dart-code-quality/hash-and-equals

Language: Dart

Severity: Warning

Category: Code Style

Description

In Dart, == and hashCode work as a pair. If two objects are equal, they must produce the same hash code. Overriding only one of them breaks Map, Set, and other collections that rely on hashing.

When you override operator ==, also override hashCode using the same fields that determine equality. If you override hashCode, make sure == is overridden too.

Non-Compliant Code Examples

class OnlyEquals {
  final int value;

  OnlyEquals(this.value);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is OnlyEquals && value == other.value;
}

class OnlyHashCode {
  final String id;

  OnlyHashCode(this.id);

  @override
  int get hashCode => id.hashCode;
}

Compliant Code Examples

class Person {
  final String name;

  Person(this.name);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Person && name == other.name;

  @override
  int get hashCode => name.hashCode;
}

class Pair {
  final int a;
  final int b;

  Pair(this.a, this.b);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Pair && a == other.a && b == other.b;

  @override
  int hashCode => Object.hash(a, b);
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security