dart

How to copy a Rectangle in Dart


I have two rectangles, one that is occasionally reset to some other rectangle. In C++ I'd just do:

_rect = _resetRect;

But in Dart that actually means that _rect now refers to the same object as _resetRect which is not what I want.

My current solution is this:

_rect.left = _resetRect.left;
_rect.width = _resetRect.width;
_rect.top = _resetRect.top;
_rect.height = _resetRect.height;

This is idiotic. Other questions suggest that there is no built-in way to copy objects (like there is in C++), and you have to rely on the object providing a clone() method. But Rectangle doesn't have one so what do I do?

Also even if it did have a clone() method, wouldn't that allocate an entirely new Rectangle rather than just setting the fields of the existing one (like C++'s operator=), and therefore be less efficient?


Solution

  • C++ also does not have a way to deep-copy an object which contains pointers/references to other objects. In Dart, all values are references, so that restriction applies to all objects.

    I assume this is a MutableRectangle since the Rectange in dart:math is unmodifiable. That class indeed does not have a way to clone the values of another rectangle, so you have to copy each of them. I would use a cascade for that:

    _rect
      ..left = _resetRect.left
      ..top = _resetRect.top
      ..width = _resetRect.width
      ..height = _resetRect.height;
    

    Alternatively, if it happens often enough, you can create a helper function:

    void copyRectangle(MutableRectangle target, Rectangle source) {
       target
         ..left = source.left
         ..top = source.top
         ..width = source.width
         ..height = source.height;
    }