
initState Runs Once: Handling New Parameters with didUpdateWidget
- كاتب موثّق
- Flutter 3.x
محتويات المقال
initState with the first customer's name, and initState never ran again.
The common misconception
State starts over, so initState runs again and sees the new values.
build() creates a brand-new object, NameField(customer: mona), so a fresh start feels natural. Most screens also seem to confirm it: when you push a new route, its widgets get new State objects, and setup in initState works every time. Developers coming from Angular may also map it onto what they know without noticing the second half: initState is close to ngOnInit, which runs once, but the role of ngOnChanges belongs to a different method. The half-truth is that initState does see the widget's parameters. It sees the first ones, once.
What actually happens
One State per element, not per widget
runtimeType and key, and the State lives as long as its element. The docs are precise about it: the framework calls initState exactly once for each State object it creates. Creating a new widget object isn't creating a new State.
The lifecycle, in order
createStatecreates the object, and it's mounted at its place in the tree.initStateruns once. Setup that depends on inherited widgets goes indidChangeDependencies, which runs right after.buildruns any number of times.didUpdateWidget(oldWidget)runs every time the parent rebuilds with a widget of the sameruntimeTypeand key. Before calling it, Flutter has already pointedwidgetat the new one, andbuildalways follows.deactivateand thendisposerun when it leaves the tree for good. Afterdispose, it's never mounted again.
Why the field kept the old name
NameField at the same spot, with the same type and no key. So the element stayed, widget.customer became Mona, and didUpdateWidget ran. initState didn't. The header was right because it reads widget.customer in build(). The text field was wrong because its controller had been filled once, from Ali.
widget is live; your copies are snapshots
State, widget always refers to the latest configuration. A field you filled from it in initState is a snapshot of that moment, and this whole class of bugs is a snapshot outliving its source: a controller's text, a subscription opened for one id, an animation started toward one value, a formatted string cached in a field. Each needs a deliberate update when the parameter it came from changes, and didUpdateWidget is where you get both versions side by side.
class _NameFieldState extends State<NameField> { late final TextEditingController _controller; @override void initState() { super.initState(); // Runs once per State: the next customer never gets here _controller = TextEditingController(text: widget.customer.name); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) => TextField(controller: _controller);}class _NameFieldState extends State<NameField> { late final TextEditingController _controller; @override void initState() { super.initState(); _controller = TextEditingController(text: widget.customer.name); } @override void didUpdateWidget(NameField oldWidget) { super.didUpdateWidget(oldWidget); if (widget.customer.id == oldWidget.customer.id) return; _controller.text = widget.customer.name; // a new customer: new text } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) => TextField(controller: _controller);}initState once and didUpdateWidget once, and the field still read "Ali Hassan". The second one had the same counts and showed "Mona Adel". Comparing ids rather than whole objects matters too: a refreshed copy of the same customer won't overwrite what the user is typing.
Three ways to follow new parameters
widget.x in build() | ||
didUpdateWidget | State; you update what you built | State should survive |
ValueKey(customer.id) | State: the old one is disposed, initState runs again | State should start over |
NameField with the customer's id ran initState twice and dispose once, and the field showed Mona. It's simple, but it also throws away focus, scroll position and anything else the State held.
How to apply it in your project
Audit every initState that reads widget For each widget.somethingread ininitState, ask whether the parent can pass a different value later. If it can, handle the change indidUpdateWidget, or key the widget.Compare what identifies the change In didUpdateWidget, compare ids or the specific fields you used, not object identity. Then redo only the work that depends on them.Keep subscriptions symmetric Every listener added in initStategets a matching swap indidUpdateWidgetand a cancel indispose.Read parameters in build when you can Don't copy constructor values into Statefields unless theStatereally owns a changing copy, like the text a user is typing.Test the parameter change In a widget test, pump the widget, pump it again with different parameters, and check what's on screen. It takes a few lines and catches this bug every time.
Key takeaways
initStateruns once perStateobject, not once per widget object you create.A new widget with the same type and key at the same place keeps the Stateand triggersdidUpdateWidget.Anything built from parameters in initStatekeeps the old values unless you update it indidUpdateWidget.Read parameters in build()when you can; key the widget when the wholeStateshould start over.Subscribe in initState, resubscribe indidUpdateWidgetand cancel indispose.
التعليقات (0)