Home > Back-end >  How to Copy an Object without Create Reference Dart
How to Copy an Object without Create Reference Dart

Time:11-07

I want to give object value from another but when I modify name2 it modify name1 at same time.

Item item2 = item1;
item2.name = 'a';

I want every object not linked to each other.

CodePudding user response:

Considering you are using a Map, You can use from to achieve this, reference answer Here

Item Item1 = {
    'foo': 'bar'
};
Item Item2 = new Item.from(Item1);

You can also use fromJson and toJson to achieve this

Item1 = Item.fromJson(Item2.toJson());

but for this you need to create fromJson and toJson manually. you can do that easily by pasting your json here

CodePudding user response:

Let's say you have an item class with the properties id and name. You can copy a class without referencing it if you create a copyWith method like below. It will copy the class and modify only the values that you pass as arguments. Try it out in Dart Pad.

void main() {
  final Item item1 = Item(id: 1, name: 'Item 1');
  final Item item2 = item1.copyWith(name: 'Item 2');
  print(item1); // Item{id: 1, name: Item 1}
  print(item2); // Item{id: 1, name: Item 2}
  print(item1); // Item{id: 1, name: Item 1}
}

class Item {
  const Item({
    required this.id,
    required this.name,
  });
  final int id;
  final String name;

  Item copyWith({int? id, String? name}) => Item(
        id: id ?? this.id,
        name: name ?? this.name,
      );
  
  @override
  String toString()=> 'Item{id: $id, name: $name}';
}

  • Related