Sub topic 1
Everything is a widget
Prerequisites
This chapter assumes you know:
- Dart classes, constructors,
finalfields, and named parameters. - Dart null safety basics, including
?andrequired. - A working Flutter installation and the ability to run a simple app.
Everything is a widget
A widget is a Dart object that describes one piece of the user interface. Text, buttons, padding, alignment, and whole screens are all widgets. Widgets do not draw pixels themselves. They describe what should appear, and Flutter turns that description into rendered output.
Widgets usually fall into two groups. Some only hold configuration and never change on their own. Others hold data that changes over time. This chapter covers the first group, the StatelessWidget, and the rules that every widget follows.
Composing widgets into a tree
Widgets nest inside other widgets. A screen is one widget that contains others, and each of those contains more. The result is a tree.
Each widget lists its children in its constructor. A parent controls the layout and position of its children.
The build method and BuildContext
A StatelessWidget must implement build. Flutter calls build when it needs the widget's UI, and build returns a new widget tree. The BuildContext argument tells the widget where it sits in the tree. You use it to look up inherited data such as the theme.
import 'package:flutter/material.dart';
class Greeting extends StatelessWidget {
const Greeting({super.key, required this.name});
final String name;
@override
Widget build(BuildContext context) {
return Text('Hello, $name');
}
}The fields are final, so build returns the same output for the same input. Flutter may call build many times, so keep it free of side effects.
Immutable widgets and const constructors
A widget is immutable. Its fields cannot change after construction. To show new data, Flutter builds a new widget instance and compares it with the old one.
A const constructor lets Flutter reuse an identical instance instead of rebuilding it. Add const when all arguments are compile-time constants.
Column(
children: const [
Greeting(name: 'Ada'),
Greeting(name: 'Grace'),
],
)Exercise
Exercise
Why does Greeting declare its name field as final, and what would break if the field were changed to a non-final String?
Show answer
A StatelessWidget must be immutable so that Flutter can compare an old instance with a new one and reuse the old one when nothing changed. If name were mutable, the widget could change after Flutter had already built it, and the UI would no longer match the widget's configuration.