Sub topic 8
Widgets and the Widget Tree
This chapter assumes that you know basic Dart syntax and have a Flutter project that runs. You should also be comfortable with classes, functions, and named parameters.
What is a widget?
A widget is a Dart object that describes part of an app's user interface. Text, buttons, rows, screens, padding, and themes are all represented by widgets.
Flutter builds interfaces by composing small widgets into larger widgets. This creates a widget tree: a hierarchy where each widget can have a parent and one or more children.
For example, a screen might have this structure:
runApp places the root widget into Flutter's rendering system:
void main() {
runApp(const MyApp());
}MyApp becomes the top-level widget. Its build method returns another widget, which returns more widgets, and so on until the complete tree describes the screen.
Composing widgets
The following complete example creates a small widget tree:
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: 'Widget Tree Demo',
home: Scaffold(
appBar: AppBar(
title: const Text('Welcome'),
),
body: const Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Hello, Flutter'),
SizedBox(height: 12),
Text('Widgets are composed into trees.'),
],
),
),
),
);
}
}The MaterialApp provides application-level behavior, such as Material Design defaults and navigation. Its home property contains a Scaffold. The Scaffold supplies a common screen layout with an app bar and body.
The Center has one child. The Column has several children, so it places its children vertically. The SizedBox adds fixed space between the two Text widgets.
A widget that accepts one widget uses a child property. A widget that accepts several widgets uses a children property. These properties make the parent-child relationships visible in the code.
How Flutter uses the tree
Widgets are immutable descriptions. Flutter can recreate them when input changes instead of asking you to manually edit screen objects. Flutter compares the new widget tree with the previous one and updates the underlying objects that display pixels and handle input.
BuildContext identifies a widget's location in the tree. It lets a widget find information provided by its ancestors, such as the current theme:
Text(
'Themed text',
style: Theme.of(context).textTheme.headlineSmall,
)The context passed to build belongs to that widget's position. It is therefore important to use it from the correct part of the tree.
Exercise
Exercise
In the example, which widget is the parent of the two Text widgets, and why does the SizedBox appear between them?
Show answer
The Column is their parent because its children list contains them. The SizedBox appears between them because it is the second child and contributes vertical space.