Search code examples
flutterflutter-layout

Example on when to use didUpdateWidget


I think I understand all other StatefulWidget lifecycle callbacks, but didUpdateWidget is one that I never had to use, neither can think of a specific use case, as I just get information about the Widget using the widget getter at build.

So on which cases didUpdateWidget is useful and desired to be used?


Solution

  • didUpdateWidget exists for when you want to trigger side-effects when one of the parameters of your stateful widget change.

    A typical use-case is implicitly animated widgets. These are implemented using didUpateWidget like so:

    @override
    void didUpdateWidget(MyWidget oldWidget) {
      super.didUpdateWidget(oldWidget);
      if (widget.value != oldWidget.value) {
        // TODO: start a transition between the previous and new value
      }
    }