Sub topic 8
Widgets and the widget tree
This chapter assumes you have a working Flutter SDK, have run flutter create, and can launch the generated app. It also assumes you know Dart classes, constructors, and named parameters. Here you will learn how Flutter models a screen as a tree of widgets, how runApp starts that tree, and which mistakes beginners make most often.
What a widget is
A widget is an immutable description of part of the user interface. It is not the pixels on screen, and it is not a long-lived object that you mutate. When something changes, Flutter builds new widget objects and compares them to the old ones.
Widgets cover more than visible elements:
- Visible pieces such as
Text,Icon, andImage. - Layout pieces such as
Row,Column,Center,Padding, andSizedBox. - Structural pieces such as
Scaffold,AppBar, andMaterialApp. - Invisible helpers such as
Theme,Navigator, andMediaQuery, which supply data to the widgets below them.
Because widgets are cheap, immutable configuration objects, creating thousands of them per frame is normal. Marking constructors const lets Dart reuse one instance instead of allocating a new one.
Composition: widgets inside widgets
Flutter favors composition over inheritance. You build a complex screen by nesting small widgets. Most widgets accept either a single child or a list of children.
import 'package:flutter/material.dart';
void main() {
runApp(const GreetingApp());
}
class GreetingApp extends StatelessWidget {
const GreetingApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: Padding(
padding: EdgeInsets.all(16),
child: Text('Hello, widget tree'),
),
),
),
);
}
}Reading from the outside in, the nesting is MaterialApp, then Scaffold, then Center, then Padding, then Text. Each widget has exactly one parent, except the root. That parent-child structure is the widget tree.
The widget tree
The widget tree is the hierarchy of widgets that build() methods produce. For the example above, it looks like this:
GreetingApp is a widget you wrote. Its build() returns MaterialApp, which in turn builds more widgets internally. The real tree is therefore deeper than the code you write. MaterialApp inserts widgets for navigation, theming, localization, and text direction, and Scaffold adds its own layout and material widgets.
Widgets, elements, and render objects
Flutter keeps three parallel trees. You only write the first, but the other two explain much of Flutter's behavior.
| Tree | Made of | Lifetime | Role |
|---|---|---|---|
| Widget tree | `Widget` objects | Short. Rebuilt often. | Describes what the UI should look like. |
| Element tree | `Element` objects | Long. Reused across rebuilds. | Holds the position of each widget in the tree and links it to its state. |
| Render tree | `RenderObject` objects | Long. Reused when possible. | Performs layout, painting, and hit testing. |
When a parent rebuilds, Flutter walks the element tree and compares each new widget to the widget the element currently holds. If the new widget has the same runtimeType and the same key, the element is kept and updated with the new configuration. Otherwise the element and its subtree are discarded and rebuilt. This comparison is why rebuilding is cheap and why a State object survives a parent's rebuild.
Starting the tree with runApp
runApp takes a widget and makes it the root of the tree. It also attaches that tree to the screen and forces the root to fill the available space.
import 'package:flutter/widgets.dart';
void main() {
runApp(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Text('No MaterialApp needed'),
),
),
);
}This program uses only the lower-level widgets library. It works, but you must supply Directionality yourself because Text needs to know the reading direction. MaterialApp normally supplies this and much more, which is why almost every app wraps its content in it.
Two details matter in practice:
runAppcan be called again, and the new widget replaces the old root. Normally you call it once frommain.- If you run code before
runAppthat uses platform channels, such as reading a plugin, callWidgetsFlutterBinding.ensureInitialized()first.
BuildContext: your position in the tree
Every build() method receives a BuildContext. It is a handle to the element that represents this widget's location in the tree. You use it to look upward, for example:
import 'package:flutter/material.dart';
class ThemedLabel extends StatelessWidget {
const ThemedLabel({super.key, required this.text});
final String text;
@override
Widget build(BuildContext context) {
final color = Theme.of(context).colorScheme.primary;
final width = MediaQuery.sizeOf(context).width;
return Text(
'$text (screen width: ${width.round()})',
style: TextStyle(color: color),
);
}
}Theme.of(context) walks up the tree from this widget until it finds the nearest Theme. If you use the wrong context, you can look up from the wrong place. A frequent error looks like this:
import 'package:flutter/material.dart';
class BrokenPage extends StatelessWidget {
const BrokenPage({super.key});
@override
Widget build(BuildContext context) {
// This context belongs to BrokenPage, which is ABOVE the Scaffold.
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Hi')),
);
},
child: const Text('Show'),
),
),
);
}
}This particular case works only when a ScaffoldMessenger exists above BrokenPage, and MaterialApp provides one. The general rule still holds: a lookup searches ancestors of the context you pass. If the widget you need is created inside the same build() method, wrap the code that needs it in a Builder or move it into its own widget so it gets a context that sits below the provider.
Layout: constraints go down, sizes go up
Flutter's layout rule explains most "why is my widget the wrong size" questions. A parent passes constraints (minimum and maximum width and height) to its child. The child picks a size within those constraints and reports it back. The parent then positions the child.
- A
Centergives its child loose constraints, so the child can be smaller than the screen. - A
Columngives its children unbounded height. Putting a scrollableListViewdirectly inside aColumnfails with an "unbounded height" error unless you wrap the list inExpanded. - A
Rowwhose children are wider than the screen shows the yellow and black overflow stripes in debug mode. Wrap children inExpandedorFlexible, or use a scrollable widget.
import 'package:flutter/material.dart';
class ListInColumn extends StatelessWidget {
const ListInColumn({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
const Text('Header'),
Expanded(
child: ListView(
children: [
for (var i = 1; i <= 30; i++) ListTile(title: Text('Item $i')),
],
),
),
],
),
);
}
}Without Expanded, the ListView asks for infinite height inside a Column that also has unbounded height, and Flutter throws a layout exception.
Keys and widget identity
By default, Flutter matches old and new widgets by position and type. That is fine for most UI. It breaks when widgets that hold state are reordered in a list, because the elements stay in place and the state stays with the position instead of following the item.
A Key tells Flutter which widget is which. Use ValueKey with a stable identifier, such as a database id, for items in a dynamic list. Stateless widgets with no internal state rarely need keys.
Common errors and how to read them
| Symptom | Likely cause | Fix |
|---|---|---|
| "No MediaQuery widget ancestor found" | The widget is above `MaterialApp`, or `runApp` got a bare widget. | Wrap the app in `MaterialApp` or move the code below it. |
| "Vertical viewport was given unbounded height" | A scrollable widget sits inside a `Column` with no height limit. | Wrap it in `Expanded`, or give it a fixed height with `SizedBox`. |
| "A RenderFlex overflowed by N pixels" | Children of a `Row` or `Column` are larger than the space. | Use `Expanded`, `Flexible`, or a scroll view. |
| "Scaffold.of() called with a context that does not contain a Scaffold" | The context passed to the lookup is above the `Scaffold`. | Use `Builder` or extract a widget. |
| Widget state jumps to the wrong list item | Reordered stateful widgets have no keys. | Give each item a `ValueKey`. |
Inspecting the tree
Flutter DevTools includes a Widget Inspector. Open it from your editor while the app runs in debug mode. You can select a widget on the device and see its place in the tree, its properties, and its layout constraints. Use it whenever the tree you imagine differs from the one on screen. The tree also shows the extra widgets that MaterialApp and Scaffold add.
Exercises
Exercise
Why does Flutter rebuild widgets so freely without a large performance cost?
Show answer
Widgets are small, immutable descriptions. Flutter keeps the longer-lived element and render objects and compares each new widget with the old one by type and key. If they match, it updates the existing element instead of recreating the subtree, and only changed render objects are laid out or painted again.
Exercise
A ListView placed directly inside a Column throws an "unbounded height" error. What is the cause, and how do you fix it?
Show answer
The Column gives its children unbounded height, and the ListView tries to be as tall as its content allows, which has no limit. Wrap the ListView in Expanded so it takes the remaining bounded space, or give it a fixed height with SizedBox.
Exercise
In a build() method you create a Scaffold and, in a button handler inside it, call Scaffold.of(context) using the method's own context. Why can this fail, and what are two ways to fix it?
Show answer
The context belongs to the widget whose build() is running, which sits above the Scaffold it just returned. of searches only ancestors, so it does not find that Scaffold. Fix it by wrapping the button in a Builder to get a context below the Scaffold, or by moving the button into its own widget class.