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!
2
Answers
instead of map, i would prefer class. in class you can make the class immutable by adding
const
modifier on it’s constructor and then createcopyWith
function. then if you want to manage the data flow easily, i suggest you to have state management so you can share data across screen and modify them easily.imagine Model View Controller. you have Model class which is the
QuestionAnswerModel
, you haveQuizController
to control the UI, you haveQuizQuestionView
andQuizDetailView
which accessing one controller (QuizController
)it would be whole lot easier if you don’t use map.
anyway you might be interested in Code Generation (https://pub.dev/packages/freezed this is my favorite Code Generation to generate model class) this will allow you to generate boilerplate such as
copyWith
automaticallyWhat 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.from
orList.from
constructors.To Json => from Json
An alternative could be just convert you JSON object to a string and then back to an object: