Flutter:在 TextInputFormatter 中使用 NumberFormat

Mah*_*deh 13 dart flutter

我正在尝试使用NumberFromatterTextInputFormatter但是当我尝试使用它时,它完全搞砸了!这是我的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: '');
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,当我将此格式化程序添加到 aTextField并尝试键入 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
Run Code Online (Sandbox Code Playgroud)

添加一个 , 字符后,光标似乎会移动。那么有人可以帮我解决这个问题吗?

die*_*per 20

这是因为在您格式化值后,您正在添加一个新字符,但文本选择保持在相同位置,少一个字符,这会导致预期的行为

你可以TextInputFormatter像这样修改你的:

固定以支持所有语言环境并记住光标位置

class NumericTextFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    if (newValue.text.isEmpty) {
      return newValue.copyWith(text: '');
    } else if (newValue.text.compareTo(oldValue.text) != 0) {
      final int selectionIndexFromTheRight =
          newValue.text.length - newValue.selection.end;
      final f = NumberFormat("#,###");
      final number =
          int.parse(newValue.text.replaceAll(f.symbols.GROUP_SEP, ''));
      final newString = f.format(number);
      return TextEditingValue(
        text: newString,
        selection: TextSelection.collapsed(
            offset: newString.length - selectionIndexFromTheRight),
      );
    } else {
      return newValue;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这很好用!但是当用户尝试编辑字符串中间的一个字符时,光标会移动到字符串的末尾。有什么解决办法吗? (2认同)