CodeBlanks Logo Icon CodeBlanks

Summary - CustomPainter

Combine CustomPaint and Path to make a pie chart.

CustomPaint and Path for a pie chart

To make a pie chart, you draw each slice with canvas.drawArc or with the addArc method of Path. You use a different color Paint for each slice and sum the slice angles to get a full circle.

final path = Path();
path.moveTo(50, 50);
path.addArc(rect, startAngle, sweepAngle);
path.close();
canvas.drawPath(path, paint);

Practice Draw a half-circle slice

Write the paint method in PiePainter. In a 100x100 Rect, using drawArc with a black fill brush, draw an arc starting at 0 radians sweeping math.pi radians (useCenter: true). In main, take an instance and print its type.

Starter code

main.dart
import 'dart:math' as math;
import 'package:flutter/material.dart';

// PiePainter sınıfını tanımla

void main() {
  // PiePainter örneğini al ve tipini yazdır
}

Sample solution

main.dart
import 'dart:math' as math;
import 'package:flutter/material.dart';

class PiePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.black
      ..style = PaintingStyle.fill;
    final rect = Rect.fromLTWH(0, 0, 100, 100);
    canvas.drawArc(rect, 0, math.pi, true, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

void main() {
  final painter = PiePainter();
  print(painter.runtimeType);
}

Expected output

PiePainter

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is added to Path to specify the arc of a pie slice?

  • path.close
  • path.moveTo
  • path.addArc Correct answer
  • path.lineTo

Explanation: addArc adds an arc to the Path and forms the curved edge of a pie slice; lineTo draws a straight line, moveTo only moves the pen, and close closes the shape.

2 Pass sweepAngle to addArc

Question
path.addArc(rect, startAngle, ____);
Answer
path.addArc(rect, startAngle, sweepAngle);

Explanation: The third parameter of addArc is sweepAngle; it specifies how much angle the arc covers.

3 Pie chart parts

Term Meaning
CustomPaint Pie chart widget
Path Slice shape
addArc Adds an arc
Paint Slice color

All lessons in Advanced