Sub topic 1
Layout starts with the widget tree
In Flutter, every layout is a tree of widgets. This chapter explains how that tree is built and how to read it. The next chapters build Row, Column, and Stack on top of it.
Prerequisites
This chapter assumes you can do the following:
- Read basic Dart: classes, named parameters, and lists.
- Write a
StatelessWidgetwith abuildmethod. - Run a Flutter app on an emulator, a device, or Chrome.
You do not need to know about constraints yet. They are the topic of the next chapter.
What a widget is
A widget is an immutable description of part of the user interface. It says what should appear, not how to draw it. Text('Hi') holds a string and some style fields. It does not hold pixels.
Widgets are cheap to create. Flutter expects you to create new ones on every rebuild and throw the old ones away. A widget that is a const instance is created once at compile time and shared.
Widgets fall into two broad groups:
| Kind | Purpose | Examples |
|---|---|---|
| Composite widgets | Build other widgets from smaller ones | `StatelessWidget`, `Scaffold`, `Container` |
| Layout and paint widgets | Control size, position, or drawing | `Row`, `Column`, `Stack`, `Padding`, `SizedBox` |
Many things you may not think of as layout are widgets too. Padding is a widget (Padding). So are alignment (Align, Center) and a fixed gap (SizedBox). Layout is done by composing widgets, not by setting style properties on one element.
Parents and children
Widgets nest. A widget that contains another is its parent, and the contained widget is its child. Together they form the widget tree.
Two shapes of parent appear all the time:
- A single-child widget takes one
child.Padding,Center,SizedBox, andExpandedare examples. - A multi-child widget takes a list called
children.Row,Column, andStackare examples.
Mixing them up is a compile error. Padding(children: [...]) fails because Padding has no children parameter. If you want several widgets inside a Padding, give the Padding one child, and make that child a Column or Row.
Padding(
padding: const EdgeInsets.all(8),
child: Column(
children: const [
Text('One'),
Text('Two'),
],
),
)A complete example
This app runs as written. Save it as lib/main.dart in a new Flutter project.
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: ProfileCard());
}
}
class ProfileCard extends StatelessWidget {
const ProfileCard({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Profile')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: const [
Icon(Icons.person),
SizedBox(width: 8),
Text('Ada Lovelace'),
],
),
const SizedBox(height: 8),
const Text('Mathematician'),
],
),
),
);
}
}You can read the nesting straight from the code. Indentation in a well-formatted Flutter file mirrors the tree. The diagram below shows the same structure, simplified. MaterialApp creates several internal widgets that are left out here.
The tree answers most layout questions before you run anything:
- The
Rowand theText('Mathematician')are siblings. They share theColumnas their parent. - The
Iconand the name are siblings inside theRow. - The
Paddingaffects everything below it, because everything below it is inside its child subtree.
Why the tree decides layout
A widget never positions itself. Its parent decides where it goes, and the parent's own parent limits how big it may be. Flutter walks the tree from the root, and each parent passes information down to its children. That is why the same Text looks different inside a Row than inside a Center. The widget is the same, but its position in the tree is different.
The rule has a short name: constraints go down, sizes go up. The next chapter covers it in full. For now, remember that the parent is the unit of control. To change how a widget is laid out, you usually change its parent, not the widget.
Three trees, one pipeline
Flutter keeps three parallel structures. You write the first one and Flutter manages the other two.
| Tree | Made of | Lifetime | Job |
|---|---|---|---|
| Widget tree | `Widget` objects | Short. Rebuilt often | Describes the configuration |
| Element tree | `Element` objects | Long. Reused across rebuilds | Holds the position in the tree and links widgets to render objects |
| Render tree | `RenderObject` objects | Long. Updated in place | Performs layout, painting, and hit testing |
When build runs again, Flutter compares each new widget with the old widget at the same position. If the type and key match, the element is kept and updated with the new configuration. If they do not match, the old element and its subtree are discarded and a new one is created. This is why rebuilding is cheap even for big screens. The expensive objects survive.
Render objects are where layout actually happens. A Row widget configures a RenderFlex. You will see that name in the overflow errors covered later in this tutorial. It is the render object behind both Row and Column.
Composite widgets hide extra widgets
Some widgets that look simple build a small subtree of their own. Container is the common example. This code:
Container(
padding: const EdgeInsets.all(8),
color: Colors.amber,
child: const Text('Hi'),
)builds Padding, ColoredBox, and others internally, depending on the arguments you set. This has two consequences.
First, a Container with no arguments and no child behaves differently from one with a width argument. Different arguments produce different inner widgets, so the layout behavior changes.
Second, using the small widget directly is often clearer. If you only need a gap, use SizedBox. If you only need padding, use Padding. If you only need a color, use ColoredBox. The tree stays smaller and the intent is obvious.
Extracting widgets does not change layout
Moving part of a build method into its own widget class adds a node to the tree, but that node has no layout effect. A StatelessWidget passes the constraints it receives straight to the widget returned from its build method.
class NameRow extends StatelessWidget {
const NameRow({super.key, required this.name});
final String name;
@override
Widget build(BuildContext context) {
return Row(
children: [
const Icon(Icons.person),
const SizedBox(width: 8),
Text(name),
],
);
}
}Replacing the inline Row in ProfileCard with NameRow(name: 'Ada Lovelace') gives the same result on screen. Prefer extracting widget classes over helper methods such as Widget _buildRow(). A class gets its own element, so Flutter can skip rebuilding it when its inputs have not changed, especially when the constructor is const.
Common errors at this level
- Putting a
childrenlist on a single-child widget, or achildon a multi-child one. The compiler reports the missing named parameter. - Forgetting a trailing comma on a long widget call. Code still runs, but the formatter then collapses the nesting, which makes the tree hard to read.
- Nesting too deeply in one
buildmethod. Split subtrees into widget classes when the indentation becomes hard to follow. - Calling
ScaffoldorMaterialApppieces out of order. Widgets such asScaffoldneed aMaterialAppabove them in the tree to find a theme and a text direction. - Building the tree in the wrong place. If a widget needs data from an ancestor, it must be a descendant of that ancestor.
Reading a tree in practice
When you meet a screen you did not write, read it in this order:
- Find the root of the
buildmethod and note its type. - For each widget, decide whether it takes
childorchildren. - Mark the widgets that only shape layout, such as
Padding,SizedBox,Expanded, andAlign. - Mark the leaves, which are the widgets that draw something, such as
TextandIcon.
After this you can sketch the tree on paper. That sketch is the best starting point for reasoning about constraints in the next chapter.
Exercise
In the ProfileCard example, you want 16 logical pixels of space between the Row and the "Mathematician" text, and you also want to move the whole Column 24 pixels away from the left edge of the screen. Which existing widgets would you change or add, and where do they sit in the tree?
Show answer
Change the existing SizedBox between the Row and the Text from height 8 to height 16. It is a child of the Column, between its two other children. For the left edge, change the Padding that wraps the Column. For example, use EdgeInsets.only(left: 24, top: 16, right: 16, bottom: 16). The Padding is the Column's parent, so it affects the whole Column subtree. Neither change needs a new widget.
Exercise
Why does Padding(children: [Text('A'), Text('B')]) fail to compile, and how do you fix it while keeping both texts stacked vertically?
Show answer
Padding is a single-child widget, so it has a child parameter and no children parameter. Give it one child that is a multi-child widget: Padding(padding: ..., child: Column(children: [Text('A'), Text('B')])).