What is CustomPaint?
- Flutter course
- Advanced
- Lesson 51/69
- 4 min
Draw custom shapes with the CustomPaint widget.
What is CustomPaint?
CustomPaint is the Flutter widget used for free-form drawing that standard widgets cannot do. It takes a painter and an optional size; the actual drawing is delegated to the painter object. If you pass a child, the drawing appears behind it.
CustomPaint(
size: Size(100, 100),
painter: MyPainter(),
)The painted area covers the size given by size.
child and size relationship
If you give CustomPaint a child, the drawing stays behind it and size is ignored; the child's size is used. Without a child, size sets the drawing size.
CustomPaint(
painter: MyPainter(),
child: Container(width: 80, height: 80),
)Practice Create a CustomPaint widget
The MyPainter class is provided. In main, create a CustomPaint of size 100x100 using MyPainter() and print its runtimeType.
Starter code
import 'package:flutter/material.dart';
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
void main() {
// 100x100 CustomPaint oluştur ve tipini yazdır
}Sample solution
import 'package:flutter/material.dart';
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
void main() {
final widget = CustomPaint(
size: Size(100, 100),
painter: MyPainter(),
);
print(widget.runtimeType);
}Expected output
CustomPaint
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Who does the actual drawing in the CustomPaint widget?
- The size parameter
- The BuildContext
- The object in the painter parameter Correct answer
- The widget in the child parameter
Explanation: The drawing is done by the CustomPainter object passed to painter; child just sits on top, and size sets the area.
2 Add the painter parameter
CustomPaint(
size: Size(50, 50),
____: MyPainter(),
)
CustomPaint(
size: Size(50, 50),
painter: MyPainter(),
)
Explanation: The object that draws is given via the painter parameter; child is the widget on top, and size is the area.
3 CustomPaint parts
| Term | Meaning |
|---|---|
CustomPaint |
Free-form drawing widget |
painter |
Object that draws |
size |
Drawing area size |
child |
Widget on top of the drawing |