Flutter Triangle Shape
A triangle is three points and a close(). Choose the direction and optional corner rounding below, and the code updates to match. Use the ClipPath version to cut an image or widget into a triangle, and the ShapeBorder version for a Container, Card or Material.
import 'package:flutter/material.dart';
// A up-pointing triangle that fills the rect.
Path trianglePath(Rect r) {
return Path()
..moveTo(r.center.dx, r.top)
..lineTo(r.right, r.bottom)
..lineTo(r.left, r.bottom)
..close();
}
class TriangleClipper extends CustomClipper<Path> {
const TriangleClipper();
@override
Path getClip(Size size) => trianglePath(Offset.zero & size);
// The shape never changes, so there is nothing to reclip.
@override
bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false;
}
// Usage:
// ClipPath(
// clipper: const TriangleClipper(),
// child: Image.asset('assets/avatar.jpg', width: 160, height: 160, fit: BoxFit.cover),
// )When to use ClipPath vs ShapeBorder for this shape
Use ClipPath with a CustomClipper when you have content to cut: a photo, a gradient container, a video thumbnail. It changes what is painted and what can be tapped, but it also clips anything drawn outside the path, including BoxShadow.
Use a ShapeBorder with ShapeDecoration, Card or Material when the triangle is the widget's own surface. Shadows, ink ripples and elevation then follow the triangle.
Common mistakes
- Adding a
BoxShadowto a clipped widget and seeing nothing. The clip also cuts the shadow. Use theShapeBorderversion, or see the ClipPath shadow guide linked below. - Returning
truefromshouldReclipfor a fixed shape. That forces a reclip on every rebuild. Returnfalse, or compare the fields that change. - Expecting rounded corners from
ClipRRect. It only rounds rectangles. Use the rounding slider here, which cuts each corner and joins it with a quadratic curve. - Using a non-square size and expecting an equilateral triangle. The code fills the rect it is given, so the triangle stretches with the widget. Give it an aspect ratio that suits.
FAQ
How do I make a triangle in Flutter?
Create a Path with moveTo to the first point, lineTo the other two, and close(). Then use it in a CustomClipper<Path> for ClipPath, in a CustomPainter, or inside a ShapeBorder. The code above does all of that for the direction you pick.
How do I round the corners of a triangle?
Cut each corner back along its two edges and join the cut points with quadraticBezierTo, using the original corner as the control point. The rounding slider generates exactly that, and the helper function is included in the code.
Can I tap only the triangle and not its bounding box?
ClipPath also clips hit testing, so taps outside the triangle do not reach the child. For a CustomPaint, override hitTest on the painter. The hit-testing article linked below explains both.