You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用dart_mappable在不序列化/反序列化的情况下克隆对象?

问题描述

我尝试通过以下方式使用dart_mappable克隆对象:

import 'dart:ui';
import 'package:dart_mappable/dart_mappable.dart';

part 'point.mapper.dart';

@MappableClass()
class Point with PointMappable {
  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');

由于我希望保持属性为final,无法通过这种方式得到原对象的副本。虽然可以连续调用两次copyWith,但这种方式很不合理:

var pointTemp = point1.copyWith(type: 'other type');
var point2 = pointTemp.copyWith(type: point1.type);

请问是否存在无需序列化/反序列化即可使用dart_mappable克隆对象的方法?最好能通过copyWith实现?

解决方案

方法1:显式传递所有原属性调用copyWith

可以直接通过copyWith传递原对象的所有属性值,生成完全一致的新实例,既保留final属性特性,又实现克隆:

var point2 = point1.copyWith(
  coordinates: point1.coordinates,
  type: point1.type,
);

方法2:封装自定义clone方法

为简化调用,可在Point类中封装一个自定义克隆方法,内部复用copyWith逻辑:

@MappableClass()
class Point with PointMappable {
  final Offset coordinates;
  final String type;

  Point(this.coordinates, this.type);

  // 自定义克隆方法
  Point clone() => copyWith(
        coordinates: coordinates,
        type: type,
      );
}

后续直接调用clone()即可获取副本:

var point2 = point1.clone();
assert(point1 != point2); // 断言成立

方法3:升级dart_mappable版本

部分旧版本的dart_mappable代码生成逻辑要求copyWith必须传入至少一个参数,升级到最新版后,无参数调用copyWith()会自动生成与原对象属性完全一致的新实例,直接满足克隆需求。

内容的提问来源于stack exchange,提问作者Rsevero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 00:32:37