id_formatter.dart 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import 'package:flutter/material.dart';
  2. import 'package:flutter/services.dart';
  3. class IDTextEditingController extends TextEditingController {
  4. IDTextEditingController({String? text}) : super(text: text);
  5. String get id => trimID(value.text);
  6. set id(String newID) => text = formatID(newID);
  7. }
  8. class IDTextInputFormatter extends TextInputFormatter {
  9. @override
  10. TextEditingValue formatEditUpdate(
  11. TextEditingValue oldValue, TextEditingValue newValue) {
  12. if (newValue.text.isEmpty) {
  13. return newValue.copyWith(text: '');
  14. } else if (newValue.text.compareTo(oldValue.text) == 0) {
  15. return newValue;
  16. } else {
  17. int selectionIndexFromTheRight =
  18. newValue.text.length - newValue.selection.extentOffset;
  19. String newID = formatID(newValue.text);
  20. return TextEditingValue(
  21. text: newID,
  22. selection: TextSelection.collapsed(
  23. offset: newID.length - selectionIndexFromTheRight,
  24. ),
  25. // https://github.com/flutter/flutter/issues/78066#issuecomment-797869906
  26. composing: newValue.composing,
  27. );
  28. }
  29. }
  30. }
  31. String formatID(String id) {
  32. String id2 = id.replaceAll(' ', '');
  33. String suffix = '';
  34. if (id2.endsWith(r'\r') || id2.endsWith(r'/r')) {
  35. suffix = id2.substring(id2.length - 2, id2.length);
  36. id2 = id2.substring(0, id2.length - 2);
  37. }
  38. if (int.tryParse(id2) == null) return id;
  39. String newID = '';
  40. if (id2.length <= 3) {
  41. newID = id2;
  42. } else {
  43. var n = id2.length;
  44. var a = n % 3 != 0 ? n % 3 : 3;
  45. newID = id2.substring(0, a);
  46. for (var i = a; i < n; i += 3) {
  47. newID += " ${id2.substring(i, i + 3)}";
  48. }
  49. }
  50. return newID + suffix;
  51. }
  52. String trimID(String id) {
  53. return id.replaceAll(' ', '');
  54. }