Home > OS >  How to properly override a class so that is uniquely added to a Map in Flutter [Dart]
How to properly override a class so that is uniquely added to a Map in Flutter [Dart]

Time:12-03

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.

CodePudding user response:

The problem here is that you are using Map.identity(). Read the documentation here on 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.

According to the docs, a map constructed with Map.identity does not use == and hashCode.

You should define your map like this instead:

Map<ActivityProject, int> timesheet = {};
  • Related