在flutter的TextFormField中管理事件

时间:2018-02-19 16:17:19

标签: dart listener textfield flutter

在Flutter项目中,我需要收听TextFormField中的输入文本并执行某些操作,尤其是当用户在此字段中放置某个字符(例如空格)或请求焦点时。当这种事件发生时,我需要修改字段的值。 我知道有一个属性called controller,但在这种情况下我不知道如何使用它。

提前谢谢。

2 个答案:

答案 0 :(得分:26)

您可以指定控制器和焦点节点,然后向其添加侦听器以监视更改。

例如:

定义控制器和焦点节点

TextEditingController _controller = new TextEditingController();

FocusNode _textFocus = new FocusNode();

定义监听器功能

void onChange(){
  String text = _controller.text;
  bool hasFocus = _textFocus.hasFocus;
  //do your text transforming
  _controller.text = newText;
  _controller.selection = new TextSelection(
                                baseOffset: newText.length, 
                                extentOffset: newText.length
                          );
}

将listner添加到控制器,并将焦点定位添加到initState

// you can have different listner functions if you wish
_controller.addListener(onChange); 
_textFocus.addListener(onChange);

然后你可以用它作为

new TextFormField(
  controller: _controller,
  focusNode: _textFocus,
)

希望有所帮助!

答案 1 :(得分:0)

如果只是尝试将输入转换为TextFormField中的其他形式,则最好使用“ TextInputFormatter”。将侦听器与TextController一起使用会带来很多麻烦。看一下我的示例代码,看看是否有帮助。顺便说一句,代码的最后一行只是试图将光标移动到文本的结尾。

TextFormField(inputFormatters: [QuantityInputFormatter()])

class QuantityInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    final intStr = (int.tryParse(newValue.text) ?? 0).toString();
    return TextEditingValue(
            text: intStr, selection: TextSelection.collapsed(offset: intStr.length),);
  }
}