Sub topic 5
Writing a StatelessWidget
Prerequisites
This chapter assumes you know basic Dart: classes, constructors, final fields, named parameters, and null safety. It also assumes you can run a simple Flutter app. You should already know that a widget describes a piece of UI and that build returns a tree of widgets.
What a StatelessWidget is
A StatelessWidget is a widget that holds no data that changes over its lifetime. Everything it needs arrives through its constructor and is stored in final fields. Given the same inputs, its build method returns the same UI.
The widget object is only a configuration, not the thing drawn on screen. Flutter may create and discard many instances of it. Because of that, a stateless widget must not keep values that change between builds.
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');
}
}This example has the four parts every stateless widget has:
- A class that extends
StatelessWidget. - A constructor, usually
const, that accepts akeyand the widget's inputs. finalfields that store those inputs.- A
buildmethod that returns a widget.
Anatomy in detail
The constructor and `super.key`
super.key forwards the optional key parameter to the Widget superclass. Flutter uses keys to decide whether an old widget and a new widget describe the same piece of UI. You rarely need to pass a key yourself, but you should always accept one so callers can. A later chapter covers keys in detail.
Final fields
Every field in a stateless widget should be final. Dart enforces this for const constructors: a class with a const constructor must have only final instance fields. The Flutter analyzer also warns when a Widget subclass has a non-final field, because the widget is meant to be immutable.
Required and optional parameters
Use required for inputs the widget cannot work without. Use a nullable type or a default value for optional inputs.
import 'package:flutter/material.dart';
class Badge extends StatelessWidget {
const Badge({
super.key,
required this.label,
this.color = Colors.blue,
this.icon,
});
final String label;
final Color color;
final IconData? icon;
@override
Widget build(BuildContext context) {
return Chip(
backgroundColor: color,
avatar: icon == null ? null : Icon(icon),
label: Text(label),
);
}
}Here label is mandatory, color has a default, and icon is nullable. Callers write const Badge(label: 'New') or Badge(label: 'Alert', color: Colors.red, icon: Icons.warning).
Note that const Badge(label: 'New') is a valid constant expression because every argument is a compile-time constant. A const constructor does not force every call to be constant. It only permits it.
The build method
build receives a BuildContext and returns a Widget. Flutter calls it when the widget is first inserted into the tree and again whenever the widget must be rebuilt. You do not call build yourself.
Keep build fast and free of side effects. Flutter can call it many times, including once per frame during an animation. Do not start network requests, write to disk, or mutate fields from inside it.
Using BuildContext for inherited data
A stateless widget has no state of its own, but it can still react to data supplied higher in the tree. It does this by reading from the BuildContext. The most common cases are Theme.of(context), MediaQuery.of(context), and Navigator.of(context).
import 'package:flutter/material.dart';
class SectionTitle extends StatelessWidget {
const SectionTitle(this.text, {super.key});
final String text;
@override
Widget build(BuildContext context) {
final style = Theme.of(context).textTheme.titleLarge;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Text(text, style: style),
);
}
}When the theme changes, Flutter rebuilds SectionTitle and build returns a new result. The widget is still stateless: the changing value lives in the theme, not in the widget. Calling Theme.of(context) registers a dependency, so Flutter knows to rebuild this widget when the theme changes.
A stateless widget can therefore produce different output over time, but only because its inputs or inherited dependencies changed.
Composition over customization
Flutter favors building larger widgets by combining smaller ones. A stateless widget is the standard tool for this. Instead of one long build method that nests many levels deep, split the tree into named widgets.
import 'package:flutter/material.dart';
class ProfileCard extends StatelessWidget {
const ProfileCard({
super.key,
required this.name,
required this.role,
});
final String name;
final String role;
@override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(name, style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 4),
Text(role),
],
),
),
);
}
}The widget tree this builds looks like the following.
Widgets versus helper methods
A common shortcut is to move part of build into a private method that returns a widget, such as Widget _buildHeader(). This works, but a separate widget class is usually better.
| Approach | Rebuild behavior | `const` allowed | Appears in DevTools |
|---|---|---|---|
| Helper method | Rebuilds every time the parent's `build` runs | No | No, it is part of the parent |
| Separate widget class | Can be skipped when its configuration is identical | Yes | Yes, as its own node |
With a helper method, Flutter sees one large widget. With a separate class that has a const constructor, Flutter can reuse the existing instance and skip the rebuild. Use a method only for small, one-off pieces that you would never reuse.
Immutability and const
Flutter compares the old widget with the new one when a parent rebuilds. If both are the same instance, Flutter knows nothing changed and skips the work for that subtree. A const widget is created once at compile time and shared, so identical const calls give the same instance.
import 'package:flutter/material.dart';
class Footer extends StatelessWidget {
const Footer({super.key});
@override
Widget build(BuildContext context) {
return const Padding(
padding: EdgeInsets.all(12),
child: Text('Version 1.0'),
);
}
}Using const in two places helps here. The Footer constructor is const, so a parent can write const Footer(). Inside build, the whole subtree is also const, so it is built once and reused.
The prefer_const_constructors and prefer_const_literals_to_create_immutables lint rules in flutter_lints point out places where you can add const. Turn them on and follow them.
Common mistakes
Storing mutable data in a field
This code does not compile cleanly, and even if it did, it would not work:
// Wrong: a stateless widget cannot keep a changing counter.
class BrokenCounter extends StatelessWidget {
BrokenCounter({super.key});
int count = 0;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () => count++,
child: Text('Count: $count'),
);
}
}Incrementing count does not trigger a rebuild, so the text never changes. Worse, if the parent rebuilds, Flutter may create a new BrokenCounter and count resets to zero. Anything that changes over time belongs in a StatefulWidget, which the next chapters cover.
Doing work in build
Avoid creating controllers, subscriptions, or futures inside a stateless build. They would be recreated on every rebuild and never disposed. Create these in a State object instead.
Forgetting the key parameter
A constructor without super.key still compiles, but callers cannot assign a key to the widget. This matters later when you reorder lists of widgets. Include super.key by default.
Expecting a rebuild without a trigger
A stateless widget rebuilds only when its parent rebuilds it with new configuration, or when an inherited dependency it read from context changes. It cannot ask to be rebuilt. If you need that ability, you need state.
When a StatelessWidget is the right choice
Choose a stateless widget when all of these are true:
- The output depends only on constructor arguments and values read from
BuildContext. - The widget does not need to remember anything between builds.
- The widget does not own a controller, animation, or subscription that needs cleanup.
Most widgets in a well-structured app are stateless. Keeping state in a few places and leaving the rest stateless makes code easier to test, because a stateless widget can be built from a known set of inputs and checked directly.
Exercises
Exercise
A teammate writes class Price extends StatelessWidget with a non-final field double amount; and a method that changes amount when a button is pressed. Give two reasons this design fails.
Show answer
First, a widget is meant to be immutable, so the analyzer flags the non-final field and a const constructor is not allowed. Second, changing the field does not schedule a rebuild, so the screen never updates, and if the parent rebuilds, Flutter may create a new instance that resets the field. The data should live in a State object or in a parent that passes it down.
Exercise
Why is a separate StatelessWidget with a const constructor usually better than a private _buildHeader() helper method for a reusable section of UI?
Show answer
A const widget instance can be reused, so Flutter can skip rebuilding that subtree when the configuration has not changed. A helper method runs again every time the parent's build runs and cannot be const. The separate class also shows up as its own node in DevTools and can be reused elsewhere.