Sub topic 2
Composing widgets into a tree
Prerequisites
This chapter assumes you can read Dart classes, constructors, and named parameters, and that you can run a Flutter app on an emulator, device, or browser. You don't need to know StatefulWidget yet. The examples use StatelessWidget only as a container for a build method, which later chapters cover in detail.
The tree is the UI
Flutter does not build a screen from one large layout file. You describe each piece of UI as a widget, and each widget can hold other widgets. A Padding holds a Column, the Column holds several Text widgets, and so on. The nesting produces a tree with these parts:
- The root is the widget passed to
runApp. - Each node has one parent, except the root.
- Each node has zero, one, or many children, depending on its type.
- Leaves have no children.
TextandIconare leaves.
A parent controls its children. It decides which widgets are its children, and it passes them the layout constraints they must obey. A child cannot move itself on screen. The tree therefore expresses both what is shown and how the layout is negotiated.
Three shapes of parent widget
Widgets accept children in three ways. Recognizing the shape tells you which parameter to use.
| Shape | Parameter | Examples |
|---|---|---|
| No child | none | `Text`, `Icon`, `SizedBox` without a child |
| Single child | `child` | `Center`, `Padding`, `Card`, `SizedBox`, `Container` |
| Multiple children | `children` (a `List<Widget>`) | `Column`, `Row`, `Stack`, `ListView` |
Some widgets have named slots instead. Scaffold accepts appBar, body, and floatingActionButton. Each slot takes one widget, and Scaffold decides where to place it.
Many widgets exist only to modify layout or appearance. Padding draws nothing. It adds space around its child. Center, Align, and Opacity work the same way. Flutter prefers many small widgets that each do one job over a few widgets with many options.
A worked example: a profile card
The following app builds a small card. It is complete and runnable.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: ProfileCard(
name: 'Ada Lovelace',
role: 'Mathematician',
),
),
),
);
}
}
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(
mainAxisSize: MainAxisSize.min,
children: [
const CircleAvatar(child: Icon(Icons.person)),
const SizedBox(width: 16),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(name, style: Theme.of(context).textTheme.titleLarge),
Text(role),
],
),
],
),
),
);
}
}Read the nesting from the outside in. MaterialApp provides theming and navigation. Scaffold provides the page structure. Center places ProfileCard in the middle of the body. Inside the card, Padding wraps a Row. The Row lays out an avatar, a fixed gap made with SizedBox, and a Column of two Text widgets.
ProfileCard is itself a widget. From the outside it looks like a single node, and the caller does not need to know about the row, column, and padding inside it. This is how you hide detail in a Flutter tree.
What the tree looks like
The diagram shows the widgets from Scaffold downward. Each arrow means "has as a child".
Two details are worth noting. First, the order of a multi-child list matters, because Row places its children left to right in list order. Second, the tree is a description. When data changes, Flutter calls build again and creates a new description. The next chapters explain how Flutter compares old and new descriptions cheaply.
Layout flows through the tree
Composition also determines layout. Flutter follows a short rule: constraints go down, sizes go up, and the parent sets position.
- A parent gives each child a range of allowed widths and heights (the constraints).
- The child picks a size inside that range and reports it back.
- The parent places the child.
This explains why Row needed mainAxisSize: MainAxisSize.min in the example. Center passes loose constraints, which allow any size up to the screen. By default a Row takes the largest width it is allowed, so the card would stretch across the screen. Setting min tells the Row to shrink to its children.
Composition over inheritance
When a build method grows deep, resist the urge to subclass a widget such as Card to change it. Flutter favors composition: build a new widget that contains the existing one. Extracting a piece of the tree into its own class gives you three benefits:
- The class gets a name that says what it is, such as
UserAvatar. - You can reuse it elsewhere.
- You can mark it
const, which later chapters show lets Flutter skip work.
Here the avatar and name block from the example are extracted.
import 'package:flutter/material.dart';
class UserAvatar extends StatelessWidget {
const UserAvatar({super.key});
@override
Widget build(BuildContext context) {
return const CircleAvatar(child: Icon(Icons.person));
}
}
class NameBlock extends StatelessWidget {
const NameBlock({super.key, required this.name, required this.role});
final String name;
final String role;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(name, style: Theme.of(context).textTheme.titleLarge),
Text(role),
],
);
}
}ProfileCard then reads as Row(children: [UserAvatar(), SizedBox(width: 16), NameBlock(name: name, role: role)]). The tree has the same shape and the code is easier to read.
A helper method such as Widget _buildName() also shortens a build method. It does not create a node of its own in the tree, so Flutter cannot treat it as a separate unit. A widget class is usually the better choice, and the performance chapter explains why.
Common errors
Most tree errors come from a mismatch between a child's needs and a parent's constraints.
Unbounded height. A Column gives its children unlimited height. A scrolling widget such as ListView wants a finite height, and the pairing throws a "Vertical viewport was given unbounded height" error. Wrap the ListView in Expanded, or give it a fixed size with SizedBox.
import 'package:flutter/material.dart';
class Inbox extends StatelessWidget {
const Inbox({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: [
const Text('Messages'),
Expanded(
child: ListView(
children: const [
ListTile(title: Text('First')),
ListTile(title: Text('Second')),
],
),
),
],
);
}
}Misplaced Expanded. Expanded and Flexible only work as direct children of Row, Column, or Flex. If another widget such as Padding sits between them, Flutter reports "Incorrect use of ParentDataWidget". Move Expanded so it is the direct child.
Overflow. A Row of fixed-size children wider than the screen shows a yellow and black overflow stripe in debug mode. Wrap long text in Expanded or Flexible, or use a scrolling parent.
Unreadable nesting. Ten levels of indentation hide the shape of the UI. Extract subtrees into named widgets before the build method passes about 40 lines.
Summary of rules
- Every widget has one parent. A parent holds its children through
child,children, or named slots. - Many widgets exist only to adjust layout, such as
Padding,Center, andSizedBox. - Constraints flow down the tree and sizes flow up.
- Extract a subtree into a new widget class instead of subclassing or writing long build methods.
Exercise
A screen has Column(children: [Text('Title'), ListView(children: items)]). It throws "Vertical viewport was given unbounded height". Why does this happen, and how do you fix it?
Show answer
A Column passes unbounded height to its children, but a ListView needs a bounded height to know its scrollable viewport. Wrap the ListView in Expanded so the Column gives it the remaining space: Column(children: [Text('Title'), Expanded(child: ListView(children: items))]). A SizedBox with a fixed height also works.
Exercise
In the ProfileCard example, what happens to the card's width if you remove mainAxisSize: MainAxisSize.min from the Row, and why?
Show answer
The card stretches to the full available width. Center gives the card loose constraints that allow any width up to the screen width, and a Row defaults to MainAxisSize.max, so it takes the largest width allowed. Padding and Card then grow with it.