The Flutter subcomponent calls the parent component method to modify the parent component parameters

Keywords: PHP

The main implementation of calling the parent component method by the subcomponent is that the parent component passes a method to the child component, and then calls the parent method in the sub component to modify the parent parameter. Take a look at the renderings

Parent component implementation

Write a method of "editParentText" in the parent component to modify the contentText value in the component, and pass in the method when introducing the child component.

class PageParent extends StatefulWidget {
  @override
  _PageParentState createState() => _PageParentState();
}

class _PageParentState extends State<PageParent> {
  String contentText;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Parent component'),
      ),
      body: Container(
        alignment: Alignment.center,
        child: Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.all(20),
              child: Column(
                children: <Widget>[
                  Text('Here are the parent component parameters',),
                  Text('${contentText}',style: TextStyle(color: Colors.red),)
                ],
              ),
            ),
            PageChildren(editParentText: (editText) => _editParentText(editText))
          ],
        ),
      ),
    );
  }

  _editParentText(editText) {
    setState(() {
      contentText = editText;
    });
  }



}

  

Sub page is the implementation

Define an editParentText method in the child page to receive the method passed from the parent, and then directly call the īš editParentText method of the parent component through widget.editParentText('returned parameter ').

class PageChildren extends StatefulWidget {
  final editParentText;
  const PageChildren({Key key, this.editParentText}) : super(key: key);
  @override
  _PageChildrenState createState() => _PageChildrenState();
}

class _PageChildrenState extends State<PageChildren> {
  TextEditingController _controller = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      color: Colors.grey,
      child: Column(
        children: <Widget>[
          Text('This is the child component'),
          Container(
            width: 200,
            color: Colors.white,
            margin: EdgeInsets.symmetric(vertical: 30),
            child: TextField(
              controller: _controller,
            ),
          ),
          RaisedButton(
            child: Text('modify parameters'),
            onPressed: (){
              setState(() {
                widget.editParentText(_controller.text);
              });
            },
          )
        ],
      ),
    );
  }

}

Posted by !Mikey on Thu, 31 Oct 2019 00:24:38 -0700