I went through a few questions about this on Stackoverflow but nothing made sense to me. What's the easiest way?
Asked
Active
Viewed 6,713 times
4
-
1There are no built-in way to deep-copy a object. There are maybe packages which makes it easier but otherwise you need to manually create the code to copy the object (e.g. make a copy constructor which takes a object as argument, or make a copy method on the object). – julemand101 Jan 13 '21 at 10:37
-
1The easiest way is to do it yourself (make by hand). – mezoni Jan 13 '21 at 16:05
-
`copyWith` is the best way now (you can check how flutter [Theme](https://flutter.dev/docs/cookbook/design/themes#extending-the-parent-theme) works). You can do copyWith by your own or use code-generators package like [freezed](https://pub.dev/packages/freezed) – yellowgray Jan 14 '21 at 03:03
1 Answers
9
Check below class for reference:
class Customer {
final String id;
final String name;
final String address;
final String phoneNo;
final String gstin;
final String state;
Customer({
this.id = '',
@required this.name,
@required this.address,
@required this.phoneNo,
this.gstin,
@required this.state,
});
Customer copyWith({
String name,
String address,
String phoneNo,
String gstin,
String state,
}) {
return Customer(
name: name ?? this.name,
address: address ?? this.address,
phoneNo: phoneNo ?? this.phoneNo,
gstin: gstin ?? this.gstin,
state: state ?? this.state,
);
}
}
using copyWith constructor you can create a copy of an object.
if you don't pass any argument to copyWith constructor it returns a new object with the same values
But, if you wish to change any argument you do with copyWith constructor it will return the object copy with the new argument value you pass
Note: In copyWith constructor, suppose if you change one argument value then other argument value stays the same as the first object.

Shahood ul Hassan
- 745
- 2
- 9
- 19

Aakash kondhalkar
- 600
- 4
- 11
-
@YannMassard You need deep clone each item in List, Map. Then create new List, Map with item cloned. – mducc Sep 29 '21 at 07:48
-
@Aakash Pleased update the answer to reflect a more complete solution: deep cloning Lists and Maps, if possible multidimensional maps. – Xao Apr 29 '23 at 21:15