Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using List as a key in map in Dart

Here is my Dart code

var mp = new Map();
  mp[[1,2]] = "Hi";
  mp[[3,5]] = "sir";
  mp.remove([3,5]);
  print(mp);

Output here is null

How can i access value at mp[[3,5]]?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Two list instances containing the same elements is not equal to each other in Dart. This is the reason your example does not work.

If you want to create a Map which works like your example, you can use LinkedHashMap from dart:collection (basically the same when you are using Map()) to create an instance with its own definition of what it means for keys to be equal and how hashCode is calculated for a key.

So something like this if you want to have keys to be equal if the list contains the same elements in the same order:

import 'dart:collection';
import 'package:collection/collection.dart';

void main() {
  final mp = LinkedHashMap<List<int>, String>(
    equals: const ListEquality().equals,
    hashCode: Object.hashAll,
  );

  mp[[1, 2]] = "Hi";
  mp[[3, 5]] = "sir";
  mp.remove([3, 5]);
  print(mp); // {[1, 2]: Hi}
}

I should add that this is really an inefficient way to do use maps and I am highly recommend to never use List as keys in maps.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading