Created
March 6, 2023 08:54
-
-
Save BarryDaBee/206df9cd562115f156502a01380adc37 to your computer and use it in GitHub Desktop.
A simple text input formatter for grouping text by splitAt and separating with the separator e.g. 2222-1111 has splitAt: 4 and seperator: '-'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter/services.dart'; | |
class CardInputFormatter extends TextInputFormatter { | |
CardInputFormatter({required this.separator, this.splitAt = 4}); | |
final String separator; | |
final int splitAt; | |
@override | |
TextEditingValue formatEditUpdate( | |
TextEditingValue oldValue, | |
TextEditingValue newValue, | |
) { | |
final oldText = oldValue.text; | |
final newText = newValue.text; | |
var endsWithSeparator = false; | |
// if you add text | |
if (newText.length > oldText.length) { | |
for (final char in separator.characters) { | |
if (newText.substring(0, newText.length - 1).endsWith(char)) { | |
endsWithSeparator = true; | |
} | |
} | |
final clean = newText.replaceAll(separator, ''); | |
if (!endsWithSeparator && | |
clean.length > 1 && | |
clean.length % splitAt == 1) { | |
return newValue.copyWith( | |
text: newText.substring(0, newText.length - 1) + | |
separator + | |
newText.characters.last, | |
selection: TextSelection.collapsed( | |
offset: newValue.selection.end + separator.length, | |
), | |
); | |
} | |
} | |
// if you delete text | |
if (newText.length < oldText.length) { | |
for (final char in separator.characters) { | |
if (oldText.substring(0, oldText.length - 1) | |
.endsWith(char)) { | |
endsWithSeparator = true; | |
} | |
} | |
final clean = oldText.substring(0, oldText.length - 1).replaceAll( | |
separator, | |
'', | |
); | |
if (endsWithSeparator && | |
clean.isNotEmpty && | |
clean.length % splitAt == 0) { | |
return newValue.copyWith( | |
text: newText.substring( | |
0, | |
newText.length - separator.length, | |
), | |
selection: TextSelection.collapsed( | |
offset: newValue.selection.end - separator.length, | |
), | |
); | |
} | |
} | |
return newValue; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment