internationalFormatPhoneNumber static method
Formats a phone number into an international format. Removes non-digit characters and adds the country code with proper spacing. Example: '+11234567890' becomes (+1) 123 45 67 890.
Implementation
static String internationalFormatPhoneNumber(String phoneNumber) {
// Remove any non-digit characters from the phone number
var digitsOnly = phoneNumber.replaceAll(RegExp(r'\D'), '');
// Extract the country code from the digitsOnly
String countryCode = '+${digitsOnly.substring(0, 2)}';
digitsOnly =
digitsOnly.substring(2); // Remove country code from the number.
// Add the remaining digits with proper formatting.
final formattedNumber = StringBuffer();
formattedNumber.write('($countryCode) ');
int i = 0;
while (i < digitsOnly.length) {
int groupLength =
2; // Default group length for international phone numbers.
if (i == 0 && countryCode == '+1') {
groupLength = 3; // Special case for US: first group of 3 digits.
}
int end = i + groupLength;
formattedNumber.write(digitsOnly.substring(i, end)); // Add the group.
if (end < digitsOnly.length) {
formattedNumber.write(' '); // Add space between groups.
}
i = end; // Move to the next group.
}
return formattedNumber.toString(); // Return the formatted phone number.
}