ClipPath: Clip Widgets to Custom Shapes
ClipPath is a stencil for your widgets. It cuts a child widget to a custom-defined shape, hiding anything outside the lines. Use it for complex shapes like waves or stars, but avoid it for simple rectangles or circles—it's expensive.
WHY IT EXISTS Standard widgets offer basic shapes like rectangles and circles. To create unique, brand-specific UIs with custom curves, angles, or other non-standard boundaries, a more flexible clipping mechanism is needed. ClipPath solves this by allowing any widget to be masked by an arbitrary shape.
THE MENTAL MODEL ClipPath is a stencil. It's a widget that wraps a child. You give ClipPath a set of instructions for drawing a shape (a Path) via a CustomClipper. The ClipPath then places this invisible stencil over its child, and only the parts of the child visible through the stencil's cutout are actually painted on the screen. Everything else is clipped away.
HOW IT WORKS ClipPath takes a child widget and a clipper property. The clipper must be an instance of a class that extends CustomClipper<Path>. This custom class has two required methods: getClip(), which must return the Path to clip with, and shouldReclip(), which tells Flutter whether the path needs to be recalculated. When Flutter paints the widget, it calls getClip() to get the shape and then prevents the child from painting anywhere outside that Path.
WHEN TO USE IT Use ClipPath when you need to clip a widget to a complex, non-standard shape that cannot be achieved with simpler widgets. Examples include creating a container with a curved or diagonal edge, making an image appear in the shape of a star or a hexagon, or creating custom background effects with unique boundaries.
WHEN NOT TO USE IT Do not use ClipPath for simple shapes. The documentation explicitly warns that it is an expensive operation. For clipping to a rectangle, use ClipRect. For an oval or circle, use ClipOval. For a rounded rectangle, use ClipRRect. Using ClipPath for these common cases is a performance anti-pattern that can lead to jank, especially during animations.
ONE CANONICAL EXAMPLE A common use case is creating a banner with a diagonal slice. You would wrap an Image or Container widget with ClipPath. The CustomClipper's getClip method would then define a Path that starts at the top-left corner, goes to the top-right, then down to the bottom-right, then to a point partway up the left edge, and finally closes the path, creating a four-sided polygon with one diagonal side.
Read the original → api.flutter.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.