首页 > 解决方案 > Flutter 监听来自其他小部件的 textField 值变化

问题描述

下面是一个使用 textField 和按钮捕获用户输入的对话框。当 textField 为空时,该按钮被禁用,但是当 textField 被填充值时,它继续被禁用。这是因为 _textController.text 状态未更新(在此小部件中再次呈现)。

void _pushAdd() async {
await showDialog(
  context: this.context,
  builder: (BuildContext context) {
    return AlertDialog(
      title: Text('Add a custom word'),
      content: _renderForm(),
      actions: <Widget>[
        FlatButton(
          child: Text('ADD'),
          onPressed: (_textController.text.isNotEmpty) ? () =>  _addNewPair() : null,
        ),
      ],
    );
  },
);
// Changed _pushAdd as async to handle onClose and clear _textController upon exit
_textController.clear();

当前 _textController 在顶部的类中启动(不是 init)。

var _textController = new TextEditingController();

带有 _textController 的 textField 位于此处:

Widget _renderForm() {
return Container(
  height: 50.0,
  child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      TextField(
        autofocus: true,
        textCapitalization: TextCapitalization.words,
        controller: _textController,
        decoration: InputDecoration(
          hintText: 'RedPotato',
        ),
      ),
    ]
  )
);

}

我最初的计划是使用 onChanged: + 另一种存储文本的状态。但是,我怀疑这样做是否有效。所以我问,实时处理 TextField 值以便其他小部件可以监听更改的标准方法是什么?

标签: dartflutter

解决方案


你只需要听TextEditingController文本变化。

      var _textController = TextEditingController();

      @override
      void dispose() {
        // Clean up the controller when the Widget is disposed
        _textController.dispose();
        super.dispose();
      }

      @override
      void initState() {
        _textController.addListener((){
            //here you have the changes of your textfield
            print("value: ${_textController.text}");
            //use setState to rebuild the widget
            setState(() {

                    });
        });
        super.initState();
      }

For more info check this link : https://flutter.io/docs/cookbook/forms/retrieve-input


推荐阅读