如何添加一个新的对地图在省?

在向 Map 添加新对时,我发现了以下错误。

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

我执行了以下代码。

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


someMap["c"] = 3;

我应该如何向 Map 添加一个新对?

我还想知道如何使用 Map.update

177302 次浏览

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}

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.

Another way to add new key/value as map to existing map is this,

oldMap.addEntries(myMap.entries);

This will update the oldMap with key/value of myMap;

Map<String, dynamic> someMap = {
'id' : 10,
'name' : 'Test Name'
};
someMethod(){
someMap.addAll({
'email' : 'test@gmail.com'
});
}
printMap(){
print(someMap);
}

make sure you can't add entries right below the declaration.

I write this utility:

Map updateMap({
/// Update a map with another map
/// Example:
///   Map map1 = {'name': 'Omid', }
///   Map map2 = {'family': 'Raha', }
///   Map map = updateMap(data:map1, update:map2);
/// Result:
///   map = {'name': 'Omid', 'family': 'Raha',}
@required Map data,
@required Map update,
}) {
if (update == null) return data;
update.forEach((key, value) {
data[key] = value;
});
return data;
}

Example:

Map map1 = {'name': 'Omid', }
Map map2 = {'family': 'Raha', }


Map map = updateMap(data:map1, update:map2);


print(map);


{'name': 'Omid', 'family': 'Raha',}

This way is also applicable:

Map<String, int> someMap = {
"a": 1,
"b": 2,
};
someMap.addEntries({"c":3}.entries);