number_text_input_formatter.dart 937 B

12345678910111213141516171819202122232425262728293031
  1. import 'package:flutter/services.dart';
  2. /// 只允许输入小数
  3. class UsNumberTextInputFormatter extends TextInputFormatter {
  4. static const defaultDouble = 0.001;
  5. static double strToFloat(String str, [double defaultValue = defaultDouble]) {
  6. try {
  7. return double.parse(str);
  8. } catch (e) {
  9. return defaultValue;
  10. }
  11. }
  12. @override
  13. TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
  14. String value = newValue.text;
  15. int selectionIndex = newValue.selection.end;
  16. if (value == ".") {
  17. value = "0.";
  18. selectionIndex++;
  19. } else if (value != "" && value != defaultDouble.toString() && strToFloat(value, defaultDouble) == defaultDouble) {
  20. value = oldValue.text;
  21. selectionIndex = oldValue.selection.end;
  22. }
  23. return new TextEditingValue(
  24. text: value,
  25. selection: new TextSelection.collapsed(offset: selectionIndex),
  26. );
  27. }
  28. }