我在我拥有或创建的
TextInputFormatter
中遇到了一个问题,当您键入数字时,在文本字段中编辑/键入数字时似乎出现问题,问题是它重复了最后一个数字或类似的内容。对于我在下面给出的代码,这种情况发生在bank3中。
对于更具体的细节,我想要的是输入采用这种格式
123-4567890123
(13 位数字,第三位和第四位数字中间有破折号)。例如,当我输入第四个数字时,我输入了 123
并输入了下一个数字,它变成了 1234-4
,当输入下一个数字时,它变成了 123445-445
,然后当我再次输入下一个数字时 1234454456-445445
那时输入应该是 123-456
。
这是我的自定义文本输入格式化程序的 dart 文件:
import 'package:flutter/services.dart';
class AccountNumberInputFormatter extends TextInputFormatter {
final String bankName;
AccountNumberInputFormatter(this.bankName);
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
final String newText = newValue.text.replaceAll(RegExp(r'[^0-9]'), '');
String formattedText = '';
if (bankName == 'bank1') {
if (newText.isNotEmpty) {
formattedText = newText.substring(0, newText.length < 12 ? newText.length : 12);
}
} else if (bankName == 'bank2') {
if (newText.isNotEmpty) {
final List<String> chunks = [];
for (int i = 0; i < newText.length; i += 4) {
final end = i + 4;
chunks.add(newText.substring(i, end > newText.length ? newText.length : end));
}
formattedText = chunks.join('-');
}
// Limit to 10 numbers without exceeding the original formatted length
formattedText = formattedText.replaceAll('-', '');
formattedText = formattedText.substring(0, formattedText.length < 10 ? formattedText.length : 10);
// Re-add the dashes to the formatted text
if (formattedText.length > 4) {
formattedText = '${formattedText.substring(0, 4)}-${formattedText.substring(4, formattedText.length)}';
}
if (formattedText.length > 9) {
formattedText = '${formattedText.substring(0, 9)}-${formattedText.substring(9, formattedText.length)}';
}
} else if (bankName == 'bank3') {
if (newText.isNotEmpty) {
formattedText = newText.substring(0, newText.length < 13 ? newText.length : 13);
if (newText.length > 3) {
formattedText += '-${newText.substring(3, newText.length < 9 ? newText.length : 9)}';
}
}
} else if (bankName == 'bank4') {
if (newText.isNotEmpty) {
formattedText = newText.substring(0, newText.length < 12 ? newText.length : 12);
}
}
return newValue.copyWith(
text: formattedText,
selection: TextSelection.collapsed(offset: formattedText.length),
);
}
}
您面临的问题似乎与您如何使用
AccountNumberInputFormatter
类处理输入文本的格式有关。具体来说,在 bank3
的情况下,在第三和第四位数字中间添加破折号的逻辑似乎导致了数字重复。
要解决此问题,您需要调整
bank3
案例中的逻辑,以正确处理破折号的插入和格式化文本的长度。这是 bank3
案例的修改后的代码:
} else if (bankName == 'bank3') {
if (newText.isNotEmpty) {
if (newText.length <= 3) {
formattedText = newText;
} else {
formattedText = '${newText.substring(0, 3)}-${newText.substring(3, newText.length < 13 ? newText.length : 13)}';
}
}
}
此代码将确保在第 3 个数字之后插入破折号,然后添加剩余的数字,同时将总长度限制为 13 个字符。
确保使用此更新的代码替换现有
bank3
类中的 AccountNumberInputFormatter
案例。这应该可以解决您所描述的重复数字的问题。