Sub topic 1
How a Flutter App Is a Tree of Widgets
Prerequisites
This chapter assumes you can do the following:
- Read and write basic Dart: classes, constructors, and named parameters.
- Run a Flutter app on an emulator, a device, or in a browser.
- Recognize a
StatelessWidgetand itsbuildmethod.
You don't need to know MaterialApp, Scaffold, or AppBar yet. Later chapters cover each in detail. This chapter explains the model they all fit into.
The working model: everything is a widget
A Flutter screen is described by a widget, an immutable object that holds configuration. A Text widget holds a string and a style. A Padding widget holds an inset. A Scaffold holds a few slots, such as an app bar and a body.
Widgets are cheap descriptions, not the things drawn on screen. Flutter creates and discards them constantly, often on every frame of an animation. Because they are immutable, every field is final, and changing the UI means building a new widget with new values.
Almost everything is a widget, including things that don't look like UI:
| Kind | Examples | What it does |
|---|---|---|
| Visible | `Text`, `Icon`, `Image` | Draws something |
| Layout | `Row`, `Column`, `Center`, `Padding` | Positions its children |
| Structural | `Scaffold`, `AppBar`, `Drawer` | Provides a standard screen layout |
| Inherited data | `Theme`, `MediaQuery`, `Navigator` | Passes data or services to descendants |
| App root | `MaterialApp` | Sets up theme, routes, and several services |
Widgets that carry data, such as Theme and MediaQuery, have no visual output of their own. They exist so that widgets below them can look the data up.
Composition: widgets nested in widgets
You build a UI by putting widgets inside other widgets. A widget that takes one widget is usually called with a child: argument. A widget that takes several uses children:. Some structural widgets have named slots instead, such as appBar: and body: on Scaffold.
This nesting forms a tree. The widget at the top is the root. Each widget can have children, and each widget except the root has exactly one parent.
Here is a small app. Read it from the outside in.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Tree demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
),
home: const HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: const Center(child: AncestorPrinter()),
);
}
}
class AncestorPrinter extends StatelessWidget {
const AncestorPrinter({super.key});
@override
Widget build(BuildContext context) {
final names = <String>[];
context.visitAncestorElements((element) {
names.add(element.widget.runtimeType.toString());
return true;
});
debugPrint(names.join(' <- '));
return Text('Depth: ${names.length}');
}
}runApp takes the root widget, here MyApp. MyApp returns a MaterialApp. MaterialApp builds the HomePage named in its home: argument. HomePage returns a Scaffold, which holds an AppBar and a Center, and so on down to the Text.
The last widget, AncestorPrinter, walks up the tree from its own position and prints each ancestor's type. Run the app in debug mode and look at the console. You will see a long chain that ends at the root, something like Center <- ... <- Scaffold <- ... <- MaterialApp <- .... The exact chain differs between Flutter versions, because MaterialApp and Scaffold insert their own helper widgets such as Theme, Navigator, and Material. That is the point of the experiment. The tree you wrote is smaller than the tree Flutter builds.
What `build` really does
Every widget in the tree is either stateless or stateful, and both kinds describe their subtree through a build method.
- A
StatelessWidgetreturns a subtree that depends only on its constructor arguments and on inherited data. - A
StatefulWidgetpairs with aStateobject that outlives individual widget instances. It can hold mutable data and request a rebuild withsetState.
build returns a widget, and that widget has its own build, until Flutter reaches widgets that draw directly. Text, Center, and Padding are the kind that ends the chain. This is why a single line like Scaffold(...) can expand into dozens of widgets underneath.
A build method should be fast and free of side effects. Flutter may call it many times, at moments you don't control. Don't start network requests or write to storage inside it.
Three trees, one mental model
The widget tree is the one you write, but Flutter keeps three related trees. You rarely touch the other two directly, yet knowing they exist explains several behaviors.
- Widget tree. Immutable configuration objects. Rebuilt often.
- Element tree. One
Elementper widget position, created when a widget is first inserted. Elements are long-lived. When a parent rebuilds, Flutter compares the new widget to the old one at the same position. If the type (and key) match, the element is kept and updated. If not, the element and its subtree are replaced. - Render tree.
RenderObjects that measure, lay out, and paint. They are expensive to create, which is why Flutter reuses them.
This split is why rebuilding is cheap. Creating hundreds of small widget objects costs little. Only the parts that really changed touch the render tree.
It also explains where State lives. A State object is attached to an element, not to a widget. When a parent rebuilds and hands the element a new StatefulWidget of the same type, the old State survives. If the type changes at that position, the state is thrown away.
BuildContext: your position in the tree
Every build method receives a BuildContext. It is a handle to the element at that widget's position, and it lets you ask questions about what is above you.
The most common use is the of pattern:
final colors = Theme.of(context).colorScheme;
final width = MediaQuery.sizeOf(context).width;Theme.of(context) starts at your element and walks up until it finds the nearest Theme widget. It returns that theme's data. Widgets that read data this way are registered as dependents. When the inherited data changes, they rebuild.
The key consequence is that the lookup starts from where the context sits, not from where the widget is written. This causes the most common mistake with the widget tree.
Common error: a context that is above the widget you want
Consider this version of MyApp:
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
// Wrong: this context is ABOVE the MaterialApp created below.
final primary = Theme.of(context).colorScheme.primary;
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
),
home: Scaffold(
body: Center(
child: Text('Primary: $primary'),
),
),
);
}
}The context in MyApp.build belongs to MyApp, whose ancestors do not include the MaterialApp it returns. Theme.of finds no Theme above and falls back to a default theme, so you see the wrong color and no error. The teal theme you configured is below you.
There are two fixes:
- Move the lookup into a widget that sits below
MaterialApp, like a separateHomePage. Its context is inside the theme. - Wrap the code in a
Builderwidget, which gives you a new context at that position.
home: Scaffold(
body: Center(
child: Builder(
builder: (innerContext) {
final primary = Theme.of(innerContext).colorScheme.primary;
return Text('Primary: $primary');
},
),
),
),Splitting into separate widgets is almost always cleaner. Use Builder for short cases. The same rule explains the well-known failure of Scaffold.of(context) when the context comes from the method that creates the Scaffold. Chapter 10 returns to this when it covers ScaffoldMessenger.
Rebuilds and `const`
When a widget calls setState, or inherited data it depends on changes, its element is marked dirty. On the next frame Flutter calls build for that element and for the widgets below it that received new configuration. It does not rebuild the whole app.
Marking a widget const helps with this. A const widget is created once at compile time. When a parent rebuilds and passes the same constant instance, Flutter sees an identical object and skips that subtree.
That is why the example constructors above all use const. Typical places to add it:
- Leaf widgets with fixed content, such as
const Text('Home')andconst Icon(Icons.search). - A whole screen, such as
home: const HomePage().
The analyzer's prefer_const_constructors lint flags places where you can add it. It only works when every argument is a compile-time constant. A Text($name) with a runtime string cannot be const.
Reading the tree while you develop
Flutter DevTools has a Widget Inspector that displays the real tree, including the helper widgets that framework code inserts. Select a widget on the device and its place in the tree is highlighted. This is the quickest way to answer "what is above this widget?" and to understand why a lookup found one Theme instead of another.
In code, debugDumpApp() prints the full widget tree as text to the console. Call it from a button handler or a debug-only hook, never during build. The output is long. Look for your own class names inside it.
How this chapter connects to the rest
The remaining chapters in this tutorial build on three widgets that sit at the top of almost every Material app, nested in this order:
MaterialAppis the root of the app. It supplies the theme, routes, and several services such asNavigator.Scaffoldis the layout of one screen, with slots for the app bar, body, drawer, and floating action button.AppBarfills the top slot of aScaffold.
Each is a widget with a place in the tree, so each chapter is an application of the idea here: configuration flows down from parents to children, and descendants look up shared data through their BuildContext.
Exercises
Exercise
In the example app, AncestorPrinter is built inside Center, which is the body of the Scaffold. Suppose you move AncestorPrinter into the AppBar's title slot. Will a Theme.of(context) lookup inside it still find the teal theme from MaterialApp? Explain why.
Show answer
Yes. The AppBar is a descendant of the Scaffold, and the Scaffold is a descendant of MaterialApp, which inserts a Theme widget above its home screen. Theme.of(context) walks up from the widget's position and finds the nearest Theme, so any widget under MaterialApp sees the teal color scheme, wherever it sits in the screen.
Exercise
A teammate writes Theme.of(context).colorScheme.primary at the top of MyApp.build, above the return MaterialApp(...), and is surprised that the value is not teal. What is wrong, and what are two ways to fix it?
Show answer
The context passed to MyApp.build belongs to MyApp, which is above the MaterialApp and its Theme. The lookup walks up from there and never sees the theme defined below it, so it gets a default theme. Fix 1: move the code into a widget that is built below MaterialApp, such as HomePage, so its context is inside the theme. Fix 2: wrap the code in a Builder widget and use the BuildContext that the builder callback receives.
Exercise
What is the difference between a widget and an element, and which of the two keeps a State object alive when its parent rebuilds?
Show answer
A widget is an immutable description of part of the UI, and Flutter creates new ones on every rebuild. An element is the long-lived object that represents that widget at one position in the tree. The State object is attached to the element. When the parent rebuilds and supplies a new StatefulWidget of the same type (and key) at that position, the element is reused and keeps its State. If the widget type changes, the element is replaced and the state is discarded.