الانتقال إلى المحتوى
تطبيقات الموبايلFlutter· 6 دقائق للقراءة

initState Runs Once: Handling New Parameters with didUpdateWidget

When the parent passes new values, your State gets didUpdateWidget, not a second initState.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • Flutter 3.x
محتويات المقال

A CRM app on a tablet lists customers on the left and shows an edit form on the right. Pick Ali Hassan, then Mona Adel: the header switches to Mona, but the name field still says "Ali Hassan". The agent fixes Mona's phone number, taps save, and Mona's record is now named Ali Hassan. The field's controller was created in initState with the first customer's name, and initState never ran again.

The common misconception

The belief: when a parent rebuilds a widget with new constructor parameters, its State starts over, so initState runs again and sees the new values.

It looks that way from the code. The parent's 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

Widgets are rebuilt all the time, but the element at a given place in the tree survives as long as the new widget has the same 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

The has a fixed order:

  1. createState creates the object, and it's mounted at its place in the tree.
  2. initState runs once. Setup that depends on inherited widgets goes in didChangeDependencies, which runs right after.
  3. build runs any number of times.
  4. didUpdateWidget(oldWidget) runs every time the parent rebuilds with a widget of the same runtimeType and key. Before calling it, Flutter has already pointed widget at the new one, and build always follows.
  5. deactivate and then dispose run when it leaves the tree for good. After dispose, it's never mounted again.

Why the field kept the old name

When Mona was selected, the parent returned a 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

Inside a 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.

Dart name_field.dart
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);}

In a widget test that showed Ali and then Mona, the first version called 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

ApproachWhat happensUse it when
Read widget.x in build()It's always current; there's nothing to syncThe value is derived: a label, a color, a formatted date
Update in didUpdateWidgetSame State; you update what you builtYou hold an object made from the parameters and the rest of the State should survive
Give it ValueKey(customer.id)A new element and State: the old one is disposed, initState runs againEverything in the State should start over

The key option is the mechanism used on purpose. In the same test, keying 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

  1. Audit every initState that reads widgetFor each widget.something read in initState, ask whether the parent can pass a different value later. If it can, handle the change in didUpdateWidget, or key the widget.
  2. Compare what identifies the changeIn didUpdateWidget, compare ids or the specific fields you used, not object identity. Then redo only the work that depends on them.
  3. Keep subscriptions symmetricEvery listener added in initState gets a matching swap in didUpdateWidget and a cancel in dispose.
  4. Read parameters in build when you canDon't copy constructor values into State fields unless the State really owns a changing copy, like the text a user is typing.
  5. Test the parameter changeIn 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

  • initState runs once per State object, not once per widget object you create.
  • A new widget with the same type and key at the same place keeps the State and triggers didUpdateWidget.
  • Anything built from parameters in initState keeps the old values unless you update it in didUpdateWidget.
  • Read parameters in build() when you can; key the widget when the whole State should start over.
  • Subscribe in initState, resubscribe in didUpdateWidget and cancel in dispose.

📚 المصادر

  1. State class — Flutter API
  2. State.initState — Flutter API
  3. State.didUpdateWidget — Flutter API
  4. State.dispose — Flutter API

التعليقات (0)