Home > Software design >  Dart - Map with Set as key
Dart - Map with Set as key

Time:10-31

I'm trying to construct a Map object with Set as keys:

final myObject = <Set<MyType1>, MyType2>{};

I can successfully insert new values in my object

myObject[{myType1}] = myType2;

However, I cannot get back anything from it as 2 sets with the same values won't be consider equal:

{0} == {0}; // <- false
myObject[{myType1}]; // <- null

Is there something built-in that could allow me to use a Map<Set<T>, U> object?

CodePudding user response:

You may create your own class that wraps a Set with your own equals and hashCode. Then the problem is solved.

A very rough example to demonstrate my idea:

class MySet<T> {
  final Set<T> inner;
  ...

  @override
  bool equals(other) => setEquals(this, other); // https://api.flutter.dev/flutter/foundation/setEquals.html

  @override
  int hashCode => ...
}

P.S. The equals/hashCode of a Set is not implemented as whether the contents are the same, because that would be very costly.

  • Related