TextFormField 抖动上没有小数点分隔符的千位分隔符

Ben*_*jax 0 textfield dart flutter

我使用flutter_masked_text来格式化我的控制器,以自动将千位分隔符添加到我的货币字段中。我正在用这个来实现这一目标。

var controller = new MoneyMaskedTextController(decimalSeparator: '.', thousandSeparator: ',');
Run Code Online (Sandbox Code Playgroud)

我不喜欢它的工作方式,因为它0.00从小数部分开始并自动开始添加数字。如果我输入1000,它应该变成1,000not 1,000.00。有没有办法可以格式化我的控制器字段以添加千位分隔符而无需小数分隔符?

小智 7

我有同样的问题,我之前找到了一种自定义输入格式化程序代码方式作为执行相同操作的临时解决方案,然后我针对这种特定体验对其进行了修改。如果有帮助,您可以尝试一下,并随意优化它。

class DecimalFormatter extends TextInputFormatter {
  final int decimalDigits;

  DecimalFormatter({this.decimalDigits = 2}) : assert(decimalDigits >= 0);

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, 
    TextEditingValue newValue,) {

      String newText;

      if (decimalDigits == 0) {
        newText = newValue.text.replaceAll(RegExp('[^0-9]'), '');
      }
      else {
        newText = newValue.text.replaceAll(RegExp('[^0-9\.]'), '');
      }

      if(newText.contains('.')) {
        //in case if user's first input is "."
        if (newText.trim() == '.') {
          return newValue.copyWith(
            text: '0.',
            selection: TextSelection.collapsed(offset: 2),
          );
        }
        //in case if user tries to input multiple "."s or tries to input 
        //more than the decimal place
        else if (
          (newText.split(".").length > 2) 
          || (newText.split(".")[1].length > this.decimalDigits)
        ) {
          return oldValue;
        }
        else return newValue;
      }

      //in case if input is empty or zero
      if (newText.trim() == '' || newText.trim() == '0') {
        return newValue.copyWith(text: '');
      } 
      else if (int.parse(newText) < 1) {
        return newValue.copyWith(text: '');
      }

      double newDouble = double.parse(newText);
      var selectionIndexFromTheRight =
        newValue.text.length - newValue.selection.end;

      String newString = NumberFormat("#,##0.##").format(newDouble);

      return TextEditingValue(
        text: newString,
        selection: TextSelection.collapsed(
          offset: newString.length - selectionIndexFromTheRight,
        ),
      );
    }
}
Run Code Online (Sandbox Code Playgroud)