getNearestTouchedSpot method

  1. @visibleForTesting
TouchLineBarSpot? getNearestTouchedSpot(
  1. Size viewSize,
  2. Offset touchedPoint,
  3. LineChartBarData barData,
  4. int barDataPosition,
  5. PaintHolder<LineChartData> holder,
)

find the nearest spot base on the touched offset

Implementation

@visibleForTesting
TouchLineBarSpot? getNearestTouchedSpot(
  Size viewSize,
  Offset touchedPoint,
  LineChartBarData barData,
  int barDataPosition,
  PaintHolder<LineChartData> holder,
) {
  final data = holder.data;
  if (!barData.show) {
    return null;
  }

  /// Find the nearest spot (based on distanceCalculator)
  final sortedSpots = <AFlSpot>[];
  double? smallestDistance;
  for (final spot in barData.spots) {
    if (spot.isNull()) continue;
    final distance = data.lineTouchData.distanceCalculator(
      touchedPoint,
      Offset(
        getPixelX(spot.x, viewSize, holder),
        getPixelY(spot.y, viewSize, holder),
      ),
    );

    if (distance <= data.lineTouchData.touchSpotThreshold) {
      smallestDistance ??= distance;

      if (distance < smallestDistance) {
        sortedSpots.insert(0, spot);
        smallestDistance = distance;
      } else {
        sortedSpots.add(spot);
      }
    }
  }

  if (sortedSpots.isNotEmpty) {
    return TouchLineBarSpot(
      barData,
      barDataPosition,
      sortedSpots.first,
      smallestDistance!,
    );
  } else {
    return null;
  }
}