handleTouch method

PieTouchedSection handleTouch(
  1. Offset localPosition,
  2. Size viewSize,
  3. PaintHolder<PieChartData> holder
)

Makes a PieTouchedSection based on the provided localPosition

Processes localPosition and checks the elements of the chart that are near the offset, then makes a PieTouchedSection from the elements that has been touched.

Implementation

PieTouchedSection handleTouch(
  Offset localPosition,
  Size viewSize,
  PaintHolder<PieChartData> holder,
) {
  final data = holder.data;
  final sectionsAngle = calculateSectionsAngle(data.sections, data.sumValue);

  final center = Offset(viewSize.width / 2, viewSize.height / 2);

  final touchedPoint2 = localPosition - center;

  final touchX = touchedPoint2.dx;
  final touchY = touchedPoint2.dy;

  final touchR = math.sqrt(math.pow(touchX, 2) + math.pow(touchY, 2));
  var touchAngle = Utils().degrees(math.atan2(touchY, touchX));
  touchAngle = touchAngle < 0 ? (180 - touchAngle.abs()) + 180 : touchAngle;

  PieChartSectionData? foundSectionData;
  var foundSectionDataPosition = -1;

  /// Find the nearest section base on the touch spot
  final relativeTouchAngle = (touchAngle - data.startDegreeOffset) % 360;
  var tempAngle = 0.0;
  for (var i = 0; i < data.sections.length; i++) {
    final section = data.sections[i];
    var sectionAngle = sectionsAngle[i];

    tempAngle %= 360;
    if (data.sections.length == 1) {
      sectionAngle = 360;
    } else {
      sectionAngle %= 360;
    }

    /// degree criteria
    final space = data.sectionsSpace / 2;
    final fromDegree = tempAngle + space;
    final toDegree = sectionAngle + tempAngle - space;
    final isInDegree =
        relativeTouchAngle >= fromDegree && relativeTouchAngle <= toDegree;

    /// radius criteria
    final centerRadius = calculateCenterRadius(viewSize, holder);
    final sectionRadius = centerRadius + section.radius;
    final isInRadius = touchR > centerRadius && touchR <= sectionRadius;

    if (isInDegree && isInRadius) {
      foundSectionData = section;
      foundSectionDataPosition = i;
      break;
    }

    tempAngle += sectionAngle;
  }

  return PieTouchedSection(
    foundSectionData,
    foundSectionDataPosition,
    touchAngle,
    touchR,
  );
}