Search code examples
flutterflutter-textformfield

flutter textinputformatter is not working


I want to implement textinputformatter in textformfield

I tried code snippet from topic below to format incoming numeric text to fit the format of (###) ###-#### ##, but it's not working (class _UsNumberTextInputFormatter extends TextInputFormatter)

https://medium.com/@rubensdemelo/flutter-formatting-textfield-with-textinputformatter-6caba78668e5

Can you tell me what I'm doing wrong? How the formatter works?


final _textInputFormatter = _UsNumberTextInputFormatter();
TextFormField(
              inputFormatters: [_textInputFormatter],
              readOnly: true,
              controller: _textController,
              decoration: InputDecoration(
                hintText: '(123) 456 78 90',
                suffixIcon: _textController.text.isNotEmpty
                    ? IconButton(
                        icon: const Icon(Icons.clear),
                        onPressed: () => _textController.clear(),
                      )
                    : null,
                helperText: 'Enter phone number',
              ),
            ),

class _UsNumberTextInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    final int newTextLength = newValue.text.length;
    int selectionIndex = newValue.selection.end;
    int usedSubstringIndex = 0;
    final StringBuffer newText = StringBuffer();
    if (newTextLength >= 1) {
      newText.write('(');
      if (newValue.selection.end >= 1) selectionIndex++;
    }
    if (newTextLength >= 4) {
      newText.write(newValue.text.substring(0, usedSubstringIndex = 3) + ') ');
      if (newValue.selection.end >= 3) selectionIndex += 2;
    }
    if (newTextLength >= 7) {
      newText.write(newValue.text.substring(3, usedSubstringIndex = 6) + '-');
      if (newValue.selection.end >= 6) selectionIndex++;
    }
    if (newTextLength >= 11) {
      newText.write(newValue.text.substring(6, usedSubstringIndex = 10) + ' ');
      if (newValue.selection.end >= 10) selectionIndex++;
    }
    // Dump the rest.
    if (newTextLength >= usedSubstringIndex)
      newText.write(newValue.text.substring(usedSubstringIndex));
    return TextEditingValue(
      text: newText.toString(),
      selection: TextSelection.collapsed(offset: selectionIndex),
    );
  }
}


Solution

  • I had the same problem. Using TextFormField(...readOnly: false was the reason.