Flutter - Why is child widget's initState() is not called on every rebuild of Parent widget?

Ok, looks like this was clearly mentioned in the State class' docs.

The correct way to do this is to override the didUpdateWidget method in the State subclass.


Thanks to @Dev Aggarwal.

Extending to Dev Aggarwal's answer, i have included example here.

Implement didUpdateWidget() method in Child widget. When ever parent state changed, didUpdateWidget() method will call in child widget.

Implement didUpdateWidget() method in Child widget.

@override
  void didUpdateWidget(<YourChildScreen> oldWidget) {

    super.didUpdateWidget(oldWidget);

    print("oldWidget.searchTerm is ${oldWidget.searchTerm}");
    print("widget.searchTerm is ${widget.searchTerm}");

    if (oldWidget.searchTerm != widget.searchTerm) {

      this.updateChildWithParent();

    }
  }


void updateChildWithParent() {
    print("updateChildWithParent/search screen");
    setState(() {

      _mJsonLoaded = false; // For loader
      if (listArray.length > 0) {
        listArray.clear();
      }
    });

    // Do whatever you want here…
    // Like call api call again in child widget.
  }

I hope it will useful.

Tags:

Dart

Flutter