Sub topic 1
Everything is a widget
Prerequisites
This chapter assumes you can do the following:
- Read and write basic Dart: classes, constructors,
finalfields, and named parameters. - Use null safety, including
requiredparameters and nullable types such asString?. - Run a Flutter app on an emulator, a device, or in a browser, and edit code in it.
You don't need any knowledge of state management. This chapter covers what a widget is. Later chapters cover how widgets change over time.
What a widget is
A widget is an immutable description of part of the user interface. It says what should be on screen for a given configuration. It doesn't hold pixels, and it doesn't draw anything itself.
In Flutter, almost everything you write in the UI layer is a widget:
- Visible things:
Text,Icon,Image,ElevatedButton. - Layout:
Row,Column,Stack,Center,Padding,SizedBox. - Styling and theming:
Theme,DecoratedBox,Opacity. - Behavior:
GestureDetector,Scrollable,Navigator. - Your own screens and components, which are classes you write that extend a widget class.
Many other frameworks separate these roles. A web page has HTML for structure, CSS for styling, and JavaScript for behavior. Flutter uses one idea for all of them. Even padding is a widget that wraps another widget. This is what "everything is a widget" means in practice.
Descriptions, not drawings
A widget is cheap to create and meant to be thrown away. When the UI needs to change, Flutter doesn't edit the old widget. Your code builds a new set of widget objects, and the framework compares them with the previous set. It then updates only what it needs to on screen.
Think of a widget as a blueprint. The framework reads the blueprint and builds or updates the real objects that lay out and paint the screen. Those objects are covered in a later chapter. For now, remember two facts:
- Widgets are lightweight configuration objects. Creating thousands of them is normal.
- Widgets are immutable. Their fields are
final. To show different data, you create a new widget with different arguments.
The following diagram shows the flow from your code to the screen.
A minimal app
The smallest useful Flutter app shows widgets nested inside each other. Save this as lib/main.dart in a new project and run it.
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: Scaffold(
body: Center(
child: Padding(
padding: EdgeInsets.all(16),
child: Text('Everything is a widget'),
),
),
),
);
}
}Read it from the outside in:
runApptakes one widget and makes it the root of the app.MyAppis a widget you wrote. Itsbuildmethod returns another widget.MaterialAppsets up theming, navigation, and other app-wide services.Scaffoldprovides a basic page structure with a body, and optionally an app bar and other slots.Centerplaces its child in the middle of the available space.Paddingadds space around its child.Textshows the string.
Each widget has one job. You build a screen by combining small widgets, not by configuring one large widget with dozens of options.
Parents and children
Most widgets accept other widgets as arguments. Two names appear often:
childtakes a single widget.Center,Padding, andSizedBoxuse it.childrentakes a list of widgets.Row,Column, andStackuse it.
A widget that contains other widgets is the parent. The widgets it contains are its children. Following the nesting through the whole app gives you the widget tree. The next chapter covers the tree in depth. Here, it is enough to see that nesting in code is the structure of the screen.
Here is a slightly larger example that uses children:
import 'package:flutter/material.dart';
void main() {
runApp(const ProfileApp());
}
class ProfileApp extends StatelessWidget {
const ProfileApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.account_circle, size: 64),
SizedBox(height: 8),
Text('Ada Lovelace'),
],
),
),
),
);
}
}SizedBox(height: 8) is a widget whose only purpose is to take up space. It has no visual output. This is a common way to add gaps in Flutter, and it shows that "widget" covers layout helpers as well as visible elements.
Configuration through constructors
A widget gets its data through constructor arguments, and those values are stored in final fields. The framework doesn't expect a widget's fields to change after construction.
import 'package:flutter/material.dart';
class Badge extends StatelessWidget {
const Badge({super.key, required this.label, this.color = Colors.blue});
final String label;
final Color color;
@override
Widget build(BuildContext context) {
return DecoratedBox(
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(12),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: Text(label, style: const TextStyle(color: Colors.white)),
),
);
}
}Use it as const Badge(label: 'New') or Badge(label: 'Sale', color: Colors.red). The widget has no setters and no internal data. Given the same label and color, it always describes the same UI.
This idea is the foundation for the rest of the tutorial. A widget that depends only on its constructor arguments is a StatelessWidget. Chapter by chapter, you will see what changes when the UI must also remember something that changes over time.
Widgets compose instead of inherit
When you want a new look, you usually don't subclass Text or Container. You write a new widget whose build method combines existing ones. The Badge above does this with DecoratedBox, Padding, and Text.
Composition works well for a few reasons:
- Each piece stays small and testable.
- You can reuse a piece anywhere without inheriting unrelated behavior.
- Changing a piece's look means editing one
buildmethod.
Widgets are not the things on screen
A common source of confusion is thinking that creating a widget puts something on screen. Consider this snippet:
import 'package:flutter/material.dart';
Widget buildLabel() {
final label = Text('Hello');
return label;
}Creating Text('Hello') produces only a description. Nothing is shown until that widget is returned from a build method (or passed to runApp) and becomes part of the tree. The framework can also create the same widget object many times and place it in several spots. Each place gets its own on-screen object. That is why a widget is a configuration and not a view.
This difference also explains why rebuilding is cheap. When your UI changes, the framework asks your build methods for new descriptions. Creating new Text objects costs little. The expensive work, layout and painting, only happens for the parts that actually changed.
Common errors at this stage
- Forgetting
childorchildren. WritingCenter(Text('Hi'))fails because the argument must be named:Center(child: Text('Hi')). - Using
childwith a list.Column(child: [...])is a type error. Multi-child widgets usechildren. - Putting layout logic in the wrong place. To add spacing, wrap a widget in
Paddingor add aSizedBox. Widgets don't have a general margin property unless they are built onContainer. - Expecting a widget to update itself. If you hold a
Textin a variable and want different text, you can't modify it. You build a newText. How the UI knows to rebuild is the subject of the stateful chapters. - Missing
const. The code still works, but it creates new objects that Flutter could have reused. The chapter on immutability andconstexplains the benefit.
Summary of the mental model
- A widget describes part of the UI. It isn't the drawn result.
- Widgets are immutable, and their data arrives through constructors.
- Layout, styling, and behavior are all expressed as widgets.
- You build complex screens by nesting simple widgets.
- Your own components are classes that return other widgets from
build.
Exercise
A teammate writes final title = Text('Welcome'); in a build method but never uses title in the returned widget. Will "Welcome" appear on screen, and why or why not?
Show answer
No. A widget is only a description. Creating Text('Welcome') produces an object, but nothing appears until it is returned from build (or nested inside a returned widget) and becomes part of the widget tree.
Exercise
Write a stateless widget named Tag that takes a required String text and shows it with 8 logical pixels of padding on every side. Which two widgets does it combine?
Show answer
It combines Padding and Text.
class Tag extends StatelessWidget {
const Tag({super.key, required this.text});
final String text;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8),
child: Text(text),
);
}
}