getAnimationTargetIndex function

int getAnimationTargetIndex({
  1. required double dx,
  2. required double dy,
  3. required int total,
  4. required Size itemSize,
  5. required Offset offset,
  6. required Offset scroll,
  7. required double crossAxisSpacing,
  8. required double mainAxisSpacing,
  9. required Axis direction,
  10. required int crossCount,
})

Computing Animation Target Index

Implementation

int getAnimationTargetIndex({
  required double dx,
  required double dy,
  required int total,
  required Size itemSize,
  required Offset offset,
  required Offset scroll,
  required double crossAxisSpacing,
  required double mainAxisSpacing,
  required Axis direction,
  required int crossCount,
}) {
  int topIndex = 0;
  int leftIndex = 0;
  int targetIndex = 0;

  double newTop = 0;
  double newLeft = 0;
  double newWidth = 0;
  double newHeight = 0;

  final tx = dx + scroll.dx;
  final ty = dy + scroll.dy;
  final left = tx - offset.dx - itemSize.width / 2 - 16.0;
  final top = ty - offset.dy - itemSize.height / 2 - 16.0;

  if (direction == Axis.vertical) {
    newTop = top + mainAxisSpacing / 2;
    newLeft = left + crossAxisSpacing / 2;
    newWidth = itemSize.width + crossAxisSpacing;
    newHeight = itemSize.height + mainAxisSpacing;

    topIndex = max((newTop / newHeight).round(), 0);
    leftIndex = max((newLeft / newWidth).round(), 0);
    targetIndex = leftIndex + crossCount * topIndex;
  }

  if (direction == Axis.horizontal) {
    newTop = top + crossAxisSpacing / 2;
    newLeft = left + mainAxisSpacing / 2;
    newWidth = itemSize.width + mainAxisSpacing;
    newHeight = itemSize.height + crossAxisSpacing;

    topIndex = max((newTop / newHeight).round(), 0);
    leftIndex = max((newLeft / newWidth).round(), 0);
    targetIndex = topIndex + crossCount * leftIndex;
  }

  if (targetIndex >= total) {
    targetIndex = total - 1;
  }

  if (targetIndex < 0) {
    targetIndex = 0;
  }

  return targetIndex;
}