getItemsCollision function

int? getItemsCollision({
  1. required int orderId,
  2. required Offset position,
  3. required Size size,
  4. required Map<int, GridItemEntity> childrenIdMap,
  5. required List<int> lockedChildren,
})

Checks collision of item with given id with another one in childrenIdMap.

Expects that the id is existing in childrenIdMap and is not locked inside of lockedChildren.

Depending of the current position of the item, it's possible that there is a collision with another one in childrenIdMap. That happens if the dragged item lays above another one. It's also possible that the item has a collision with itself. In that case you should check if the returned id is equal to the given id because most of the cases you don't want to update sth if nothing changes.

If there was no collision or the collision item is found in lockedChildren, then null will be returned. Otherwise the id of the collision item in childrenIdMap.

Implementation

int? getItemsCollision({
  required int orderId,
  required Offset position,
  required Size size,
  required Map<int, GridItemEntity> childrenIdMap,
  required List<int> lockedChildren,
}) {
  int? collisionOrderId;

  // child does not exist or is locked
  if (lockedChildren.contains(orderId)) {
    return null;
  }

  final currentDx = position.dx + size.width / 2;
  final currentDy = position.dy + size.height / 2;

  for (final entry in childrenIdMap.entries) {
    final item = entry.value;
    final itemDx = item.localPosition.dx;
    final itemDy = item.localPosition.dy;
    final itemWidth = item.size.width;
    final itemHeight = item.size.height;

    // checking collision with full item size and local position
    if (currentDx >= itemDx &&
        currentDy >= itemDy &&
        currentDx <= itemDx + itemWidth &&
        currentDy <= itemDy + itemHeight) {
      collisionOrderId = entry.value.orderId;
      break;
    }
  }

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

  return collisionOrderId;
}