Flutter 3.x+Live previewCopy-paste Dart

Flutter Diagonal Header

A diagonal header is a rectangle whose bottom edge slopes. It needs four points: set the slant (how much lower one corner sits) and which side is lower, then copy the code. The ShapeBorder version also works as the shape of an AppBar or a SliverAppBar.

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

// The bottom edge slopes: the right corner sits [slant] lower than the other.
Path diagonalHeaderPath(Rect r) {
  const slant = 48.0;
  final s = math.min(slant, r.height);
  return Path()
    ..moveTo(r.left, r.top)
    ..lineTo(r.right, r.top)
    ..lineTo(r.right, r.bottom)
    ..lineTo(r.left, r.bottom - s)
    ..close();
}

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

  @override
  Path getClip(Size size) => diagonalHeaderPath(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 DiagonalHeaderClipper(),
//   child: Container(
//     height: 220,
//     decoration: const BoxDecoration(
//       gradient: LinearGradient(colors: [Color(0xFF6366F1), Color(0xFFEC4899)]),
//     ),
//   ),
// )

When to use ClipPath vs ShapeBorder for this shape

Use ClipPath for a hero image or gradient header at the top of a screen.

Use the ShapeBorder when the header is an AppBar, SliverAppBar or Card: pass it as shape and the elevation shadow follows the slope.

Common mistakes

  • Letting content run into the slanted corner. The lower corner covers extra height, so add padding at the bottom of the header's child.
  • A slant taller than the header. The code clamps the slant to the rect height, but a slant close to the height leaves almost nothing on the high side.
  • Clipping a header that has a shadow. ClipPath removes the BoxShadow; use the ShapeBorder version for shadows.
  • Forgetting that the slope scales with width. With a fixed slant in pixels, the angle changes on a wider screen. Use a fraction of the width if you need a constant angle.

FAQ

How do I make a slanted container in Flutter?

Clip it with a path that has four points where one bottom corner is higher than the other. The ClipPath tab above is exactly that: moveTo, three lineTo calls, and close().

Can I use this as an AppBar shape?

Yes. AppBar and SliverAppBar take a shape of type ShapeBorder, so use the ShapeBorder tab and pass shape: const DiagonalHeaderBorder(). The shadow then follows the slope.

How do I slant the other way?

Switch the lower corner between right and left. The code swaps which bottom corner is raised by slant.

Related