如何正确覆盖 class 以便在 Flutter [Dart] 中将其唯一添加到地图中
How to properly override a class so that is uniquely added to a Map in Flutter [Dart]
我想在 Flutter 中创建一个 Map 并将 activityProject 唯一地存储在地图中。您可以在下方看到截取的代码。
void main() {
Map<ActivityProject, int> timesheet = Map.identity();
timesheet.putIfAbsent(ActivityProject('activity', 'project'), () => 1);
timesheet.putIfAbsent(ActivityProject('activity', 'project'), () => 2);
timesheet.putIfAbsent(ActivityProject('activity', 'project'), () => 3);
timesheet.entries.forEach((element) {
print("Hashcode: ${element.key.hashCode}" );
print(
"Key: ${element.key.activity}-${element.key.project}, Value: ${element.value}");
});
}
ActivityProjectclass定义如下
class ActivityProject {
String activity;
String project;
ActivityProject(this.activity, this.project);
@override
bool operator ==(Object other) =>
other is ActivityProject &&
other.activity == activity &&
other.project == project;
@override
int get hashCode => hashValues(activity, project);
}
我已经覆盖了“==”和hashCode,但即使哈希码相同,值也会放在里面地图。
输出:
Hashcode: 176486800
Key: activity-project, Value: 1
Hashcode: 176486800
Key: activity-project, Value: 2
Hashcode: 176486800
Key: activity-project, Value: 3
如有任何建议,我们将不胜感激。
这里的问题是您正在使用 Map.identity()
。在 Map<K, V>.identity constructor.
上阅读此处的文档
An identity map uses identical for equality and identityHashCode for hash codes of keys instead of the intrinsic Object.== and Object.hashCode of the keys.
根据文档,使用 Map.identity
构建的地图不使用 ==
和 hashCode
。
您应该这样定义您的地图:
Map<ActivityProject, int> timesheet = {};
我想在 Flutter 中创建一个 Map
void main() {
Map<ActivityProject, int> timesheet = Map.identity();
timesheet.putIfAbsent(ActivityProject('activity', 'project'), () => 1);
timesheet.putIfAbsent(ActivityProject('activity', 'project'), () => 2);
timesheet.putIfAbsent(ActivityProject('activity', 'project'), () => 3);
timesheet.entries.forEach((element) {
print("Hashcode: ${element.key.hashCode}" );
print(
"Key: ${element.key.activity}-${element.key.project}, Value: ${element.value}");
});
}
ActivityProjectclass定义如下
class ActivityProject {
String activity;
String project;
ActivityProject(this.activity, this.project);
@override
bool operator ==(Object other) =>
other is ActivityProject &&
other.activity == activity &&
other.project == project;
@override
int get hashCode => hashValues(activity, project);
}
我已经覆盖了“==”和hashCode,但即使哈希码相同,值也会放在里面地图。
输出:
Hashcode: 176486800
Key: activity-project, Value: 1
Hashcode: 176486800
Key: activity-project, Value: 2
Hashcode: 176486800
Key: activity-project, Value: 3
如有任何建议,我们将不胜感激。
这里的问题是您正在使用 Map.identity()
。在 Map<K, V>.identity constructor.
An identity map uses identical for equality and identityHashCode for hash codes of keys instead of the intrinsic Object.== and Object.hashCode of the keys.
根据文档,使用 Map.identity
构建的地图不使用 ==
和 hashCode
。
您应该这样定义您的地图:
Map<ActivityProject, int> timesheet = {};