Reputation: 59
I have a map:
{0: {0:"a",1:"b"}}
Now, on click of button in flutter I want to copy the map to a new key. So it should be
{0: {0:"a",1:"b"},1: {0:"a",1:"b"}}
Now, if I add a new value to key 1, it gets reflected to key 0 also.
So instead of
{0: {0:"a",1:"b"},1: {0:"a",1:"b",2:"c"}}
it becomes
{0: {0:"a",1:"b",2:"c"},1: {0:"a",1:"b",2:"c"}}
Map<int,dynamic> tempMap=new HashMap();
tempMap={...pageMap};
var tempValue=pageMap[pageIndex];
tempMap[(pageIndex+1)]= tempValue;
pageMap.clear();
for (var key in tempMap.keys) {
pageMap.putIfAbsent(key, () => tempMap[key]);
}
Does the map copies by reference in flutter/dart?
Upvotes: 3
Views: 2598
Reputation: 6239
This problem can be resolved with this code:
void main(List<String> args) {
Map getClone(Map data) {
return data.map((k, v) => MapEntry(k, v is Map ? getClone(v) : v));
}
var map1 = {0: {0:'a',1:'b'}};
var map2 = <int, dynamic>{};
map2[0] = getClone(map1);
map2[1] = getClone(map1);
print(map2);
map2[0][0][2] = 'c';
print(map2);
}
Result:
{0: {0: {0: a, 1: b}}, 1: {0: {0: a, 1: b}}}
{0: {0: {0: a, 1: b, 2: c}}, 1: {0: {0: a, 1: b}}}
Upvotes: 1
Reputation: 2717
In Dart, maps update by reference, not by value. But you can create a new copy of your first map and assign the copy to a second map. That way you can modify the second without modifying the first.
final firstMap = {1: 'test'};
var secondMap = new Map<int,dynamic>.from(firstMap);
// You can modify secondMap now without firstMap changing
Have you tried updating directly the first map? It might be a simpler approach
pageMap.putIfAbsent(pageIndex + 1, () => pageMap[pageIndex]);
Upvotes: 0
Reputation: 44066
In general, var x = y
makes both x and y refer to the same object. If you now send methods to x, it will also affect y, because they aren't two different objects. So adding a value to a map referenced by y will also make that same element be visible via x.
Upvotes: 1