如何使用 dart_mappable 克隆对象而不进行序列化/反序列化?
我想简单地说:
import 'dart:ui';
import 'package:dart_mappable/dart_mappable.dart';
@MappableClass()
class Point {
final Offset coordinates
final String type;
Point(this.coordinates, this.type);
}
void main() {
var point1 = Point(Offset.zero, 'this type');
var point2 = point1.copyWith();
assert(point1 != point2);
}
但是失败了。
只有当我实际更改 copyWith 调用上的某些属性时,它才有效:
var point2 = point1.copyWith(type: 'other type');
但由于我希望我的财产是最终的,所以我无法做到这一点并拥有我想要的原件副本。或者我需要连续执行 2 个 copyWiths,这看起来很愚蠢:
var pointTemp = point1.copyWith(type: 'other type');
var point2 = pointTemp.copyWith(type: point1.type);
是否有某种方法可以使用 dart_mappable 进行克隆而无需序列化/反序列化?使用 copyWith 会更好吗?
查看dart_mappable包的正确用法。我添加了一些缺失的行。看看评论。认为这会起作用
import 'dart:ui';
import 'package:dart_mappable/dart_mappable.dart';
// Will be generated by dart_mappable
part 'point.mapper.dart'; // Add this line
@MappableClass()
class Point with PointMappable { // Add the mixin
final Offset coordinates; // Fix missing semicolon
final String type;
Point(this.coordinates, this.type);
}
void main() {
var point1 = Point(Offset.zero, 'this type');
// Use clone() method which is generated by dart_mappable
var point2 = point1.clone();
assert(point1 != point2);
}