final Map<String, List<List<dynamic>>> originalData = {
"Chicago": [
[
8512,
7,
3620.15,
],
[
8421,
7,
5625,
],
],
"California": [
[
8512,
21,
11407.630000000001,
],
[
8708,
12,
5537.84,
],
]
};
Map<String, List<List<dynamic>>> myNewMap = Map.from(originalData);
myNewMap.forEach((st, data) {
data.forEach((List<dynamic> row) {
row.insert(0, st);
});
});
I tried Map.from(), ...OriginalData, and many more methods but it still change the OriginalData.
Expected Result should be:
myNewMap = {Chicago: [[Chicago, 8512, 7, 3620.15], [Chicago, 8421, 7, 5625]], California: [[California, 8512, 21, 11407.630000000001], [California, 8708, 12, 5537.84]]}
originalData = {Chicago: [[8512, 7, 3620.15], [8421, 7, 5625]], California: [[8512, 21, 11407.630000000001], [8708, 12, 5537.84]]}
Flutter uses shallow copy, but I also tried known methods of deep copy but nothing works.
Please help me to get over this.
I referred to this site. According to this site, the problem in your code is that in the multi-dimensional map the method used by you doesn't work it only works in one dimensional maps.
Full Code
import 'dart:convert';
void main() {
final Map originalData = {
"Chicago": [
[
8512,
7,
3620.15,
],
[
8421,
7,
5625,
],
],
"California": [
[
8512,
21,
11407.630000000001,
],
[
8708,
12,
5537.84,
],
]
};
Map myNewMap = json.decode(json.encode(originalData));
myNewMap.forEach((st, data) {
data.forEach((row) {
row.insert(0, st);
});
});
print("New Map: $myNewMap");
print("Original Map: $originalData");
}
Output
New Map: {Chicago: [[Chicago, 8512, 7, 3620.15], [Chicago, 8421, 7, 5625]], California: [[California, 8512, 21, 11407.630000000001], [California, 8708, 12, 5537.84]]}
Original Map: {Chicago: [[8512, 7, 3620.15], [8421, 7, 5625]], California: [[8512, 21, 11407.630000000001], [8708, 12, 5537.84]]}
Hope this helps. Happy Coding :)