print({[1,2]:3}[[1,2]])
prints null
. This is obviously unexpected.
Is there a blessed workaround or do I have to create a new list-like-class/wrapper and give it a proper operator==
and hashCode
?
Lists in Dart do not have equality based on their elements.
You can use a Map
with a custom equality function.
There is an equality on lists defined in package:collection/equality.dart
, so you can do:
import "dart:collection";
import "package:collection/equality.dart";
main() {
const eq = const ListEquality();
var map = HashMap(equals: eq.equals, hashCode: eq.hash, isValidKey: eq.isValidKey);
map[[1,2]] = 42;
print(map[[1,2]]);
}
That still won't allow you to use a map literal, though.
There is an open issue for this: http://dartbug.com/17963 and maybe http://dartbug.com/2217
Hashmap has a constructor that accepts functions to calculate equality and the hashCode:
HashMap({
Function bool equals(K key1, K key2),
Function int hashCode(K key),
Function bool isValidKey(potentialKey)})
You should be aware that when you calculate the hashCode dependent on the elements contained in the list and you modify the list while it is contained in the map you won't find it anymore (like in your example)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With