findClosestItemIndex static method

int findClosestItemIndex(
  1. Offset position,
  2. List<Offset> itemPositions,
  3. List<Size> itemSizes
)

Finds the closest item index to a given position

Implementation

static int findClosestItemIndex(
  Offset position,
  List<Offset> itemPositions,
  List<Size> itemSizes,
) {
  if (itemPositions.isEmpty) return 0;

  double minDistance = double.infinity;
  int closestIndex = 0;

  for (int i = 0; i < itemPositions.length; i++) {
    final itemCenter = Offset(
      itemPositions[i].dx + itemSizes[i].width / 2,
      itemPositions[i].dy + itemSizes[i].height / 2,
    );

    final distance = (position - itemCenter).distance;
    if (distance < minDistance) {
      minDistance = distance;
      closestIndex = i;
    }
  }

  return closestIndex;
}