Use lists as keys on a map

print({[1,2]:3}[[1,2]])prints null. This is obviously unexpected.

Is there a blessed workaround or do I need to create a new list-like-class / wrapper and give it the correct ones operator==and hashCode?

+4
source share
2 answers

Lists in Dart are not equal based on their elements.

You can use Mapwith custom equality function. There package:collection/equality.dartis equality in the lists defined in , so you can do:

import "package:collection/equality.dart";
main() {
  const eq = const ListEquality();
  var map = new Map(equals: eq.equals, hashCode: eq.hash, isValidKey: eq.isValidKey);
  map[[1,2]] = 42;
  print(map[[1,2]]);
}

This will still not allow you to use a map literal.

+5
source

There is an open problem for this: http://dartbug.com/17963 and possibly http://dartbug.com/2217

Hashmap , hashCode:

HashMap({
    Function bool equals(K key1, K key2), 
    Function int hashCode(K key), 
    Function bool isValidKey(potentialKey)})

, -, , , , , ( )

+1

All Articles