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

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

    No as far as open issues seems to suggest:

    http://code.google.com/p/dart/issues/detail?id=3367

    And specifically:

    .. Objects have identity, and you can only pass around references to them. There is no implicit copying.
    
    0 讨论(0)
  • 2020-12-01 14:20

    Let's say you a have class

    Class DailyInfo
    
      { 
         String xxx;
      }
    

    Make a new clone of the class object dailyInfo by

     DailyInfo newDailyInfo =  new DailyInfo.fromJson(dailyInfo.toJson());
    

    For this to work your class must have implemented

     factory DailyInfo.fromJson(Map<String, dynamic> json) => _$DailyInfoFromJson(json);
    
    
    Map<String, dynamic> toJson() => _$DailyInfoToJson(this);
    

    which can be done by making class serializable using

    @JsonSerializable(fieldRename: FieldRename.snake, includeIfNull: false)
    Class DailyInfo{ 
     String xxx;
    }
    
    0 讨论(0)
  • 2020-12-01 14:21

    I guess for not-too-complex objects, you could use the convert library:

    import 'dart:convert';
    

    and then use the JSON encode/decode functionality

    Map clonedObject = JSON.decode(JSON.encode(object));
    

    If you're using a custom class as a value in the object to clone, the class either needs to implement a toJson() method or you have to provide a toEncodable function for the JSON.encode method and a reviver method for the decode call.

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

    Late to the party, but I recently faced this problem and had to do something along the lines of :-

    class RandomObject {
    
    RandomObject(this.x, this.y);
    
    RandomObject.clone(RandomObject randomObject): this(randomObject.x, randomObject.y);
    
    int x;
    int y;
    }
    

    Then, you can just call copy with the original, like so:-

    final RandomObject original = RandomObject(1, 2);
    final RandomObject copy = RandomObject.clone(original);
    
    0 讨论(0)
  • 2020-12-01 14:23

    You could use the equatable library https://pub.dev/packages/equatable It allows for equating different instances of the same class provided they extend the Equatable class.

    0 讨论(0)
提交回复
热议问题