handleOneCollision function

void handleOneCollision({
  1. required int dragOrderId,
  2. required int collisionOrderId,
  3. required Map<int, GridItemEntity> childrenIdMap,
  4. required List<int> lockedChildren,
  5. required ReorderCallback onReorder,
})

Swapping positions and orderId of items with dragOrderId and collisionOrderId.

Usually this is called after a collision happens between two items while dragging it. The dragOrderId and collisionOrderId should be different and the collisionOrderId should not be in lockedChildren. If that is not the case, then the following values are swapped between the two items with dragOrderId and collisionOrderId -> localPosition, globalPosition and orderId.

Also childrenOrderIdMap gets an update by swapping the values of the dragged and collision item.

It's important that the id does not change because this value is needed to animate the new position of the given childrenIdMap.

There is no return value because childrenIdMap and childrenOrderIdMap gets immediately updated.

Implementation

void handleOneCollision({
  required int dragOrderId,
  required int collisionOrderId,
  required Map<int, GridItemEntity> childrenIdMap,
  required List<int> lockedChildren,
  required ReorderCallback onReorder,
}) {
  assert(dragOrderId != collisionOrderId);

  if (lockedChildren.contains(collisionOrderId)) {
    return;
  }

  final entryA = childrenIdMap.entries.firstWhere(
    (entry) => entry.value.orderId == dragOrderId,
  );
  final entryB = childrenIdMap.entries.firstWhere(
    (entry) => entry.value.orderId == collisionOrderId,
  );

  final updatedEntryValueA = entryA.value.copyWith(
    localPosition: entryB.value.localPosition,
    orderId: entryB.value.orderId,
  );
  final updatedEntryValueB = entryB.value.copyWith(
    localPosition: entryA.value.localPosition,
    orderId: entryA.value.orderId,
  );

  childrenIdMap[entryA.key] = updatedEntryValueA;
  childrenIdMap[entryB.key] = updatedEntryValueB;

  onReorder(entryA.value.orderId, entryB.value.orderId);
}