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

前端 未结 11 2283
谎友^
谎友^ 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 13:57

    It only works for object types that can be represented by JSON.

    ClassName newObj = ClassName.fromMap(obj.toMap());
    

    or

    ClassName newObj = ClassName.fromJson(obj.toJson());
    
    0 讨论(0)
  • 2020-12-01 13:58

    Darts built-in collections use a named constructor called "from" to accomplish this. See this post: Clone a List, Map or Set in Dart

    Map mapA = {
        'foo': 'bar'
    };
    Map mapB = new Map.from(mapA);
    
    0 讨论(0)
  • 2020-12-01 13:58

    To copy an object without reference, the solution I found was similar to the one posted here, however if the object contains MAP or LIST you have to do it this way:

    class Item {
      int id;
      String nome;
      String email;
      bool logado;
      Map mapa;
      List lista;
      Item({this.id, this.nome, this.email, this.logado, this.mapa, this.lista});
    
      Item copyWith({ int id, String nome, String email, bool logado, Map mapa, List lista }) {
        return Item(
          id: id ?? this.id,
          nome: nome ?? this.nome,
          email: email ?? this.email,
          logado: logado ?? this.logado,
          mapa: mapa ?? Map.from(this.mapa ?? {}),
          lista: lista ?? List.from(this.lista ?? []),
        );
      }
    }
    
    Item item1 = Item(
        id: 1,
        nome: 'João Silva',
        email: 'joaosilva@gmail.com',
        logado: true,
        mapa: {
          'chave1': 'valor1',
          'chave2': 'valor2',
        },
        lista: ['1', '2'],
      );
    
    // -----------------
    // copy and change data
    Item item2 = item1.copyWith(
        id: 2,
        nome: 'Pedro de Nobrega',
        lista: ['4', '5', '6', '7', '8']
      );
    
    // -----------------
    // copy and not change data
    Item item3 = item1.copyWith();
    
    // -----------------
    // copy and change a specific key of Map or List
    Item item4 = item1.copyWith();
    item4.mapa['chave2'] = 'valor2New';
    
    

    See an example on dartpad

    https://dartpad.dev/f114ef18700a41a3aa04a4837c13c70e

    0 讨论(0)
  • 2020-12-01 14:04

    Trying using a Copyable interface provided by Dart.

    0 讨论(0)
  • 2020-12-01 14:07

    Unfortunately no language support. What I did is to create an abstract class called copyable which I can implement in the classes I want to be able to copy:

    abstract class Copyable<T> {
      T copy();
      T copyWith();
    }
    

    I can then use this as follows, e.g. for a Location object:

    @override
    Location copy() {
      return Location(
          longitude: this.longitude,
          latitude: this.latitude,
          timestamp: this.timestamp,
          country: this.country,
          locality: this.locality,
          postalCode: this.postalCode,
          name: this.name,
          isoCountryCode: this.isoCountryCode,
          bearing: this.bearing);
    }
    
    @override
    Location copyWith({
        String country,
        String locality,
        String name
      }) {
      return Location(
          country: country,
          locality: locality,
          name: name,
          longitude: this.longitude,
          latitude: this.latitude,
          timestamp: this.timestamp,
          postalCode: this.postalCode,
          isoCountryCode: this.isoCountryCode,
          bearing: this.bearing);
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题