Dart 颤振:在TextInputFormatter中使用NumberFormat
我试图在Dart 颤振:在TextInputFormatter中使用NumberFormat,dart,flutter,Dart,Flutter,我试图在TextInputFormatter中使用NumberFromatter,但当我试图使用它时,它完全搞糟了!这是我的TextInputFormatter实现代码: class NumericTextFormatter extends TextInputFormatter { TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { if(newValue.
TextInputFormatter
中使用NumberFromatter
,但当我试图使用它时,它完全搞糟了!这是我的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: '');
}
}
}
因此,当我将此格式化程序添加到文本字段
并尝试键入1到9时,我希望看到的是:123456789
但这就是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
1
12
123
1,234
12354这是因为格式化值后,您添加了一个新字符,但文本选择保持在相同的位置,少了一个字符,这会导致预期的行为
您可以像这样修改TextInputFormatter
:
已修复以支持所有区域设置并记住光标位置
class NumericTextFormatter扩展了TextInputFormatter{
@凌驾
文本编辑值格式编辑更新(
TextEditingValue旧值,TextEditingValue新值){
if(newValue.text.isEmpty){
返回newValue.copyWith(文本:“”);
}else if(newValue.text.compareTo(oldValue.text)!=0){
从右侧选择最终整数索引=
newValue.text.length-newValue.selection.end;
最终f=数字格式(“#,####”);
最终数量=
int.parse(newValue.text.replaceAll(f.symbols.GROUP_SEP');
最终新闻字符串=f.format(数字);
返回TextEditingValue(
文本:新闻字符串,
选择:TextSelection.collapsed(
偏移量:newString.length-从右侧选择索引),
);
}否则{
返回新值;
}
}
}
基于答案,适用于寻求快速解决方案的欧洲人
class NumericTextFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
final currencySymbol = '€';
if (newValue.text.isEmpty || newValue.text.trim() == currencySymbol) {
return newValue.copyWith(text: '');
} else if (newValue.text.compareTo(oldValue.text) != 0) {
var selectionIndexFromTheRight =
newValue.text.length - newValue.selection.end;
final f =
NumberFormat.currency(locale: 'de', decimalDigits: 0, symbol: '');
var num = int.parse(newValue.text.replaceAll(RegExp('[^0-9]'), ''));
final newString = '$currencySymbol ' + f.format(num).trim();
return TextEditingValue(
text: newString,
selection: TextSelection.collapsed(
offset: newString.length - selectionIndexFromTheRight),
);
} else {
return newValue;
}
}
}
这太棒了!但当用户试图编辑字符串中间的一个字符时,光标会移动到字符串的末尾。有什么解决办法吗?@diegoveloper,解决办法很好。即使在尝试删除中间字符的情况下,光标也会按预期移动。这是否在pub.dev包中?是否有方法在稍后的处理过程中返回未格式化的值?谢谢,我们如何更改分隔符?我希望分隔符是逗号','而不是点