我想将TextFormField
格式的输入号码设置为正确的电话号码格式。
我尝试使用下面的TextInputFormatter
class NumberTextInputFormatter 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 = new StringBuffer();
if (newTextLength >= 1) {
newText.write('+');
if (newValue.selection.end >= 1) selectionIndex++;
}
if (newTextLength >= 3) {
newText.write(newValue.text.substring(0, usedSubstringIndex = 1) + ' ');
if (newValue.selection.end >= 2) selectionIndex += 1;
}
if (newTextLength >= 3) {
newText.write( ' ');
if (newValue.selection.end >= 6) selectionIndex += 1;
}
if (newTextLength >= usedSubstringIndex)
newText.write(newValue.text.substring(usedSubstringIndex));
return new TextEditingValue(
text: newText.toString(),
selection: new TextSelection.collapsed(offset: selectionIndex),
);
}
}
但我没有得到预期的输出
我期望的数字格式
"+1 123-456-7890"
如果需要更多信息,请告诉我。提前致谢。您的努力将不胜感激。
最佳答案
最后,我决定从两个单独的TextFormField
中获取电话号码和国家/地区代码
class CountryCodeTextInputFormatter 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 = new StringBuffer();
if (newTextLength >= 1) {
newText.write('+');
if (newValue.selection.end >= 1) selectionIndex++;
}
if (newTextLength >= usedSubstringIndex)
newText.write(newValue.text.substring(usedSubstringIndex));
return new TextEditingValue(
text: newText.toString(),
selection: new TextSelection.collapsed(offset: selectionIndex),
);
}
}
class PhoneNumberTextInputFormatter 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 = new StringBuffer();
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++;
}
if (newTextLength >= usedSubstringIndex)
newText.write(newValue.text.substring(usedSubstringIndex));
return new TextEditingValue(
text: newText.toString(),
selection: new TextSelection.collapsed(offset: newText.length),
);
}
}
关于Flutter –如何设置电话号码文本字段的格式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60667881/