Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 73 ยท Material, styling and assets

ClipRRect, ClipPath, ShaderMask and Opacity

Round corners with ClipRRect, cut custom shapes with ClipPath, paint gradients over text with ShaderMask, and fade widgets correctly with Opacity and its cheaper cousins.

Layout decides where a widget goes. Painting effects decide what it looks like once it is there: whether its corners are round, whether a banner has a wavy bottom edge, whether a headline is filled with a gradient, and whether the whole thing is half transparent. Flutter has a family of small wrapper widgets for these jobs, and they share one important property: each can force the engine to draw the child into an offscreen layer, which costs time. Knowing when that happens is the difference between a smooth screen and a janky one (performance and DevTools).

Real vs stand-in. The Dart is real and read-only, because the site cannot run Flutter. The live examples are JavaScript stand-ins for the math: whether a tap lands inside a rounded clip, and how opacity composes over overlapping pixels.

ClipRRect, ClipOval and ClipRect

Clipping trims a child to a shape. Anything outside is neither drawn nor tappable.

DART
ClipRRect(
  borderRadius: BorderRadius.circular(16),
  child: Image.asset('assets/cover.jpg', width: 200, height: 120, fit: BoxFit.cover),
)

ClipOval(child: Image.asset('assets/me.jpg', width: 80, height: 80, fit: BoxFit.cover))

ClipRRect rounds corners, ClipOval makes an ellipse (a circle for a square child) and ClipRect cuts to a rectangle (useful to stop an animated child from drawing outside its box). The clipBehavior parameter picks quality and cost:

clipBehavior Meaning
Clip.none No clipping. Fastest.
Clip.hardEdge Clips without smoothing: fast, edges look jagged on curves.
Clip.antiAlias Smooth edges: the default for ClipRRect. Slight cost.
Clip.antiAliasWithSaveLayer Smooth and correct for overlapping content, but expensive. Rarely needed.

Often you do not need a clip widget at all. An image inside a rounded Card, Container with decoration: BoxDecoration(borderRadius: ...) and clipBehavior: Clip.antiAlias, or CircleAvatar can round the child with less overhead. Prefer them when they fit, and avoid clipping long scrolling lists of large images when a pre-rounded asset would do.

Stand-in: clipping also clips taps

JS Does this tap hit the rounded card?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

ClipPath and CustomClipper

For any other shape, give ClipPath a CustomClipper<Path> that returns the outline. A wavy header bottom is the classic example.

DART
class WaveClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final path = Path()..lineTo(0, size.height - 40);
    path.quadraticBezierTo(
      size.width * 0.25, size.height,
      size.width * 0.5, size.height - 30,
    );
    path.quadraticBezierTo(
      size.width * 0.75, size.height - 60,
      size.width, size.height - 20,
    );
    path
      ..lineTo(size.width, 0)
      ..close();
    return path;
  }

  @override
  bool shouldReclip(WaveClipper oldClipper) => false;   // static shape: never recompute
}

ClipPath(
  clipper: WaveClipper(),
  child: Container(height: 220, color: Colors.indigo),
)

getClip receives the child's size, so the shape scales with the layout. shouldReclip is called when the widget updates: return true only when something that affects the path changed (for example an animated value stored in the clipper). The drawing commands are the same ones CustomPaint uses. Hit testing follows the path too, so a tap on the cut-away corner passes through.

ShaderMask: gradients over anything

ShaderMask paints its child, then covers it with a shader using a blend mode. The most popular use is gradient text:

DART
ShaderMask(
  blendMode: BlendMode.srcIn,
  shaderCallback: (Rect bounds) => const LinearGradient(
    colors: [Colors.orange, Colors.pink],
  ).createShader(bounds),
  child: const Text(
    'Sunset',
    style: TextStyle(fontSize: 48, fontWeight: FontWeight.w800, color: Colors.white),
  ),
)

With BlendMode.srcIn, the shader's color is kept only where the child (the destination) is opaque, so the gradient takes the shape of the letters. The child's own color should be solid, and white is the convention. Another common use is a fade-out edge on a scrolling list: a gradient from opaque to transparent with BlendMode.dstIn fades the child toward transparent. bounds is the child's rectangle, so createShader(bounds) stretches the gradient across it.

Opacity and the cheaper options

Opacity(opacity: 0.5, child: ...) draws the child as a unit into an offscreen layer and then blends the layer at half strength. That means overlapping parts of the child do not show through each other, which is often what you want, but it forces the layer on every frame.

DART
Opacity(opacity: 0.5, child: card)              // simple, one layer
AnimatedOpacity(                                 // fade by itself on change
  opacity: visible ? 1 : 0,
  duration: const Duration(milliseconds: 250),
  child: card,
)
FadeTransition(opacity: _controller, child: card) // you drive an AnimationController
Container(color: Colors.blue.withValues(alpha: 0.5))   // alpha on one colour: no layer

Rules of thumb: for an animation use AnimatedOpacity or FadeTransition (implicit animations), which are optimized to avoid rebuilding the child; for a single colored shape put the alpha into the color; use Opacity for a static group of widgets that must fade as one piece. Opacity with 0 still lays out and paints nothing but keeps the child alive; to remove it from the tree, use Visibility or an if. Older code uses color.withOpacity(0.5); newer Flutter prefers withValues(alpha: 0.5).

JS Opacity on a group vs alpha on each child

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Clipping everything. Every ClipRRect in a list of 100 images adds work. Round once at the container or use pre-sized assets.
  • Opacity in an animation. Use AnimatedOpacity or FadeTransition.
  • shouldReclip returning true always. The path is rebuilt every update.
  • A ShaderMask child that is not solid. The result inherits its transparency and looks washed out.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Clip.hardEdge trade away compared with Clip.antiAlias?

    Hard edges skip smoothing, which is faster but looks jagged on curves.
  2. 2. In ShaderMask with BlendMode.srcIn, where does the gradient show?

    srcIn keeps the shader's color inside the destination's opaque pixels.
  3. 3. What does shouldReclip decide in a CustomClipper?

    Return true only when something that shapes the path has changed.
  4. 4. Which is the best choice to fade a widget in and out when a boolean changes?

    AnimatedOpacity runs the fade for you and avoids rebuilding the child on each frame.

Summary

  • ClipRRect, ClipOval, ClipRect and ClipPath trim drawing and hit testing; pick clipBehavior for the quality and cost you need, and skip the widget when a decoration can round the corners.
  • CustomClipper<Path> defines any shape; return false from shouldReclip for static paths.
  • ShaderMask with srcIn paints gradients through text and icons; dstIn makes fades.
  • Prefer AnimatedOpacity, FadeTransition or a color with alpha over a raw Opacity that changes each frame.

Next: Navigator and Routes