簡體   English   中英

無法使用 TextFormField 更新文本

[英]Cannot update text with TextFormField

我想在用戶輸入 2 個日數和 2 個月數后添加飛濺。 下面的代碼以前工作過,但我不知道從哪個 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',
            ),
          )
        ],
      ),
    ));
  }
}

只需將TextFormField替換為TextField ,它將再次正常工作。

我們應該使用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