cyclingMechanic method

void cyclingMechanic(
  1. DragUpdateDetails details
)

Handles the rotation logic during a horizontal drag gesture.

Implementation

void cyclingMechanic(DragUpdateDetails details) {
  // counter-clockwise drag
  if (details.localPosition.dx.floorToDouble() > _detailsVar.localPosition.dx.floorToDouble()) {
    data.value = data.value + widget.dragSpeed;
  }
  // clockwise drag
  else {
    data.value = data.value - widget.dragSpeed;
  }

  final itemCount = widget.items.length;
  final step = 2 * pi / itemCount; // 2 * pi

  // Calculate index based on the rotation angle.
  // The angle is divided by the step angle for each item, and rounded to the nearest whole number.
  // This gives the index of the item that is closest to the top position.
  final rawIndex = -data.value / step;
  final snappedIndex = rawIndex.round();

  // Normalize the index to ensure it's within the valid range [0, itemCount - 1].
  // The modulo operator (%) handles wrapping around, and adding itemCount before the modulo
  // ensures the result is always positive.
  topIndex.value = (snappedIndex % itemCount + itemCount) % itemCount;
}