Sub topic 9
Building UI with StatelessWidget
This chapter assumes you have a project created with flutter create that runs with flutter run. It also assumes you know Dart classes, final fields, and named constructor parameters. By the end you will be able to write your own StatelessWidget classes, pass data into them, compose them into larger screens, and avoid the usual mistakes.
What a StatelessWidget is
A StatelessWidget is a widget whose configuration never changes after it is created. It holds no mutable data of its own. Given the same constructor arguments and the same inherited data (such as the theme), its build() method always describes the same UI.
Your generated MyApp is already one. Every StatelessWidget has the same shape:
- A constructor that takes configuration.
finalfields that store that configuration.- A
build(BuildContext context)method that returns a widget describing the UI.
"Stateless" does not mean "static on screen". The widget can appear differently when its parent gives it new arguments, or when something it reads from context changes. It just cannot change itself.
How build() is called
Flutter calls build() when the widget is first inserted into the tree. It calls it again when the parent rebuilds and supplies a new configuration, and when an inherited widget the build method depends on changes. For example, Theme.of(context) registers that dependency.
Because Flutter may call build() many times, often once per animation frame, it must be fast and free of side effects. Do not make network calls, write to files, or start timers inside it.
A complete example
This file replaces lib/main.dart. It defines a reusable ProfileCard that takes two required strings and one optional flag.
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: 'Profiles',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
),
home: const Scaffold(
body: SafeArea(
child: Center(
child: ProfileCard(
name: 'Ada Lovelace',
role: 'Mathematician',
highlighted: true,
),
),
),
),
);
}
}
class ProfileCard extends StatelessWidget {
const ProfileCard({
super.key,
required this.name,
required this.role,
this.highlighted = false,
});
final String name;
final String role;
final bool highlighted;
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
return Card(
color: highlighted ? colors.primaryContainer : null,
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(name, style: Theme.of(context).textTheme.titleLarge),
const SizedBox(height: 4),
Text(role),
],
),
),
);
}
}Points to notice:
super.keyforwards the optionalkeyargument to the parent class. Keys let Flutter match widgets between rebuilds, which matters mostly in lists.- The fields are
final. A widget is an immutable description, and Flutter creates new widget objects freely. requiredmakesnameandrolecompulsory, so a caller cannot forget them.highlightedhas a default.Theme.of(context)reads the nearestThemeabove this widget in the tree. That is whycontextis passed tobuild().build()returns one widget, and that widget's children are nested inside it. The result is a small tree:Card, thenPadding, thenColumn, then twoTextwidgets and aSizedBox.
Composing widgets
Flutter favors composition over inheritance. You do not subclass Card to customize it. You write a new widget that returns a Card. To show several profiles, build another stateless widget that uses the first:
class ProfileList extends StatelessWidget {
const ProfileList({super.key, required this.people});
final List<(String, String)> people;
@override
Widget build(BuildContext context) {
return ListView(
padding: const EdgeInsets.all(8),
children: [
for (final (name, role) in people)
ProfileCard(name: name, role: role),
],
);
}
}This uses Dart 3 record types (String, String) and a collection for. To try it, replace the Center(...) in MyApp with a ProfileList that has a few entries. Because the list is not constant, remove const from the Scaffold and its ancestors that wrap it.
Why const matters
A const constructor lets Dart create the widget at compile time and share one instance. When a parent rebuilds and meets the identical const instance, Flutter sees nothing changed and skips that subtree's build().
To get this benefit, you must do both of these:
- Declare the constructor
const. This requires every field to befinal. - Write
constat the call site, as inconst Text('Hello').
If any argument is computed at runtime, such as Text(name), that widget cannot be const. Its parent can still be rebuilt normally. Mark the parts that can be constant, like the Padding value and SizedBox above.
The flutter_lints package, included in new projects, reports prefer_const_constructors and prefer_const_literals_to_create_immutables. Your editor can apply these fixes for you.
Widgets versus helper methods
You may be tempted to split a long build() into methods like Widget _buildHeader(). This works, but a separate widget class is usually better:
| Approach | Rebuild behavior | `const` possible | Testable on its own |
|---|---|---|---|
| Helper method | Runs every time the parent's `build()` runs | No | Only through the parent |
| Separate `StatelessWidget` | Skipped when given an identical `const` instance | Yes | Yes |
Use a helper method for a small piece used once. Extract a class when the piece is reused, has its own parameters, or sits in a part of the tree that rebuilds often.
Choosing stateless or stateful
Ask whether the widget needs to remember something that changes because of its own events, such as a tap counter, a text field's contents, or a checkbox. If so, it needs state, which the next chapter covers. If everything it shows comes from constructor arguments or from context, keep it stateless. Most widgets in a real app are stateless.
Common errors
- Mutable fields. Writing
String name;withoutfinaltriggers the analyzer warning "This class (or a class that this class inherits from) is marked as '@immutable', but one or more of its instance fields aren't final." Make the fieldfinaland create a new widget to change it. - Calling
setStatein a stateless widget. The method does not exist there, so the compiler reportsThe method 'setState' isn't defined. Move the changing data into aStatefulWidget, or into the parent, which passes new values down. - Forgetting to return. A
build()that builds a widget but never returns it fails with a message that the function's return type isWidgetand it "could return null". Alwaysreturnthe root widget. - Missing required arguments. A new field added to the constructor without updating each call site produces
The named parameter 'x' is required, but there's no corresponding argument. - Unbounded sizes. A
ListViewdirectly inside aColumnthrows "Vertical viewport was given unbounded height". Wrap theListViewinExpanded, or give it a fixed height. - Row overflow. Long text in a
Rowshows a yellow-and-black stripe and "A RenderFlex overflowed by N pixels". Wrap theTextinExpandedorFlexible. - Doing work in build(). Starting a request in
build()repeats it on every rebuild. Do that work outside ofbuild(), in a stateful widget'sinitStateor in a state management layer.
Try it
Change ProfileCard to accept an optional IconData? icon. When it is not null, show the icon in a Row to the left of the name. Mark every constructor you can as const. Run flutter analyze and fix any warnings.
Exercise
Your teammate writes a widget with the field String title; (not final) and a method that sets title = 'New' inside a button handler, expecting the screen to update. Name two things wrong with this design and how you would fix it.
Show answer
First, widget fields should be final, because widgets are immutable descriptions and the analyzer flags non-final fields in a StatelessWidget. Second, assigning a field does not tell Flutter to rebuild, so the screen will not change. Fix it by turning the widget into a StatefulWidget that keeps the title in its State object and changes it inside setState. Alternatively, keep the widget stateless and have the parent own the value and pass a new title down.
Exercise
Why can const Text('Hi') avoid being rebuilt when its parent rebuilds, while Text(userName) cannot?
Show answer
A const expression is created once at compile time, so every rebuild of the parent produces the identical instance. Flutter detects the same instance and skips that subtree's build(). Text(userName) depends on a runtime value, so it cannot be const. A new widget object is created on each parent build, and Flutter must compare it with the old one and rebuild if its configuration differs.