子组件调用父级组件方法的主要实现是父组件给子组件传入一个方法,然后在子组件中调用父级方法来修改父级的参数。
父级组件实现
在父级组件中写一个_editParentText的方法来修改组件中的contentText值,并在引入子组件的时候传入该方法
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('父级组件'), ), body: Container( alignment: Alignment.center, child: Column( children: <Widget>[ Container( padding: EdgeInsets.all(20), child: Column( children: <Widget>[ Text('这里是父级组件参数',), Text('${contentText}',style: TextStyle(color: Colors.red),) ], ), ), PageChildren(editParentText: (editText) => _editParentText(editText)) // 给子组件传入_editParentText()方法 ], ), ), ); } // 修改contentText参数 _editParentText(editText) { setState(() { contentText = editText; }); } }
子级页面是实现
在子级页面中定义一个editParentText用于接收父级传过来的方法,然后直接通过widget.editParentText(‘传回的参数’)即调用父级组件的_editParentText方法
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('这里是子级组件'), Container( width: 200, color: Colors.white, margin: EdgeInsets.symmetric(vertical: 30), child: TextField( controller: _controller, ), ), RaisedButton( child: Text('修改参数'), onPressed: (){ setState(() { widget.editParentText(_controller.text); // 调用父级组件方法 }); }, ) ], ), ); } }