dart map -不打印添加到其中的所有键值Paris



我在一个类中声明了如下的map

var testMap = new Map();

在initState方法上,我正在向它写入一对键值对

void initState() {
super.initState();
testMap['dn'] = 'test name1';
testMap['ph'] = '4160000000';
testMap['dn'] = 'test name2';
testMap['ph'] = '7780000000';
}

但是当我像下面这样打印testMap的值时,我得到的只是

print(testMap);
Result - {dn: test name2, ph: 7780000000}

第一个键值对去了哪里?

映射是键值对。

键必须唯一

如果您使用相同的键,您将覆盖旧值。如果您在前两行之后打印映射,它将打印这些值。

testMap['dn'] = 'test name1';
testMap['ph'] = '4160000000';
print(testMap); // prints test name1 & 4160000000

然后覆盖这些值,以便在打印映射时得到新值。

你可以尝试创建一个包含映射的List:

List<Map<String, String>> list = [];

然后添加映射:

Map<String, String> testMap = new Map();
testMap['dn'] = 'test name1';
testMap['ph'] = '4160000000';
list.add(testMap);
print(list);

映射的键必须唯一,值可以相同。所以你重复了两次。这将用新值替换旧值。像这样修改代码

void initState() {
super.initState();
testMap['dn'] = 'test name1';
testMap['ph'] = '4160000000';
testMap['dn1'] = 'test name2';
testMap['ph1'] = '7780000000';

}

最新更新