有两种方法可以将项目(键值对)添加到 Map:
1.使用方括号[]
2.调用putIfAbsent()
方法
Map map = {1: 'one', 2: 'two'};
map[3] = 'three';
print(map);
var threeValue = map.putIfAbsent(3, () => 'THREE');
print(map);
print(threeValue); // the value associated to key, if there is one
map.putIfAbsent(4, () => 'four');
print(map)
; 输出:
{1: one, 2: two, 3: three}
{1: one, 2: two, 3: three}
three
{1: one, 2: two, 3: three, 4: four}
您可以使用该方法将另一个 Map 的所有键/值对添加到当前 Map addAll()
。
Map map = {1: 'one', 2: 'two'};
map.addAll({3: 'three', 4: 'four', 5: 'five'});
print(map);
输出:
{1: one, 2: two, 3: three, 4: four, 5: five}