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

前端 未结 11 2287
谎友^
谎友^ 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

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

提交回复
热议问题