Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new pair to Map in Dart?

I caught the following errors when adding a new pair to a Map.

  • Variables must be declared using the keywords const, final, var, or a type name
  • Expected to find;
  • the name someMap is already defined

I executed the following code.

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

How should I add a new pair to the Map?

I'd also like to know how to use Map.update.

like image 828
hrsma2i Avatar asked Dec 24 '18 01:12

hrsma2i


People also ask

How do I add items to my Dart map?

Add item to a Map in Dart/Flutter There are 2 way to add an item (key-value pair) to a Map: using square brackets [] calling putIfAbsent() method.


2 Answers

To declare your map in Flutter you probably want final:

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

Then, your update should work:

someMap["c"] = 3; 

Finally, the update function has two parameters you need to pass, the first is the key, and the second is a function that itself is given one parameter (the existing value). Example:

someMap.update("a", (value) => value + 100); 

If you print the map after all of this you would get:

{a: 101, b: 2, c: 3} 
like image 144
Tyler Avatar answered Sep 18 '22 20:09

Tyler


You can add a new pair to a Map in Dart by specifying a new key like this:

Map<String, int> map = {   'a': 1,   'b': 2, };  map['c'] = 3;  // {a: 1, b: 2, c: 3} 

According to the comments, the reason it didn't work for the OP was that this needs to be done inside a method, not at the top level.

like image 30
Suragch Avatar answered Sep 20 '22 20:09

Suragch