Hello everyone,
I needed to clone an object in the project I was working on. I did a little research on this. Even though there are dart packages developed for this job, I would like to talk about an easier and more effective method.
I think most of us are already doing json serilization in their projects. We have the fromJson and toJson methods. We can use these methods for the object we want to clone.
I go to the codes without extending much :)
factory SearchRequest.fromJson(Map<String, dynamic> json) => _$SearchRequestFromJson(json);
Map<String, dynamic> toJson() => _$SearchRequestToJson(this);
SearchRequest clone() {
final String jsonString = json.encode(this);
final jsonResponse = json.decode(jsonString);
return SearchRequest.fromJson(jsonResponse as Map<String, dynamic>);
}
I added a method called clone, in this method I first convert my object to json string and then convert it back to the object. Thus, I create a new object with the data. (You must add “import ‘dart:convert’;” package)
I hope it will be useful, thanks for reading.
Mar 20, 2020