Created
April 1, 2024 06:30
-
-
Save BarryDaBee/282754634034d33e8f5e94bf9f74e561 to your computer and use it in GitHub Desktop.
Phone Number TextInputFormatter for (XXX) XXX-XXXX
This file contains 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/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