Flutter:在TextInputFormatter中使用NumberFormat
问题内容:
我试图使用NumberFromatter
的TextInputFormatter
,但是当我尝试使用它,它完全搞砸了!这是我的TextInputFormatter
实现代码:
class NumericTextFormatter extends TextInputFormatter {
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
if(newValue.text.length > 0) {
int num = int.parse(newValue.text.replaceAll(',', ''));
final f = new NumberFormat("#,###");
return newValue.copyWith(text: f.format(num));
} else {
return newValue.copyWith(text: '');
}
}
}
因此,当我将此格式化程序添加到TextField
并尝试输入1到9时,我希望看到的内容如下:123,456,789
但这显示在TextField
:
1
12
123
1,234
12,354 <- this is where it starts
123,564
1,235,674
12,356,874 <- and it happends again
似乎在添加一个字符后光标移动了。那么有人可以帮我吗?
问题答案:
这是因为在格式化值之后,您要添加一个新字符,但文本选择保持在同一位置,少一个字符,这会导致预期的行为
您可以TextInputFormatter
这样修改:
固定以支持所有语言环境并记住光标位置
class NumericTextFormatter extends TextInputFormatter {
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.text.length == 0) {
return newValue.copyWith(text: '');
} else if (newValue.text.compareTo(oldValue.text) != 0) {
int selectionIndexFromTheRight = newValue.text.length - newValue.selection.end;
final f = new NumberFormat("#,###");
int num = int.parse(newValue.text.replaceAll(f.symbols.GROUP_SEP, ''));
final newString = f.format(num);
return new TextEditingValue(
text: newString,
selection: TextSelection.collapsed(offset: newString.length - selectionIndexFromTheRight),
);
} else {
return newValue;
}
}
}