Anil Mukkoti
Anil Mukkoti

Reputation: 11

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]]?

Upvotes: 0

Views: 4235

Answers (3)

Muhammad Javed
Muhammad Javed

Reputation: 119

Map countries = {

"01": "USA",

"02": "United Kingdom",

"03": "China",

"04": "India",

"05": "Brazil",

"06": "Nepal",

"07": "Russia"

};

//method 1:

var _key = countries.keys.firstWhere((k)
      => countries[k] == 'Russia', orElse: () => null);

print(key); //output: 07

Upvotes: 0

julemand101
julemand101

Reputation: 31309

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. It should be noted it does not support nested lists:

import 'dart:collection';

void main() {
  final mp = LinkedHashMap<List<int>, String>(
    equals: (list1, list2) {
      if (list1.length != list2.length) {
        return false;
      }
      
      for (var i = 0; i < list1.length; i++) {
        if (list1[i] != list2[i]) {
          return false;
        }
      }
      
      return true;
    },
    hashCode: Object.hashAll,
  );

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

I should also 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.

Upvotes: 3

Salih Can
Salih Can

Reputation: 1821

You add a list instance as a key to the Map object. You need the corresponding list instance to delete it again.

There are two ways to access

First;

  final mp = {};
  mp[[1,2]] = "Hi";
  mp[[3,5]] = "sir";
  mp.removeWhere((key, value) {
    if(key is List){
      return key.first == 3 && key[1] == 5;
    }
    return false;
  });

Second;

  final mp = {};
  final key = [3, 5];
  mp[[1,2]] = "Hi";
  mp[key] = "sir";
  mp.remove(key);

Upvotes: 0

Related Questions