input_formatter.dart 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import 'package:flutter/services.dart';
  2. class XNumberTextInputFormatter extends TextInputFormatter {
  3. int? maxIntegerLength;
  4. int? maxDecimalLength;
  5. bool isAllowDecimal;
  6. /// [maxIntegerLength]限定整数的最大位数,为null时不限
  7. /// [maxDecimalLength]限定小数点的最大位数,为null时不限
  8. /// [isAllowDecimal]是否可以为小数,默认是可以为小数,也就是可以输入小数点
  9. XNumberTextInputFormatter({
  10. this.maxIntegerLength,
  11. this.maxDecimalLength,
  12. this.isAllowDecimal = true,
  13. });
  14. @override
  15. TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
  16. String value = newValue.text.trim(); //去掉前后空格
  17. int selectionIndex = newValue.selection.end;
  18. if (isAllowDecimal) {
  19. if (value == '.') {
  20. value = '0.';
  21. selectionIndex++;
  22. } else if (value != '' && _isToDoubleError(value)) {
  23. //不是double输入数据
  24. return _oldTextEditingValue(oldValue);
  25. }
  26. //包含小数点
  27. if (value.contains('.')) {
  28. int pointIndex = value.indexOf('.');
  29. String beforePoint = value.substring(0, pointIndex);
  30. // print('$beforePoint');
  31. String afterPoint = value.substring(pointIndex + 1, value.length);
  32. // print('$afterPoint');
  33. //小数点前面没内容补0
  34. if (beforePoint.isEmpty) {
  35. value = '0.$afterPoint';
  36. selectionIndex++;
  37. } else {
  38. //限定整数位数
  39. if (maxIntegerLength != null) {
  40. if (beforePoint.length > maxIntegerLength!) {
  41. return _oldTextEditingValue(oldValue);
  42. }
  43. }
  44. }
  45. //限定小数点位数
  46. if (null != maxDecimalLength) {
  47. if (afterPoint.length > maxDecimalLength!) {
  48. return _oldTextEditingValue(oldValue);
  49. }
  50. }
  51. } else {
  52. //限定整数位数
  53. if (null != maxIntegerLength) {
  54. if (value.length > maxIntegerLength!) {
  55. return _oldTextEditingValue(oldValue);
  56. }
  57. }
  58. }
  59. } else {
  60. if (value.contains('.') ||
  61. (value != '' && _isToDoubleError(value)) ||
  62. (null != maxIntegerLength && value.length > maxIntegerLength!)) {
  63. return _oldTextEditingValue(oldValue);
  64. }
  65. }
  66. return TextEditingValue(
  67. text: value,
  68. selection: TextSelection.collapsed(offset: selectionIndex),
  69. );
  70. }
  71. ///返回旧的输入内容
  72. TextEditingValue _oldTextEditingValue(TextEditingValue oldValue) {
  73. return TextEditingValue(
  74. text: oldValue.text,
  75. selection: TextSelection.collapsed(offset: oldValue.selection.end),
  76. );
  77. }
  78. ///输入内容不能解析成double
  79. bool _isToDoubleError(String value) {
  80. try {
  81. double.parse(value);
  82. } catch (e) {
  83. return true;
  84. }
  85. return false;
  86. }
  87. }