简体   繁体   English

无法使用 TextFormField 更新文本

[英]Cannot update text with TextFormField

I want to add splash after user entered 2 numbers for day and 2 numbers for month.我想在用户输入 2 个日数和 2 个月数后添加飞溅。 The code below worked before but I don't know from which flutter version, it started behaving strangely.下面的代码以前工作过,但我不知道从哪个 flutter 版本开始,它开始表现得很奇怪。

class MyCustomForm extends StatefulWidget {
  @override
  _MyCustomFormState createState() => _MyCustomFormState();
}

class _MyCustomFormState extends State<MyCustomForm> {
  final _dobInputController = TextEditingController();
  String _lastDobValue = '';

  @override
  void initState() {
    super.initState();
    _dobInputController.addListener(_onTextChange);
  }

  @override
  void dispose() {
    _dobInputController.dispose();
    super.dispose();
  }

  _onTextChange() {
    int length = _dobInputController.text.length;
    if (_lastDobValue.length < length && (length == 2 || length == 5)) {
      _dobInputController.text += '/';
      _dobInputController.selection = TextSelection.fromPosition(TextPosition(offset: length + 1));
    }
    _lastDobValue = _dobInputController.text;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: <Widget>[
          TextFormField(
            controller: _dobInputController,
            decoration: InputDecoration(
              hintText: 'MM/DD/YYYY',
            ),
          )
        ],
      ),
    ));
  }
}

Just replace TextFormField with TextField , it will work properly again.只需将TextFormField替换为TextField ,它将再次正常工作。

We should use inputFormatters instead to avoid inner loop since updating text using TextEditingController will call itself and act strangely:我们应该使用inputFormatters来避免内部循环,因为使用TextEditingController更新文本会调用自身并产生奇怪的行为:

TextFormField(
              decoration: InputDecoration(
                hintText: 'MM/DD/YYYY',
              ),
              inputFormatters: [
                TextInputFormatter.withFunction((oldValue, newValue) {
                  String newText = newValue.text;
                  int newTextLength = newText.length;
                  if (newValue.text.length > oldValue.text.length && (newTextLength == 2 || newTextLength == 5)) {
                    return TextEditingValue(
                        text: newText + '/',
                        selection: TextSelection.fromPosition(TextPosition(offset: newTextLength + 1)));
                  }
                  return newValue;
                })
              ])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM