How to Invoke initState() method of child widget from parent widget in flutter

Viewed 1863

I want to call initState() method of child widget from parent stateful widget.

Here is my Code:

class ClassA extends StatefulWidget {
  @override
  _ClassAState createState() => _ClassAState();
}

class _ClassAState extends State<ClassA> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: <Widget>[
            ClassB(),
            InkWell(
              child: Text('Call ClassB initState()'),
              onTap: (){
                setState(() {});
              },
            ),
          ],
        ),
      )
      ,
    );
  }
}

class ClassB extends StatefulWidget {
  @override
  _ClassBState createState() => _ClassBState();
}

class _ClassBState extends State<ClassB> {

  @override
  void initState() {
    print('initState in ClassB');
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 100,
      child: Text('Class B'),
    );
  }
}

In above i want to invoke ClassB initState() method from ClassA(). But On tap, it invokes only the build method of class B but I also want to invoke initState().

1 Answers

ClassA and ClassB has 2 different internal state. On the first run the two widget are insert into the tree so every initState is called. After that if you call setState in ClassA you are changing ClassA state. If you look at documentation

https://api.flutter.dev/flutter/widgets/State/initState.html

Called when this object is inserted into the tree.

The framework will call this method exactly once for each State object it creates.

Override this method to perform initialization that depends on the location at which this object was inserted into the tree (i.e., context) or on the widget used to configure this object (i.e., widget).

You can see that initState is called by the framework only once, so isn't the right method to manipulate the state of ClassB once it is already initialized. As Randal Schwartz suggested you should change your code. You can start here

https://flutter.dev/docs/development/ui/interactive

Related