JXCommon.dart 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import 'package:flutter/services.dart';
  2. /*
  3. 工具类
  4. * */
  5. // 限制小数位数
  6. class NumberTextInputFormatter extends TextInputFormatter {
  7. static const defaultDouble = 0.001;
  8. ///允许的小数位数,-1代表不限制位数
  9. int digit;
  10. NumberTextInputFormatter({this.digit = -1});
  11. static double strToFloat(String str, [double defaultValue = defaultDouble]) {
  12. try {
  13. return double.parse(str);
  14. } catch (e) {
  15. return defaultValue;
  16. }
  17. }
  18. ///获取目前的小数位数
  19. static int getValueDigit(String value) {
  20. if (value.contains(".")) {
  21. return value.split(".")[1].length;
  22. } else {
  23. return -1;
  24. }
  25. }
  26. @override
  27. TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
  28. // TODO: implement formatEditUpdate
  29. String value = newValue.text;
  30. int selectionIndex = newValue.selection.end;
  31. if (value == ".") {
  32. value = "0.";
  33. selectionIndex++;
  34. } else if(value=="-"){
  35. value = "-";
  36. selectionIndex++;
  37. }else if (value != "" &&
  38. value != defaultDouble.toString() &&
  39. strToFloat(value, defaultDouble) == defaultDouble ||
  40. getValueDigit(value) > digit) {
  41. value = oldValue.text;
  42. selectionIndex = oldValue.selection.end;
  43. }
  44. return new TextEditingValue(
  45. text: value,
  46. selection: new TextSelection.collapsed(offset: selectionIndex),
  47. );
  48. }
  49. }