-1

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.

mhmd
  • 107
  • 1
  • 8
  • can you include the model class? – Yeasin Sheikh Nov 07 '21 at 07:08
  • considered it any class with any properties just make it when you equal the class with new class when you change property value not changing in the parent class property value – mhmd Nov 07 '21 at 13:21

2 Answers2

1

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

NaKib
  • 483
  • 4
  • 12
0

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}';
}

quoci
  • 2,388
  • 1
  • 7
  • 18