1

I have a class:

class MyClass {
  MyClass(this.id, this.name);

  final int id;
  final String name;
}

The class is then added to a Map with some extra information:

Map<MyClass, String> myMap = { 
   MyClass(0, "Hello")  : "First", 
   MyClass(1, "World!") : "Second" 
};

I then have some callback function:

function doMagic(MyClass thisOne) {
  String? value = myMap[thisOne];
}

Now that should work fine, if you are using the same Object... But actually the thisOne is being recreated from a database and is therefore not the same Object as the one in myMap so there is no match.

The only way I can think of to do this is:

function doMagic(MyClass thisOne) {
  List<MyClass> matchItem = myMap.keys.where((my) => my.id == thisOne.id).toList();
  String? value;

  if(matchItem.isNotEmpty) {
    value = myMap[matchItem[0]];
  }
}

I'm sure I've read somewhere about the issue with checking Maps for Objects because of this issue (it is looking for the instance which is equal rather than the contents). Is there an easier way?

1 Answers1

1

Thanks goes to @Richard Heap...

The answer is to provide both an == operator override and a hashCode override, which then allows the Map [] operator to use one of those to do the value equality comparison.

class MyClass {
  MyClass(this.id, this.name);

  final int id;
  final String name;

  bool operator==(Object other) =>
      other is MyClass && id == other.id && name == other.name;

  int get hashCode => Object.hash(id, name);
}

Now, this works correctly:

function doMagic(MyClass thisOne) {
  String? value = myMap[thisOne];
}