0

I can clone Maps like this:

var copy = json.decode(json.encode(original));

but how could I do similar thing for classes without converting it to a Map?

var original = new Original();

var copy = original;

copy.prop = "New";

print(original.prop); // this should be "old", not "new"
Dani
  • 3,128
  • 2
  • 43
  • 91
  • Does this answer your question? [How can I clone an Object (deep copy) in Dart?](https://stackoverflow.com/questions/13107906/how-can-i-clone-an-object-deep-copy-in-dart) – Siddharth Agrawal Aug 12 '21 at 10:14
  • I do not understand what's the problem with using maps. If it is such a big problem, why don't you make a function in the class called clone where u creat a new Object of that class and loop over all the properties assigning them – Siddharth Agrawal Aug 12 '21 at 10:16
  • https://developer.school/dart-flutter-what-does-copywith-do – pskink Aug 12 '21 at 10:18
  • https://www.flutterclutter.dev/flutter/basics/clone-copy-objects-in-dart/2020/1851/ – t00n Aug 12 '21 at 10:22
  • @TechnicalWorld you are creating another reference – Dani Aug 12 '21 at 10:26
  • what I never did was converting it back from Map to class – Dani Aug 12 '21 at 10:56

1 Answers1

0

There is no direct method do this with a class. I have to create the class again like this:

var copy = new Original(prop: "new");

print(original.prop); // "old"
print(copy.prop); // "new"
Dani
  • 3,128
  • 2
  • 43
  • 91