【发布时间】:2020-10-05 17:35:18
【问题描述】:
我正在尝试创建自定义 InputTextFormatter。 格式化程序用空格分隔数千个字符,并将点后的字符数限制为 2 个字符。
我想将光标移动到 TextField 值的末尾,但看起来 real 光标会根据我在达到限制后尝试输入其他字符的次数进一步移动(2 个字符)。 看起来选择不适用于生成的 TextEditingValue。
重现步骤:
- 在 TextField 中输入“12.34”。
- 保留以前的值尝试添加 例如“111”。
- 按退格键。什么都没有发生。
预期行为:按一次退格键必须删除 TextField 中的最后一个字符。
class MoneyFormatter extends TextInputFormatter {
MoneyFormatter({this.maxLength = 30, this.decimals = 0});
final int maxLength;
final int decimals;
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
print('---------- newValue.selection.extentOffset : ${newValue.selection.extentOffset}');
String output = newValue.text.formatAsCurrency(decimals: decimals);
var result = TextEditingValue(
text: output,
//this line doesn't have any effect
selection: TextSelection.collapsed(offset: output.length),
);
print('---------- result.selection.extentOffset : ${result.selection.extentOffset}');
return result;
}
}
每增加一个字符result.selection.extentOffset 保持不变,但newValue.selection.extentOffset 增加1 尽管事实上返回selection: TextSelection.collapsed(offset: output.length)
extension FormatAsCurrency on String {
String formatAsCurrency({int decimals = 0, String ifNullReturn}) {
if (this == null) return ifNullReturn;
if (this.isEmpty) return '';
String output = this;
if (output[0] == '.') output = '0' + output;
var chunks = this.withoutTrailingDots.split('.');
output = chunks[0].separatedThousands;
if (decimals == 0 || chunks.length == 1) return output;
output += '.' + chunks[1].limitLengthTo(decimals).withoutTrailingZeros;
return output;
}
}
我知道 pub.dev 上还有其他 TextInputFormatters,例如 flutter_multi_formatter,我已经尝试了所有这些,问题仍然存在。
【问题讨论】:
-
我也遇到了同样的问题,你找到解决办法了吗?
-
不,仍在寻找解决方案
-
我也有这个问题,我发现如果你不聚焦输入就可以了。
-
@intraector 仍然没有解决方案?
-
不,问题仍然存在