flutter - 如何在不影响 maxLength 的情况下格式化 TextFormField 中的输入文本?
问题描述
我想要实现的是计算输入字符的计数器应该只计算输入的数字(数字字符)。输入的位数为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,
],
),
解决方案
推荐阅读
- c# - 尝试使用 C# 导航 ModelMetadata 时如何获取 ContainerMetadata 的 PropertyName?
- cloud-init - 是否可以在 cloud-init 中同时运行命令
- putty - 无法让计算机连接到 GSM 调制解调器
- python - render_template 中的可选关键字参数
- python - Python/Pandas:一步删除包含两个字符串之一的列*不*?
- reactjs - React Admin getOne 不适用于 Api Patform dataProvider
- amazon-web-services - Pulumi - 如何从堆栈中删除导入的资源而不从 aws 中删除它们?
- c++ - C++:如何使用指向函数的指针值创建成员 unordered_map
- javascript - d3如何在饼图中将图像与切片一起转换
- javascript - 在 sweetAlert 上插入文件时运行一个函数