didChangeDependencies method in Flutter
didChangeDependencies method in Flutter

In Flutter, The didChangeDependencies() override method comes in lifecycle of StatefulWidget. And is been called everytime whenever it see changes in dependencies of StatefulWidget.

For example, Let’s say a StatefulWidget depends on a inherited widget, and due to user event/action the value in inherited widget there is some changes occured, at that momentdidChangeDependencies method will be called to reflect the changes.

Below is a Example on how we can make use of didChangeDependencies in flutter:

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  MyInheritedWidget _inheritedWidget;

  @override
  void didChangeDependencies() {
    _inheritedWidget = MyInheritedWidget.of(context);
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    // Use the inherited widget here
  }
}

In above example, the _MyWidgetState class is depended onMyInheritedWidget class, that is an inherited widget. basically didChangeDependencies method is used to fetch or detect value changes happens in the inherited widget, so that feather we can make use of it in the build method. Due to some event/action by user, If any value of the inherited widget changes, the didChangeDependencies method will be called immediately again, which make the StatefulWidget to update itself with the new value received in the inherited widget.

Note: It’s very important to call super.didChangeDependencies() at the end of the didChangeDependencies method, as it allows any ancestor widgets to also update their dependencies.