0

Dart Can't change map value from initial map

I have this code :

void main() {
  Map tabtest = {
    '1' : {
      'd' : 'one'
    }
  };

  Map tabtest1 = {};
  tabtest.forEach((cle1, val1) {
    val1['d']='two';
    tabtest1['cle1']=val1;
  });

  Map tabtest2={};
  tabtest.forEach((cle2, val2) {
    val2['d']='three';
    tabtest2['cle2']=val2;
  });

  print(tabtest);
  print(tabtest1);
  print(tabtest2);
}

This code display :

{1: {d: three}}
{1: {d: three}}
{1: {d: three}}

But I want different value from tabtest1 and tabtest2 like :

tabtest1 = {1: {d: two}}
tabtest2 = {1: {d: three}}

Can help me?

Thanks.

James Allen
  • 6,406
  • 8
  • 50
  • 83
Eugène
  • 1
  • 1
  • When you do `tabtest1[cle1] = val1;` `tabtest1` stores a *reference* to the nested `Map`, not a copy. If you want those nested `Map`s to be independent, you will need to create *copies* of those `Map`s. For example: `tabtest1[cle1]=Map.of(val1);` Same thing applies to `tabtest2`. – jamesdlin Mar 24 '22 at 15:49

1 Answers1

3

There were a couple of problems:

  • you were actually using the same sub-map {'d': 'one'} in all three versions, instead of creating three seperate maps. The easiest way to copy a Map is to use Map secondMap = Map.from(firstMap). Beware though - this will only copy the first 'level' of the map. See this question for more information

  • you were using the string 'cle1' instead of it's value, so tabtest1['cle1'] should have been tabtest1[cle1]

void main() {

  Map tabtest = {
    '1' : {
      'd' : 'one'
    }
  };

  Map tabtest1 = {};

  // For each map entry in tabtest
  tabtest.forEach((cle, val) {
    // First COPY the sub-map. If we don't make a copy, we end up
    // changing the sub-map in both tabtest and tabtest2
    Map val1 = Map.from(val);

    // Then we can update the value in our new sub-map:
    val1['d']='two';

    // And set this as the key '1' in tabtest1
    tabtest1[cle]=val1;
  });

  Map tabtest2={};
  tabtest.forEach((cle, val) {
    Map val2 = Map.from(val);
    val2['d']='three';
    tabtest2[cle]=val2;
  });

  print(tabtest);
  print(tabtest1);
  print(tabtest2);
}

{1: {d: one}}

{1: {d: two}}

{1: {d: three}}

James Allen
  • 6,406
  • 8
  • 50
  • 83