Interview frequency: …
Short answer
Move the state to the nearest common parent that needs to read or modify it, then pass the value and callbacks down to the children.
Explanation
The parent becomes the single source of truth, and children display the data or request changes through a callback. Lift state gradually; lifting it to the top of the app from the start increases passing and coupling.
Code example
class Parent extends StatefulWidget {
const Parent({super.key});
@override State<Parent> createState() => _ParentState();
}
class _ParentState extends State<Parent> {
int count = 0;
@override Widget build(BuildContext context) => Child(
value: count,
onChanged: (value) => setState(() => count = value),
);
}Common mistakes
- Owning the same state in both the child and the parent.
- Passing many callbacks instead of settling on a single owner.