Flutter 3.x+Live previewCopy-paste Dart

Flutter Hexagon Shape & Hexagon Avatar

A regular polygon is a loop over angles. Set the number of sides, a rotation and a corner rounding below: the default is a hexagon, and 5, 7 or 8 sides give a pentagon, heptagon or octagon. Clip an avatar with the ClipPath code, or use the ShapeBorder for cards and buttons.

Flutter ClipPath + CustomClipper Code
import 'dart:math' as math;
import 'package:flutter/material.dart';

// A regular 6-sided polygon inscribed in the largest circle that fits the rect.
Path hexagonPath(Rect r) {
  const sides = 6;
  const rotation = 0 * math.pi / 180; // 0 puts a vertex at the top
  final center = r.center;
  final radius = math.min(r.width, r.height) / 2;
  final points = <Offset>[
    for (var i = 0; i < sides; i++)
      center +
          Offset.fromDirection(
            rotation + 2 * math.pi * i / sides - math.pi / 2,
            radius,
          ),
  ];
  return Path()..addPolygon(points, true);
}

class HexagonClipper extends CustomClipper<Path> {
  const HexagonClipper();

  @override
  Path getClip(Size size) => hexagonPath(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 HexagonClipper(),
//   child: Image.asset('assets/avatar.jpg', width: 160, height: 160, fit: BoxFit.cover),
// )

When to use ClipPath vs ShapeBorder for this shape

Use ClipPath for a hexagon avatar or an image grid: the picture is cut to the polygon.

Use the ShapeBorder for buttons, badges and cards that need a hexagonal surface with a border, shadow and ripple that follow the shape.

Common mistakes

  • Using a non-square widget. The polygon is inscribed in the circle that fits the smaller side, so it is centered and the extra space stays empty. Give an avatar equal width and height.
  • Mixing up pointy-top and flat-top. At rotation 0 a vertex points up. For a flat-top hexagon, rotate by 30 degrees.
  • Putting a BoxShadow on the widget you clip. The shadow is cut away with the rest. Use the ShapeBorder version for shadows.
  • Edge pixels looking rough on photos. ClipPath defaults to Clip.antiAlias, so leave it unless you changed clipBehavior.

FAQ

How do I make a hexagon avatar in Flutter?

Wrap a square Image in ClipPath with a clipper that returns a hexagon path. Copy the ClipPath tab above and replace the placeholder image with your own.

Can I make other polygons with the same code?

Yes. The path is a loop over sides vertices, so changing the constant gives a pentagon, hexagon, heptagon or octagon. The sides slider shows 5 to 8, and the generated function is named after the shape.

How do I round the corners of a hexagon?

Cut each corner back along its edges and join the cuts with a quadratic curve through the original vertex. Raise the rounding slider and the code adds that helper.

Related