首页 > 解决方案 > 如何在不影响 maxLength 的情况下格式化 TextFormField 中的输入文本?

问题描述

我想要实现的是计算输入字符的计数器应该只计算输入的数字(数字字符)。输入的位数为10;但是空格、括号和连字符也被计算在内!: (

输入的字符数为 10,但空格、括号和连字符也被计算在内!

这是用于格式化输入文本的类:

/// Format incoming numeric text to fit the format of (###) ###-#### ##
class _UsNumberTextInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    final newTextLength = newValue.text.length;
    final newText = StringBuffer();
    var selectionIndex = newValue.selection.end;
    var usedSubstringIndex = 0;
    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),
    );
  }
}

声明类型:

final _UsNumberTextInputFormatter _phoneNumberFormatter = _UsNumberTextInputFormatter();

在 TextFormField 中使用它:

TextFormField(
  restorationId: 'phone_number_field',
  textInputAction: TextInputAction.next,
  focusNode: _phoneNumber,
  decoration: InputDecoration(
    filled: true,
    icon: const Icon(Icons.phone),
    hintText: GalleryLocalizations.of(context)
        .demoTextFieldWhereCanWeReachYou,
    labelText:
        GalleryLocalizations.of(context).demoTextFieldPhoneNumber,
    prefixText: '+1 ',
  ),
  keyboardType: TextInputType.phone,
  onSaved: (value) {
    person.phoneNumber = value;
    _email.requestFocus();
  },
  maxLength: 14,
  maxLengthEnforcement: MaxLengthEnforcement.none,
  validator: _validatePhoneNumber,
  // TextInputFormatters are applied in sequence.
  inputFormatters: <TextInputFormatter>[
    FilteringTextInputFormatter.digitsOnly,
    // Fit the validating format.
    _phoneNumberFormatter,
  ],
),

来源:https ://gallery.flutter.dev/#/demo/text-field

标签: flutterdarttextformfield

解决方案


推荐阅读