In my Flutter-Dart project, I have a map (myMap) that contains nested lists and maps, and these nested structures can further contain lists or maps. The data within these structures is dynamic, originating from a server, making it challenging to anticipate their lengths or values. An illustrative example of myMap is as follows:
Map<String, dynamic> myMap = {
'key': {
'key': [1, 2, 3],
'key2': {
'key': 23,
'subKey': {
'nestedKey': [4, 5, {'deepKey': {'finalList': [9, 10, {'ultraKey': [11, 12]}]}}]
}
}
},
'key2': {
'key': [1, 2, 3, {'dsf': [1, 2, {'superKey': [3, 4, {'megaKey': [5, 6]}]}]}],
'key2': {
'key': 23,
'fdasd': [
{
'nestedList': [
7,
8,
{
'deepKey': {
'finalList': [9, 10, {'ultraKey': [11, 12, {'ultimateKey': [13, 14]}]}]
}
}
]
}
]
}
}
};
Now, I need to create another map (myMap2) = (myMap ) that is entirely independent of myMap. Merely assigning myMap2 = myMap creates a reference, leading to changes in one affecting the other. Similarly, using Map.of(myMap) doesn’t achieve independence for nested lists and maps; modifications to nested structures in myMap reflect in myMap2.
I am currently using a manual approach involving looping through myMap and conditionally copying lists or maps using List.of() or Map.of(). However, this solution is not optimal due to the dynamic and unpredictable nature of the data received from the server.
Is there a concise and efficient one-liner or method that ensures complete independence for all items, including nested structures within myMap and those within them?
Thank you for your guidance.
>Solution :
You can always jsonDecode(jsonEncode(data)) to get a deep clone of anything that has valid .toJson and .fromJson methods.