Sub topic 14
Painting and the Layer Tree
Assume you know Dart classes and basic Flutter widgets such as Row, Column, Padding, and Text. You should also understand that render objects handle layout and painting.
From Render Objects to Pixels
During layout, each render object chooses a size and position. During painting, it receives a Canvas and draws its visual content. A RenderParagraph draws text, while a RenderDecoratedBox draws backgrounds and borders.
Painting usually follows the render tree from parent to child. A parent paints its background, then its children, so later drawing can appear above earlier drawing. The result is recorded into a display list instead of being sent to the screen immediately.
Flutter groups this recorded drawing into a layer tree. A layer describes how a group of pixels should be displayed. Common layers represent transforms, clips, opacity, platform views, or cached pictures.
Painting and Compositing
Painting answers “what should be drawn?” Compositing answers “how should these drawings be combined?”
For example, Opacity may place its child in an offscreen layer and blend that layer with the rest of the scene. Transform can place a child in a transformed layer. These operations can require extra memory and work because Flutter may need to render content separately before combining it.
A layer can be retained between frames. If only a small part of the application changes, Flutter can reuse unchanged layers rather than repainting the entire scene. However, a retained layer does not mean that its contents are always free to update. A change inside a layer can still mark that layer, or its render objects, as needing paint.
Repaint Boundaries
RepaintBoundary separates repaint work. When a descendant changes, Flutter can repaint that subtree without repainting surrounding content.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: PaintDemo()));
}
class PaintDemo extends StatelessWidget {
const PaintDemo({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child: RepaintBoundary(
child: CustomPaint(
size: Size(160, 160),
painter: DotPainter(),
),
),
),
);
}
}
class DotPainter extends CustomPainter {
const DotPainter();
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()..color = Colors.indigo;
canvas.drawCircle(size.center(Offset.zero), 60, paint);
}
@override
bool shouldRepaint(covariant DotPainter oldDelegate) => false;
}Use boundaries around expensive, frequently changing regions, such as an animation beside a static dashboard. Too many boundaries can also hurt performance because they create more layers and compositing work.
Exercise
Exercise
Why might Flutter use a separate layer for an Opacity widget?
Show answer
It may need to paint the child offscreen first, then blend the resulting pixels with the surrounding scene.