Sub topic 10
Lifting State Up
Prerequisites
This chapter assumes you can write a StatelessWidget and a StatefulWidget with setState, and that you know the State lifecycle (initState, didUpdateWidget, dispose). You should also be comfortable with Dart function types such as VoidCallback and ValueChanged<T>.
The problem: two widgets need one value
Suppose a screen has a quantity picker and a label showing the total price. Both depend on the same number. If the picker keeps _quantity in its own State, the label has no way to read it. Widgets can't reach into a sibling's State object.
The fix is to move the value to a widget that sits above both. This is called lifting state up. The ancestor owns the value, passes it down through constructor arguments, and receives change requests through callbacks. The summary is data down, events up.
The rule: data down, events up
A child that displays or edits a value it does not own needs two things from its parent:
- The current value, as a
finalfield. - A callback it calls when the user asks for a change.
The child never changes the value itself. It reports what the user did, and the parent decides whether to update its state. Here is the smallest version of the pattern:
import 'package:flutter/material.dart';
class FavoriteButton extends StatelessWidget {
const FavoriteButton({
super.key,
required this.isFavorite,
required this.onToggle,
});
final bool isFavorite;
final VoidCallback onToggle;
@override
Widget build(BuildContext context) {
return IconButton(
onPressed: onToggle,
icon: Icon(isFavorite ? Icons.favorite : Icons.favorite_border),
);
}
}
class FavoriteScreen extends StatefulWidget {
const FavoriteScreen({super.key});
@override
State<FavoriteScreen> createState() => _FavoriteScreenState();
}
class _FavoriteScreenState extends State<FavoriteScreen> {
bool _isFavorite = false;
@override
Widget build(BuildContext context) {
return FavoriteButton(
isFavorite: _isFavorite,
onToggle: () => setState(() => _isFavorite = !_isFavorite),
);
}
}FavoriteButton is now stateless. Any other widget in FavoriteScreen's subtree could also receive _isFavorite, and they would all agree.
Worked example: a picker and a total
This example has two siblings that share one value. It is a complete app you can run.
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: Scaffold(body: Center(child: ShoppingPanel())),
),
);
}
class QuantityPicker extends StatelessWidget {
const QuantityPicker({
super.key,
required this.quantity,
required this.onChanged,
});
final int quantity;
final ValueChanged<int> onChanged;
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
onPressed: quantity > 0 ? () => onChanged(quantity - 1) : null,
icon: const Icon(Icons.remove),
),
Text('$quantity'),
IconButton(
onPressed: () => onChanged(quantity + 1),
icon: const Icon(Icons.add),
),
],
);
}
}
class TotalLabel extends StatelessWidget {
const TotalLabel({
super.key,
required this.quantity,
required this.unitPrice,
});
final int quantity;
final double unitPrice;
@override
Widget build(BuildContext context) {
return Text('Total: \$${(quantity * unitPrice).toStringAsFixed(2)}');
}
}
class ShoppingPanel extends StatefulWidget {
const ShoppingPanel({super.key});
@override
State<ShoppingPanel> createState() => _ShoppingPanelState();
}
class _ShoppingPanelState extends State<ShoppingPanel> {
int _quantity = 1;
void _setQuantity(int value) {
setState(() {
_quantity = value;
});
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
QuantityPicker(quantity: _quantity, onChanged: _setQuantity),
TotalLabel(quantity: _quantity, unitPrice: 4.50),
],
);
}
}When the user taps the plus button, the flow is:
QuantityPickercallsonChanged(quantity + 1)._setQuantityruns in_ShoppingPanelStateand callssetState.- Flutter rebuilds
ShoppingPanel, which creates newQuantityPickerandTotalLabelwidgets with the new number.
Both children are stateless. This makes them easy to test, because the same arguments always produce the same output.
Choosing where the state goes
Put the state in the lowest common ancestor of every widget that reads or writes it. Going lower is impossible, because some widget would be out of reach. Going higher works but costs you:
- Every
setStaterebuilds a larger subtree. - The value must pass through more constructors.
- The ancestor takes on responsibilities unrelated to its own job.
A useful check is to list the widgets that read the value and the widgets that change it. Find the nearest widget above all of them. That widget owns the state.
| Situation | Where the state lives |
|---|---|
| Only one widget uses the value, such as a focus flag or an animation controller | That widget's own `State` |
| Two siblings use the value | Their shared parent |
| Widgets in different screens use the value | A higher ancestor, or an app-wide tool such as `InheritedWidget` or a state-management package |
Edge cases and costs
Callback types
Use VoidCallback when no value is passed (void Function()). Use ValueChanged<T> when the child reports a new value (void Function(T)). Make callbacks required fields. A nullable onChanged is also a convention: Flutter's own widgets treat a null callback as "disabled". The QuantityPicker above does this for the minus button by passing null when the quantity is 0.
Rebuild scope
setState marks the owner dirty, and the owner's build runs again. Children that are const are skipped, because Flutter can reuse the same instance. In the example, TotalLabel needs the new quantity, so it can't be const. A static child under the panel, such as a title Text, could be.
If the owning widget grows large, split the parts that don't depend on the changing value into their own widgets with const constructors. This keeps the rebuild small.
Copying a value into the child's state
A common mistake is to lift state up and then copy it back down into a child's State:
class _PickerState extends State<QuantityPicker> {
late int _quantity;
@override
void initState() {
super.initState();
_quantity = widget.quantity; // copied once, never updated
}
}initState runs once. When the parent later passes a different quantity, the child still shows the old copy. Now there are two sources of truth that can disagree. If the child only displays the value, read widget.quantity directly, or make the child stateless. If the child truly needs its own editable copy, such as a text field draft, update it in didUpdateWidget when the incoming value changes.
Mutating shared collections
If the owned state is a List or Map, changing it in place while passing the same object down can confuse children that compare old and new values. Replace the collection with a new one inside setState when children might compare by identity:
setState(() {
_items = [..._items, newItem];
});Async work and `mounted`
A callback may start async work that finishes after the owner has been removed from the tree. Calling setState then throws an error. Check mounted first:
Future<void> _load() async {
final result = await fetchQuantity();
if (!mounted) return;
setState(() => _quantity = result);
}Here fetchQuantity stands for any async function that returns an int.
Prop drilling
If a value must pass through four or five widgets that don't use it, the constructors get noisy. This is called prop drilling. Lifting state up is still correct, but at some depth an InheritedWidget (or a package built on it) is a better way to deliver the value. The ownership rule stays the same. Only the delivery changes.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Child keeps its own copy of a parent's value | The child shows stale data after the parent changes | Read `widget.value`, or sync in `didUpdateWidget` |
| Calling `setState` inside `build` | An error about setting state during build | Call it from an event handler or callback |
| Passing a callback that calls the parent's `setState` from a disposed widget | An error after async work | Check `mounted` |
| Lifting state higher than needed | Large rebuilds and long constructor chains | Move it to the lowest common ancestor |
| Changing a list in place | Children don't notice the change | Assign a new list in `setState` |
Exercise
A Counter widget has a button and shows _count in its own State. A sibling ResetBar widget needs a "Reset" button that sets the count to 0. Describe how you would restructure the widgets, and name what each one needs in its constructor.
Show answer
Create a parent stateful widget that owns _count. Make Counter stateless with final int count and final VoidCallback onIncrement. Make ResetBar stateless with final VoidCallback onReset. The parent builds both, passes _count and an onIncrement that calls setState(() => _count++) to Counter, and passes an onReset that calls setState(() => _count = 0) to ResetBar.
Exercise
A child widget copies widget.price into a _price field in initState and displays _price. The parent changes the price from 5 to 8, but the child still shows 5. Why does this happen, and what are two ways to fix it?
Show answer
initState runs only once, when the State is first inserted into the tree. A rebuild with new widget arguments keeps the same State object, so _price keeps its old value. Fix it by reading widget.price directly in build, or by updating _price in didUpdateWidget when widget.price differs from oldWidget.price.