Search code examples
flutterdart

How can I clone and object with dart_mappable without serializing/deserializing?


How can I clone an object with dart_mappable without serializing/deserializing?

I would like to simply:

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

but it fails.

It only works if I actually change some property on the copyWith call like:

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

but as I want my properties to be final, I can't do it and have my desired copy of the original. Or I would need to do 2 copyWiths in a row, which seems silly:

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

Is there some way to clone with dart_mappable without serializing/deserializing? Using copyWith would be a plus?


Solution

  • The mixin PointMappable generated by the dart_mappable builder overrides the operator == and the getter hashCode so that objects of type Point are compared using the class variables coordinates and type.

    For this reason I would expect:

    var point1 = Point(Offset.zero, 'this type');
    point1 == point1.copyWith();            // True
    identical(point1, point1.copyWith());   // False