避免在可變類別上使用 equals 和 hashCode
避免在未標記 @immutable
的類別上覆寫 operator == 和 hashCode。
此規則自 Dart 2.6 起可用。
詳細資訊
#避免在未標記 @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;
}
注意:lint 會檢查 @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
除非另有說明,否則本網站上的文件反映的是 Dart 3.6.0。頁面最後更新於 2024-07-03。 檢視原始碼 或 回報問題。