How can I clone an Object (deep copy) in Dart?

前端 未结 11 2354
谎友^
谎友^ 2020-12-01 13:22

Is there a Language supported way make a full (deep) copy of an Object in Dart?

Secondary only; are there multiple ways of doing this, and what are the differences?<

11条回答
  •  被撕碎了的回忆
    2020-12-01 14:07

    An example of Deep copy in dart.

    void main() {
      Person person1 = Person(
          id: 1001,
          firstName: 'John',
          lastName: 'Doe',
          email: 'john.doe@email.com',
          alive: true);
    
      Person person2 = Person(
          id: person1.id,
          firstName: person1.firstName,
          lastName: person1.lastName,
          email: person1.email,
          alive: person1.alive);
    
      print('Object: person1');
      print('id     : ${person1.id}');
      print('fName  : ${person1.firstName}');
      print('lName  : ${person1.lastName}');
      print('email  : ${person1.email}');
      print('alive  : ${person1.alive}');
      print('=hashCode=: ${person1.hashCode}');
    
      print('Object: person2');
      print('id     : ${person2.id}');
      print('fName  : ${person2.firstName}');
      print('lName  : ${person2.lastName}');
      print('email  : ${person2.email}');
      print('alive  : ${person2.alive}');
      print('=hashCode=: ${person2.hashCode}');
    }
    
    class Person {
      int id;
      String firstName;
      String lastName;
      String email;
      bool alive;
      Person({this.id, this.firstName, this.lastName, this.email, this.alive});
    }
    

    And the output below.

    id     : 1001
    fName  : John
    lName  : Doe
    email  : john.doe@email.com
    alive  : true
    =hashCode=: 515186678
    
    Object: person2
    id     : 1001
    fName  : John
    lName  : Doe
    email  : john.doe@email.com
    alive  : true
    =hashCode=: 686393765
    

提交回复
热议问题