Sub topic 10
Filling shapes with gradients
A gradient in Flutter is a recipe for colors, not something you draw directly. To paint with it, you turn it into a shader (a color source for each pixel) and attach it to a Paint. This chapter covers the three gradient classes, the rectangle argument that causes most gradient bugs, and the rules for stroked shapes, text, and repainting.
It assumes you can write a CustomPainter with paint and shouldRepaint, and that you know Paint styles and Offset.zero & size.
From Gradient to Shader to Paint
LinearGradient, RadialGradient, and SweepGradient are plain immutable objects from the painting library. They hold colors and geometry as fractions, not pixels. Calling createShader(Rect) resolves those fractions against a rectangle and returns a Shader. You assign that shader to Paint.shader, and the canvas uses it instead of Paint.color.
When shader is set, Paint.color is ignored for the fill. The paint's style, strokeWidth, and blendMode still apply.
A linear gradient on a card
LinearGradient runs along a line from begin to end. Both are Alignment values, which are fractions of the rectangle you pass in. Alignment.topLeft is (-1, -1) and Alignment.bottomRight is (1, 1).
import 'package:flutter/material.dart';
void main() => runApp(
const MaterialApp(
home: Scaffold(body: Center(child: GradientDemo())),
),
);
class GradientDemo extends StatelessWidget {
const GradientDemo({super.key});
@override
Widget build(BuildContext context) {
return CustomPaint(
size: const Size(240, 120),
painter: LinearCardPainter(),
);
}
}
class LinearCardPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final rect = Offset.zero & size;
final paint = Paint()
..shader = const LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xFF7C4DFF), Color(0xFFFF9800), Color(0xFFFFEB3B)],
stops: [0.0, 0.6, 1.0],
).createShader(rect);
canvas.drawRRect(
RRect.fromRectAndRadius(rect, const Radius.circular(16)),
paint,
);
}
@override
bool shouldRepaint(covariant LinearCardPainter oldDelegate) => false;
}Colors, stops, and tile mode
colorsneeds at least two entries.stopsis optional. If you omit it, colors are spaced evenly. If you provide it, it must have the same length ascolors, and the values must be non-decreasing and between 0.0 and 1.0.- Two equal stops create a hard edge instead of a blend. For example,
[Colors.red, Colors.red, Colors.blue, Colors.blue]with stops[0, 0.5, 0.5, 1]gives a sharp split. tileModecontrols what happens outside the gradient's span.TileMode.clamp(the default) extends the end colors.repeatedrestarts the gradient.mirroralternates direction.decalleaves the area transparent.decalonly works on newer engines, so test it on your target platforms.
A mismatch between colors and stops throws an assertion in debug builds, so you find out quickly.
The rectangle must match the shape
createShader places the gradient in the rectangle you pass. It does not know what shape you will draw, and it does not clip to that rectangle. If the rectangle and the shape disagree, the gradient lands in the wrong place.
The next painter draws a circle off-center. It builds the shader from the circle's own bounds, so the highlight sits on the sphere instead of in the middle of the canvas.
import 'package:flutter/material.dart';
class SpotlightPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final center = Offset(size.width * 0.65, size.height / 2);
final radius = size.shortestSide * 0.4;
final bounds = Rect.fromCircle(center: center, radius: radius);
final paint = Paint()
..shader = const RadialGradient(
center: Alignment(-0.3, -0.3),
radius: 0.9,
colors: [Colors.white, Colors.teal, Color(0xFF004D40)],
stops: [0.0, 0.5, 1.0],
).createShader(bounds);
canvas.drawCircle(center, radius, paint);
}
@override
bool shouldRepaint(covariant SpotlightPainter oldDelegate) => false;
}For RadialGradient, center is an Alignment inside the rectangle. radius is a fraction of the rectangle's shortest side, so 0.5 reaches the edge of an inscribed circle. Use focal and focalRadius if you want a cone-like light source.
If you had passed Offset.zero & size here, the highlight would be computed for the whole canvas. The circle would show only a slice of it, usually a flat-looking color.
The transform gotcha
A shader lives in the canvas coordinate system at the moment you assign it to the paint. The Rect you give createShader is interpreted in that same local space when the shape is drawn. If you call canvas.translate, rotate, or scale after building the shader, the shader moves with the canvas. Build the shader with a rectangle in the same coordinate space you draw in.
Absolute coordinates with ui.Gradient
The dart:ui class ui.Gradient creates shaders directly from pixel coordinates, with no Alignment or Rect step. Use it when you already have exact points, such as a gradient stroke that follows a line.
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
class GradientLinePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final start = Offset(16, size.height / 2);
final end = Offset(size.width - 16, size.height / 2);
final paint = Paint()
..shader = ui.Gradient.linear(
start,
end,
const [Colors.red, Colors.blue],
)
..style = PaintingStyle.stroke
..strokeWidth = 10
..strokeCap = StrokeCap.round;
canvas.drawLine(start, end, paint);
}
@override
bool shouldRepaint(covariant GradientLinePainter oldDelegate) => false;
}The framework gradients are easier to read and support TextDirection and GradientTransform. ui.Gradient is better when the geometry is already in pixels.
Sweep gradients on strokes
SweepGradient rotates colors around a center. Angles are in radians and start at the positive x-axis (3 o'clock), moving clockwise. Flutter's drawArc uses the same convention, so you often need to rotate the gradient to line up with an arc that starts at the top. The transform parameter takes a GradientRotation for this.
import 'dart:math' as math;
import 'package:flutter/material.dart';
class GradientRingPainter extends CustomPainter {
GradientRingPainter({required this.progress});
final double progress; // 0.0 to 1.0
@override
void paint(Canvas canvas, Size size) {
const strokeWidth = 14.0;
final arcRect = (Offset.zero & size).deflate(strokeWidth / 2);
final paint = Paint()
..shader = const SweepGradient(
colors: [Colors.cyan, Colors.blue, Colors.purple],
transform: GradientRotation(-math.pi / 2),
).createShader(arcRect)
..style = PaintingStyle.stroke
..strokeWidth = strokeWidth
..strokeCap = StrokeCap.round;
canvas.drawArc(arcRect, -math.pi / 2, 2 * math.pi * progress, false, paint);
}
@override
bool shouldRepaint(covariant GradientRingPainter oldDelegate) =>
oldDelegate.progress != progress;
}The gradient spans the full circle, and the arc reveals only a part of it. At 50 percent progress you see cyan to blue, and purple appears only as the ring nears completion. For a gradient that always fits the visible arc, set endAngle to 2 * math.pi * progress. In that case the shader depends on progress, which shouldRepaint already compares.
The first and last colors of a full sweep meet at the seam. If they differ, you see a hard line there. Repeat the first color at the end of the list to hide it.
Gradients on text
TextPainter draws with a TextStyle, and a style can carry a foreground paint. Give that paint a shader, and the glyphs take the gradient. The rectangle should match the laid-out text size.
import 'package:flutter/material.dart';
void paintGradientText(Canvas canvas, Offset offset) {
const text = 'Gradient';
final measure = TextPainter(
text: const TextSpan(
text: text,
style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
),
textDirection: TextDirection.ltr,
)..layout();
final bounds = offset & measure.size;
final painter = TextPainter(
text: TextSpan(
text: text,
style: TextStyle(
fontSize: 40,
fontWeight: FontWeight.bold,
foreground: Paint()
..shader = const LinearGradient(
colors: [Colors.pink, Colors.amber],
).createShader(bounds),
),
),
textDirection: TextDirection.ltr,
)..layout();
painter.paint(canvas, offset);
}TextStyle allows either color or foreground, not both. Setting both throws an assertion.
Cost and caching
Creating a shader is cheap but not free, and paint can run every frame during an animation. Two habits keep things light:
- Build a shader only from values that change. If the size is the same, a stored shader is still valid.
- Keep gradient objects
constwhere possible. This avoids allocating them again on each paint.
A common pattern is caching the shader for the last Size, rebuilding only when the size differs. Measure before adding this complexity. For a handful of gradients, creating them inside paint is fine.
Also remember shouldRepaint. A gradient whose colors depend on a field must be listed in the comparison, or the old colors stay on screen after the field changes.
Common errors
| Symptom | Likely cause |
|---|---|
| Shape shows one flat color | `createShader` used a much larger rectangle than the shape, such as the whole canvas |
| Gradient is shifted after `translate` | Shader rectangle built in a different coordinate space than the draw call |
| Assertion about stops | `stops.length` differs from `colors.length`, or values are out of order |
| Visible seam on a sweep ring | First and last colors differ |
| Colors do not update | A changed color field is missing from `shouldRepaint` |
| Assertion on `TextStyle` | Both `color` and `foreground` were set |
Exercise
You draw a circle at Offset(300, 100) with radius 40 on a 400 by 200 canvas. You paint it with a RadialGradient from createShader(Offset.zero & size). The circle looks almost entirely one color. Why does this happen, and how do you fix it?
Show answer
The shader is resolved against the whole canvas, so the gradient's center is near (200, 100) and its radius is a fraction of 200. The small circle at x = 300 only covers a narrow slice of the gradient, so it looks nearly flat. Fix it by building the shader from the circle's own bounds: Rect.fromCircle(center: const Offset(300, 100), radius: 40), and pass that rectangle to createShader.
Exercise
In GradientRingPainter, the ring's last color meets its first color at the top, and a hard line is visible. What change removes the line, and which painter members need no change?
Show answer
Make the gradient's colors end where they begin, for example [Colors.cyan, Colors.blue, Colors.purple, Colors.cyan], so the sweep closes smoothly. shouldRepaint needs no change because it already compares progress, and the gradient colors are constant.