format method
Formats a phone number in the specified format using default rules. Note that this does not promise to produce a phone number that the user can dial from where they are - although we do format in either 'national' or 'international' format depending on what the client asks for, we do not currently support a more abbreviated format, such as for users in the same 'area' who could potentially dial the number without area code. Note that if the phone number has a country calling code of 0 or an otherwise invalid country calling code, we cannot work out which formatting rules to apply so we return the national significant number with no formatting applied.
number
the phone number to be formatted.
numberFormat
the format the phone number should be formatted into.
Implementation
String format(PhoneNumber number, PhoneNumberFormat numberFormat) {
if (number.nationalNumber == 0 && number.hasRawInput()) {
// Unparseable numbers that kept their raw input just use that.
// This is the only case where a number can be formatted as E164 without a
// leading '+' symbol (but the original number wasn't parseable anyway).
// TODO: Consider removing the 'if' above so that unparseable strings
// without raw input format to the empty string instead of '+00'
String rawInput = number.rawInput;
if (rawInput.isNotEmpty) return rawInput;
}
int countryCallingCode = number.countryCode;
String nationalSignificantNumber = getNationalSignificantNumber(number);
if (numberFormat == PhoneNumberFormat.e164) {
// Early exit for E164 case (even if the country calling code is invalid)
// since no formatting of the national number needs to be applied.
// Extensions are not formatted.
return _prefixNumberWithCountryCallingCode(
countryCallingCode,
PhoneNumberFormat.e164,
nationalSignificantNumber,
'',
);
}
if (!_hasValidCountryCallingCode(countryCallingCode)) {
return nationalSignificantNumber;
}
// Note [getRegionCodeForCountryCode()] is used because formatting information
// for regions which share a country calling code is contained by only one
// region for performance reasons. For example, for NANPA regions it will be
// contained in the metadata for US.
String regionCode = getRegionCodeForCountryCode(countryCallingCode);
// Metadata cannot be null because the country calling code is valid (which
// means that the region code cannot be ZZ and must be one of our supported
// region codes).
PhoneMetadata metadata =
_getMetadataForRegionOrCallingCode(countryCallingCode, regionCode)!;
String formattedExtension = _maybeGetFormattedExtension(
number,
metadata,
numberFormat,
);
String formattedNationalNumber = _formatNsn(
nationalSignificantNumber,
metadata,
numberFormat,
);
return _prefixNumberWithCountryCallingCode(
countryCallingCode,
numberFormat,
formattedNationalNumber,
formattedExtension,
);
}