-1

this is my first post to StackOverflow. I have been struggling with the Map data. It’s been taking too much time to find a way more than I thought...

Ex)

Map<String, int> someMap = {
  "a": 1,
  "b": 2,
  "c": 3,
};

How can I add a new value to the same key Map? like this.

a:1, b:2, c:3,4,5,6etc....

I'd be grateful if you could tell me the correct way. Thank you.

user51375
  • 1
  • 2
  • Does this answer your question? [How to add a new pair to Map in Dart?](https://stackoverflow.com/questions/53908405/how-to-add-a-new-pair-to-map-in-dart) – Ivo May 04 '22 at 12:33
  • Hi there, do you mean adding new key value pair in map or adding new multiples to existing key in map? – Anurag Parmar May 04 '22 at 12:34

1 Answers1

1

If you want multiple values for the same key, you'll need to change the value type: Right now it's int, but that can only be a single int, and by definition, a key only occurs once in a map.

If you change the type of the value to List<int>, you can add multiple values for the same key:

Map<String, List<int>> someMap = {
  "a": [1],
  "b": [2,3],
  "c": [4],
};

Now, to add more values, you could simply access the list and add values to it:

someMap["c"].add(5);  // c: [4, 5]
someMap["c"].addAll([6,7,8]);  // c: [4, 5, 6, 7, 8]
fravolt
  • 2,565
  • 1
  • 4
  • 19
  • Note that you _could_ also use a value type `dynamic`, but I wouldn't recommend it, as you won't be able to know whether there is an int or a list of ints in there, without checking first. – fravolt May 04 '22 at 12:42