简体   繁体   中英

Cannot update text with TextFormField

I want to add splash after user entered 2 numbers for day and 2 numbers for month. The code below worked before but I don't know from which flutter version, it started behaving strangely.

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.

We should use inputFormatters instead to avoid inner loop since updating text using TextEditingController will call itself and act strangely:

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;
                })
              ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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