Flutter子組件調用父組件方法修改父組件參數

子組件調用父級組件方法的主要實現是父組件給子組件傳入一個方法,而後在子組件中調用父級方法來修改父級的參數。看一下效果圖javascript

父級組件實現

在父級組件中寫一個_editParentText的方法來修改組件中的contentText值,並在引入子組件的時候傳入該方法java

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方法app

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);    // 調用父級組件方法
              });
            },
          )
        ],
      ),
    );
  }

}
相關文章
相關標籤/搜索