number_text_input_formatter.dart 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import 'package:flutter/services.dart';
  2. /// 数字、小数格式化(默认两位小数)
  3. class UsNumberTextInputFormatter extends TextInputFormatter {
  4. UsNumberTextInputFormatter({
  5. this.digit = 2,
  6. this.max = 1000000
  7. });
  8. /// 允许输入的小数位数,-1代表不限制位数
  9. final int digit;
  10. /// 允许输入的最大值
  11. final double max;
  12. static const double _kDefaultDouble = 0.001;
  13. double _strToFloat(String str, [double defaultValue = _kDefaultDouble]) {
  14. try {
  15. return double.parse(str);
  16. } catch (e) {
  17. return defaultValue;
  18. }
  19. }
  20. ///获取目前的小数位数
  21. int _getValueDigit(String value) {
  22. if (value.contains('.')) {
  23. return value.split('.')[1].length;
  24. } else {
  25. return -1;
  26. }
  27. }
  28. @override
  29. TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
  30. String value = newValue.text;
  31. int selectionIndex = newValue.selection.end;
  32. if (value == '.') {
  33. value = '0.';
  34. selectionIndex++;
  35. } else if (value != '' && value != _kDefaultDouble.toString() &&
  36. _strToFloat(value) == _kDefaultDouble ||
  37. _getValueDigit(value) > digit || _strToFloat(value) > max) {
  38. value = oldValue.text;
  39. selectionIndex = oldValue.selection.end;
  40. }
  41. return TextEditingValue(
  42. text: value,
  43. selection: TextSelection.collapsed(offset: selectionIndex),
  44. );
  45. }
  46. }