skip to Main Content

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?

2

Answers


  1. See the correct usage of dart_mappable package. I have added few missing lines. See the comments. Think this would work

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

    In order to generate the serialization code, run the following command:

    dart pub run build_runner build
    

    You’ll need to re-run code generation each time you are making changes to your annotated classes. During development, you can use watch to automatically watch your changes: dart pub run build_runner watch

    • quoted from official documentation.

    And obviously you would have added necessary dev dependencies I believe.

    flutter pub add build_runner --dev
    flutter pub add dart_mappable_builder --dev
    
    Login or Signup to reply.
  2. 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
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search