Skip to content

Instantly share code, notes, and snippets.

@natintosh
Created December 16, 2019 09:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natintosh/6d040393fbc431b88d71998b48f3471b to your computer and use it in GitHub Desktop.
Save natintosh/6d040393fbc431b88d71998b48f3471b to your computer and use it in GitHub Desktop.
A class formats phone number input as you type
typedef OnInputFormatted<T> = void Function(T value);
class PhoneFormatter extends TextInputFormatter {
final RegExp separatorChars = RegExp(r'[^\d]+');
final RegExp allowedChars = RegExp(r'[\d+]');
final String isoCode;
final String dialCode;
final OnInputFormatted<TextEditingValue> onInputFormatted;
PhoneFormatter(
{@required this.isoCode,
@required this.dialCode,
@required this.onInputFormatted})
: assert(isoCode != null),
assert(dialCode != null);
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
int oldValueLength = oldValue.text.length;
int newValueLength = newValue.text.length;
if (newValueLength > 0 && newValueLength > oldValueLength) {
String newValueText = newValue.text;
String rawText = newValueText.replaceAll(separatorChars, '');
String textToParse = dialCode + rawText;
formatAsYouType(input: textToParse).then(
(String value) {
String parsedText =
value.replaceAll(RegExp('^([\\+?${this.dialCode}\\s?]+)'), '');
int offset = newValue.selection.baseOffset;
try {
if (separatorChars.hasMatch(parsedText[offset])) {
offset += 2;
} else {
offset += 1;
}
} on RangeError {}
if (separatorChars.hasMatch(parsedText))
this.onInputFormatted(
TextEditingValue(
text: parsedText,
selection: TextSelection.collapsed(offset: offset),
),
);
},
);
}
return newValue;
}
Future<String> formatAsYouType({@required String input}) async {
try {
String formattedPhoneNumber = await PhoneNumberUtil.formatAsYouType(
phoneNumber: input, isoCode: isoCode);
return formattedPhoneNumber;
} on Exception {
return '';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment