When having a List, Map method clear() clears out a Map, BUT also clears the Map out the List

Please RUN an example of the issue in dartpad:

Map<String,dynamic> map = {
'id': 0,
'name': 'Tomas',
};

List<dynamic> list = [];
List<dynamic> list2;

void main() {


  print('0. map: $map');
  print('0. list: $list');
  print('0. list2: $list2 \n');
  
  list.add(map);
  list2=list;
  print('1. map: $map');
  print('1. list: $list');
  print('1. list2: $list2 \n');
  
  list.add({'id': 1, 'name': 'Anna'});
  list2=list;
  print('2. map: $map');
  print('2. list: $list');
  print('2. list2: $list2 \n');
  
 
  
  map.clear();
  //map = {};
  print('3. map: $map');
  print('3. list: $list');
  print('3. list2: $list2 \n');
  


}

When we use Map = {} instead of Map.clear(), everything works as it should. Take a look here:

Map<String,dynamic> map = {
'id': 0,
'name': 'Tomas',
};

List<dynamic> list = [];
List<dynamic> list2;

void main() {


  print('0. map: $map');
  print('0. list: $list');
  print('0. list2: $list2 \n');
  
  list.add(map);
  list2=list;
  print('1. map: $map');
  print('1. list: $list');
  print('1. list2: $list2 \n');
  
  list.add({'id': 1, 'name': 'Anna'});
  list2=list;
  print('2. map: $map');
  print('2. list: $list');
  print('2. list2: $list2 \n');
  
 
  
  //map.clear();
  map = {};
  print('3. map: $map');
  print('3. list: $list');
  print('3. list2: $list2 \n');
  


}
  • My Dart VM version: 2.7.1 (Thu Jan 23 13:02:26 2020 +0100) on “macos_x64”

Author: Fantashit

1 thought on “When having a List, Map method clear() clears out a Map, BUT also clears the Map out the List

  1. What List<Map> actually means is that you have a list of references to Map objects. When you then add your map object to the list with list.add(map); you are inserting the reference to you map object into the list.

    So in the end, there are only one map instance in your code but you have multiple variables pointing into this same map object. Therefore, when you are calling map.clear() you are making this call on the only map instance in your code. Since your list are referring to the map you have cleared it will also be seen as empty.

    When you are using map = {} you are actually creating a new empty map object and sets the map variable to point to this new instance. Since your list are still referring to the old instance it will be seen as it keep its elements.

    If you want to put a copy of your map into the List you can use list.add(Map.from(map)); when adding the map to the list. Then it will not be affected if you later makes modifications to the Map object which the map variable are referring to.

Comments are closed.