Learn/Advanced UI/CustomPainter & Canvas

CustomPainter & Canvas

Draw custom shapes, charts, and graphics on a canvas

8 min~5 min read+45 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Painter Performance Strategy
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary
  9. 9. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

CustomPainter & Canvas

CustomPainter gives you direct access to a canvas where you can draw anything from shapes, lines, arcs, and paths to gradients and beyond. CustomPainter is commonly used for building charts, custom animations, and unique UI elements that standard widgets cannot achieve. Understanding the Canvas API opens up possibilities for creating entirely custom visual experiences in your Flutter applications.

dart
1// ── Basic CustomPainter ──
2class CircleProgressPainter extends CustomPainter {
3 final double progress; // 0.0 to 1.0
4 final Color color;
5
6 CircleProgressPainter({required this.progress, required this.color});
7
8 @override
9 void paint(Canvas canvas, Size size) {
10 final center = Offset(size.width / 2, size.height / 2);
11 final radius = size.width / 2 - 10;
12
13 // Background circle
14 final bgPaint = Paint()
15 ..color = Colors.grey[300]!
16 ..strokeWidth = 8
17 ..style = PaintingStyle.stroke;
18 canvas.drawCircle(center, radius, bgPaint);
19
20 // Progress arc
21 final progressPaint = Paint()
22 ..color = color
23 ..strokeWidth = 8
24 ..style = PaintingStyle.stroke
25 ..strokeCap = StrokeCap.round;
26 canvas.drawArc(
27 Rect.fromCircle(center: center, radius: radius),
28 -pi / 2, // start angle (top)
29 2 * pi * progress, // sweep angle
30 false,
31 progressPaint,
32 );
33
34 // Center text
35 final textPainter = TextPainter(
36 text: TextSpan(
37 text: '${(progress * 100).toInt()}%',
38 style: TextStyle(color: color, fontSize: 24, fontWeight: FontWeight.bold),
39 ),
40 textDirection: TextDirection.ltr,
41 );
42 textPainter.layout();
43 textPainter.paint(canvas, center - Offset(textPainter.width / 2, textPainter.height / 2));
44 }
45
46 @override
47 bool shouldRepaint(CircleProgressPainter old) => old.progress != progress;
48}
49
50// Usage:
51CustomPaint(
52 size: const Size(150, 150),
53 painter: CircleProgressPainter(progress: 0.75, color: Colors.blue),
54)

shouldRepaint()

💡 shouldRepaint()

Always implement shouldRepaint() correctly! Return true only when the painter's parameters change. This prevents unnecessary repaints and improves performance.

Painter Performance Strategy

CustomPainter work runs frequently, so small inefficiencies become visible quickly:

  • Keep paint logic purely rendering-focused with no heavy computation.
  • Precompute geometry outside paint when input values are stable.
  • Limit repaint triggers by comparing painter fields carefully.
  • Wrap expensive canvas regions with RepaintBoundary when useful.

Efficient painters unlock advanced visuals without sacrificing smoothness.

Custom Painter Checklist

  • Painter inputs are immutable and clearly scoped.
  • shouldRepaint returns true only when visual output truly changes.
  • Text and path calculations are not recomputed unnecessarily per frame.
  • Canvas output is validated on multiple device pixel densities.
  • Performance profiling confirms stable frame times during animation.

This Lesson In Simple Words

Draw custom shapes, charts, and graphics on a canvas. This lesson adds one more building block for creating stable and user-friendly Flutter apps.

Your level focus

Operate with production and interview-level clarity.

One practical habit

After reading, rewrite the concept in your own words and apply it in a tiny runnable sample.

Deep Understanding Guide

Why this lesson matters

Each lesson becomes useful when you connect concept, implementation, and real-user outcome together.

Study flow for better retention

  1. Tie each concept to scale, failure handling, and delivery strategy.
  2. Use a simple cycle: understand, implement, test, and explain.
  3. If you can defend trade-offs under constraints, your understanding is strong.

Common Mistakes To Avoid

  • Moving forward without checking whether the current concept is truly clear.
  • Copying code exactly without experimenting with small changes.
  • Skipping edge cases and only testing happy-path behavior.
  • Assuming one pattern works for every scenario without trade-off analysis.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build one tiny example from memory after finishing this lesson.
  • Write one paragraph about where this concept fits in a real app.
  • Create one failure scenario and verify your app handles it safely.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What method do you override to draw on the canvas?".

Quick Glossary

  • widget: A reusable UI building block in Flutter.
  • build: The method that describes UI for the current state.
  • animation: Controlled change in UI properties over time.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Connect this lesson to separation of concerns so your codebase stays maintainable as it grows.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "CustomPainter & Canvas" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Moving forward without checking whether the current concept is truly clear.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What method do you override to draw on the canvas?

The paint() method receives a Canvas and the Size of the paint area, where you do all drawing.

What does shouldRepaint() control?

shouldRepaint() tells Flutter if the painter needs to redraw. Return true when data changes.

Which Paint style draws the outline of a shape?

PaintingStyle.stroke draws just the outline. PaintingStyle.fill fills the entire shape.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue