|
| 1 | +import 'package:brasil_fields/src/interfaces/compoundable_formatter.dart'; |
| 2 | +import 'package:flutter/services.dart'; |
| 3 | + |
| 4 | +/// Formata o valor do campo com a máscara CEST `XX.XXX.XX`. |
| 5 | +class CESTInputFormatter extends TextInputFormatter |
| 6 | + implements CompoundableFormatter { |
| 7 | + // Define o tamanho máximo do campo. |
| 8 | + @override |
| 9 | + int get maxLength => 7; |
| 10 | + |
| 11 | + @override |
| 12 | + TextEditingValue formatEditUpdate( |
| 13 | + TextEditingValue oldValue, TextEditingValue newValue) { |
| 14 | + final newValueLength = newValue.text.length; |
| 15 | + |
| 16 | + if (newValueLength > maxLength) { |
| 17 | + return oldValue; |
| 18 | + } |
| 19 | + |
| 20 | + var selectionIndex = newValue.selection.end; |
| 21 | + var substrIndex = 0; |
| 22 | + final newText = StringBuffer(); |
| 23 | + |
| 24 | + if (newValueLength >= 3) { |
| 25 | + newText.write('${newValue.text.substring(0, substrIndex = 2)}.'); |
| 26 | + if (newValue.selection.end >= 2) selectionIndex++; |
| 27 | + } |
| 28 | + if (newValueLength >= 6) { |
| 29 | + newText.write('${newValue.text.substring(2, substrIndex = 5)}.'); |
| 30 | + if (newValue.selection.end >= 5) selectionIndex++; |
| 31 | + } |
| 32 | + |
| 33 | + if (newValueLength >= substrIndex) { |
| 34 | + newText.write(newValue.text.substring(substrIndex)); |
| 35 | + } |
| 36 | + |
| 37 | + return TextEditingValue( |
| 38 | + text: newText.toString(), |
| 39 | + selection: TextSelection.collapsed(offset: selectionIndex), |
| 40 | + ); |
| 41 | + } |
| 42 | +} |
0 commit comments