hash_and_equals
如果覆蓋了 ==,則始終覆蓋 hashCode。
詳情
#務必 在覆蓋 == 時覆蓋 hashCode,並在覆蓋 hashCode 時優先覆蓋 ==。
Dart 中的每個物件都有一個 hashCode。為了使常見的雜湊表實現正常工作,物件的 == 運算子和 hashCode 屬性必須保持一致。因此,在覆蓋 == 時,也應覆蓋 hashCode 以保持一致。同樣,如果覆蓋了 hashCode,也應覆蓋 ==。
錯誤示例
dart
class Bad {
final int value;
Bad(this.value);
@override
bool operator ==(Object other) => other is Bad && other.value == value;
}正確示例
dart
class Better {
final int value;
Better(this.value);
@override
bool operator ==(Object other) =>
other is Better &&
other.runtimeType == runtimeType &&
other.value == value;
@override
int get hashCode => value.hashCode;
}啟用
#要啟用 hash_and_equals 規則,請在您的 analysis_options.yaml 檔案中將 hash_and_equals 新增到 linter > rules 下方。
analysis_options.yaml
yaml
linter:
rules:
- hash_and_equals如果您改用 YAML map 語法配置 linter 規則,請在 linter > rules 下新增 hash_and_equals: true。
analysis_options.yaml
yaml
linter:
rules:
hash_and_equals: true