Home > OS >  Dart removeWhere on second/temp variable affects origin
Dart removeWhere on second/temp variable affects origin

Time:12-03

I want to use removeWhere on the second/temp variable without affecting the origin variable.

void main() {  
  Map<String, dynamic> testMap = {
    'first': {'value': 1},
    'second': {'value': 2},
    'third': {'value': 3},
  };
  
  print(testMap);
  
  Map<String, dynamic> tempMap = testMap;
  tempMap.removeWhere((k,v) => v['value'] > 1);
  
  print(testMap);
  print(tempMap);
}

The output for print will be:

{first: {value: 1}, second: {value: 2}, third: {value: 3}}
{first: {value: 1}}
{first: {value: 1}}

Why is removeWhere affecting the origin variable? When I'm calling it on tempMap

EDIT: As responded in the comment by OMi Shah, the fastest way would be:

Map<String, dynamic> tempMap = {...testMap};

CodePudding user response:

Use Map.from

    Map<String, dynamic> testMap = {
      'first': {'value': 1},
      'second': {'value': 2},
      'third': {'value': 3},
    };
    
    Map<String, dynamic> tempMap = Map.from(testMap);
    tempMap.removeWhere((k,v) => v['value'] > 1);

    print(testMap);
    print(tempMap);

CodePudding user response:

You need to create a new map. In your specific case, we could just create a new map from the original where we at creation will filter out the key-value pairs you don't want.

So something like this:

void main() {
  Map<String, dynamic> testMap = {
    'first': {'value': 1},
    'second': {'value': 2},
    'third': {'value': 3},
  };

  print(testMap); // {first: {value: 1}, second: {value: 2}, third: {value: 3}}

  Map<String, dynamic> tempMap = {
    for (final entry in testMap.entries)
      if (entry.value['value'] <= 1) entry.key: entry.value
  };

  print(testMap); // {first: {value: 1}, second: {value: 2}, third: {value: 3}}
  print(tempMap); // {first: {value: 1}}
}
  •  Tags:  
  • dart
  • Related