I'm working on a Flutter/Dart application where I need to pass a Map object from one screen to another. However, I want to ensure that the original Map object remains unchanged and that any modifications made to the passed Map object on the second screen do not affect the original Map object on the first screen. Original Map object contains JSON init so it will be not clear structure of it.
Map originalMap = {
'question': 'What is your name',
};
Map modifiedMap = {
'question': 'What is your name',
'answer': 'XYZ',
};
I've considered using methods like copyWith or creating a new Map object from the original Map.
Map modifiedMap = new Map.from(originalMap);
Map modifiedMap = JSON.decode(JSON.encode(originalMap));
Any guidance or examples would be greatly appreciated. Thank you!
What you are looking for is performing a deep copy of your JSON object.
Deep copy
JSON objects, when represented as Dart objects are of type
Map<String, dynamic>, where according to JSON specification the datatype for the dynamic are:Map<String, dynamic>)Your deep copy function shall consider all the types in order to also copy the nested objects, which is not performed when using
Map.fromorList.fromconstructors.To Json => from Json
An alternative could be just convert you JSON object to a string and then back to an object: