class RandomObject {
RandomObject(this.x, this.y);
RandomObject.clone(RandomObject randomObject): this(randomObject.x, randomObject.y);
int x;
int y;
}
然后,你可以只调用复制与原件,如下所示:
final RandomObject original = RandomObject(1, 2);
final RandomObject copy = RandomObject.clone(original);
Person copyWith({
List<Skills>? skills,
}) =>
Person(skills: skills ?? this.skills);
如果您的列表是基元类型,您可以这样做。基本类型会被自动复制,因此您可以使用这种更短的语法。
class Person {
final List<int> names;
const Person({required this.names});
Person copyWith({
List<int>? names,
}) =>
Person(names: names ?? []...addAll(names));
}
extension Clone<T> on T {
/// in Flutter
Future<T> clone() => compute<T, T>((e) => e, this);
/// in Dart
Future<T> clone() async {
final receive = ReceivePort();
receive.sendPort.send(this);
return receive.first.then((e) => e as T).whenComplete(receive.close);
}
}