dart中的Map将使用上次更新的值替换先前键的值

时间:2017-11-13 08:49:44

标签: dart

我实际上是在使用dart中的map,我无法弄清楚为什么我的示例中的map变量表现得很奇怪,或者我在代码中做错了。

请有人帮我调试代码,我已经发布了代码来重现问题。

  

example.dart

void main() {
  var data2 = {};
  var data1 = {};

  var floorDetails = new Map();
  floorDetails.clear();
  for (int i = 0; i < 2; i++) {
    data2.clear();
    data1.clear();
    for (int j = 0; j < 2; j++) {
      data1 = {
        'flat${(i + 1) * 100 + (j + 1)}': {'flattype': "flat"},
      };
      data2.addAll(data1);
    }
    print('data2=$data2');

    floorDetails['floor${(i+1)}'] = data2;

    print('floorDetails = $floorDetails');
  }

  print(floorDetails.keys);
}

代码的输出是:

floorDetails = {floor1: {flat201: {flattype: flat}, flat202: {flattype: flat}}, floor2: {flat201: {flattype: flat}, flat202: {flattype: flat}}}

实际上我期待输出为:

floorDetails = {floor1: {flat101: {flattype: flat}, flat102: {flattype: flat}}, floor2: {flat201: {flattype: flat}, flat202: {flattype: flat}}}

这实际上是根据Map.addAll()方法的文档覆盖了地图floorDetails内所有键的值

    void addAll(
Map<K, V> other
)
Adds all key-value pairs of other to this map.

If a key of other is already in this map, its value is overwritten.

The operation is equivalent to doing this[key] = value for each key and associated value in other. It iterates over other, which must therefore not change during the iteration.

虽然在给定的示例中,键是不同的,但它仍然覆盖了值。

请,任何帮助将不胜感激。 非常感谢, 鳅

1 个答案:

答案 0 :(得分:4)

在第一次迭代中,您可以在此处指定data2

floorDetails['floor${(i+1)}'] = data2;

但下一次迭代的第一行是

data2.clear();

清除data2。这也清除了floorDetails [&#39; floor1&#39;]`的内容,因为它引用了相同的地图。

您可以创建新地图,而不是通过更改

来清除它
data2.clear();
data1.clear();

data2 = {}; // or new Map()
data1 = {};

或在分配之前创建地图的副本

floorDetails['floor${(i+1)}'] = new Map.from(data2);

Map是一个对象,通过引用复制。只有booldoubleintString这样的原始类型会按值复制。