saguado
saguado

Reputation: 27

Flutter cloned Map updating both values

I have an original map called _device, I store this Map in a variable called 'before', then I clone these last ones to a Map called 'after'. Whenever I update 'after' values, the values in 'before' and '_device' are also updated. What's wrong with my code? I have reproduced my code in dartPad and works fine. I'm under master channel 1.26.0-13.pre123.

Map<String, dynamic> before = {};
Map<String, dynamic> after = {};
...
before = _device; // _device variable contains Map<String, dynamic>
after = {...before};
...
  if (_storedValue == null) after[_field]['status'] = 'SI';
  if (_storedValue == 'SI') after[_field]['status'] = 'NO';
  if (_storedValue == 'NO') after[_field]['status'] = '(!)';
  if (_storedValue == '(!)') after[_field]['status'] = null;

Thanks for any support.

Upvotes: 1

Views: 447

Answers (2)

hasan
hasan

Reputation: 1

Try this:

Map<String, dynamic> before = {};
Map<String, dynamic> after = {};
//...
before.addAll(_device); // _device variable contains Map<String, dynamic>
after.addAll(before);

Upvotes: 0

Hamed Rezaee
Hamed Rezaee

Reputation: 7222

The issue you are facing is due to how Dart handles object assignment and copying.

In your code, when you assign before = _device, you are not creating a new copy of _device. Instead, both before and _device now reference the same underlying object in memory. So, any changes made to one of them will affect the other.

You can use Map<String, dynamic> Map.from(Map<dynamic, dynamic> other) to copy the original Map.

Map<String, dynamic> before = {};
Map<String, dynamic> after = {};

before = Map.from(_device);
after = Map.from(before);

if (_storedValue == null) after[_field]['status'] = 'SI';
if (_storedValue == 'SI') after[_field]['status'] = 'NO';
if (_storedValue == 'NO') after[_field]['status'] = '(!)';
if (_storedValue == '(!)') after[_field]['status'] = null;

Upvotes: 0

Related Questions