I want to create a Map<ActivityProject, int> in Flutter and have activityProject uniquely stored inside the map. Below you can see a snipped code.
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}");
});
}
ActivityProject class is defined as follows
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);
}
I have override both "==" and hashCode, but even if the hashcode is the same, the values are put inside the map.
Output:
Hashcode: 176486800
Key: activity-project, Value: 1
Hashcode: 176486800
Key: activity-project, Value: 2
Hashcode: 176486800
Key: activity-project, Value: 3
Any suggestion would be highly appreciated.