Lesson 4 / 25

The Widget Tree

Composition over inheritance.

Widgets, elements and render objects

In Flutter, buttons, padding, alignment, themes and whole screens are all widgets: lightweight, immutable descriptions of part of the UI. You build interfaces by composing small widgets inside each other, forming the widget tree. The framework keeps a longer-lived element tree that tracks where each widget sits and holds state, and a render tree of RenderObjects that does layout and painting. When something changes, build produces new widgets; Flutter compares them with the previous ones and updates only the elements and render objects that need it. The BuildContext passed to build is a handle to the widget's element and its position in the tree.

Everything is a widget

A Flutter UI is a tree of immutable widget descriptions that the framework turns into elements and render objects.

Three ideas: the widget tree, stateless versus stateful widgets, const and keys.
Figure 2.1 — Widget tree, element tree and render tree.

Composing a card

Small widgets nested into a tree.

class ProfileCard extends StatelessWidget {
  const ProfileCard({super.key, required this.name, required this.role});

  final String name;
  final String role;

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            const CircleAvatar(child: Icon(Icons.person)),
            const SizedBox(width: 12),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(name, style: Theme.of(context).textTheme.titleMedium),
                Text(role),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Blueprints and buildings

Widgets are cheap blueprints you redraw freely; elements are the construction crew that compares the new blueprint with the old one and only rebuilds the rooms that changed.

Quick check: Which tree performs layout and painting in Flutter?

  • The widget tree
  • The render tree of RenderObjects
  • The pubspec tree
  • The navigation stack
Answer

The render tree of RenderObjects — Widgets describe, elements manage, render objects lay out and paint.