Skip to content

Instantly share code, notes, and snippets.

@BarryDaBee
Created April 1, 2024 06:30
Show Gist options
  • Save BarryDaBee/282754634034d33e8f5e94bf9f74e561 to your computer and use it in GitHub Desktop.
Save BarryDaBee/282754634034d33e8f5e94bf9f74e561 to your computer and use it in GitHub Desktop.
Phone Number TextInputFormatter for (XXX) XXX-XXXX
import 'package:flutter/services.dart';
class PhoneNumberFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue,) {
if (newValue.text.isEmpty) {
return newValue;
}
final unformattedText = newValue.text.replaceAll(RegExp(r'\D'), '');
final formattedText = _formatPhoneNumber(unformattedText);
return newValue.copyWith(
text: formattedText,
selection: TextSelection.collapsed(offset: formattedText.length),
);
}
String _formatPhoneNumber(String unformattedText) {
if (unformattedText.length <= 3) {
return '($unformattedText';
} else if (unformattedText.length <= 6) {
return '(${unformattedText.substring(0, 3)}) '
'${unformattedText.substring(3)}';
} else {
return '(${unformattedText.substring(0, 3)}) '
'${unformattedText.substring(3, 6)}'
'-${unformattedText.substring(6)}';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment