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?