Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to clone objects in Dart?

I went through a few questions about this on Stackoverflow but nothing made sense to me. What's the easiest way?

like image 678
Track Back Avatar asked Oct 20 '25 14:10

Track Back


1 Answers

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.

like image 166
Aakash kondhalkar Avatar answered Oct 22 '25 04:10

Aakash kondhalkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!