getLengthOfGeographicalAreaCode method

int getLengthOfGeographicalAreaCode(
  1. PhoneNumber number
)

Gets the length of the geographical area code from the nationalNumber field of the PhoneNumber object passed in, so that clients could use it to split a national significant number into geographical area code and subscriber number. It works in such a way that the resultant subscriber number should be diallable, at least on some devices. An example of how this could be used:

var phoneUtil = PhoneNumberUtil.instance;
var number = phoneUtil.parse('16502530000', 'US');
var nationalSignificantNumber =
    phoneUtil.getNationalSignificantNumber(number);
var areaCode;
var subscriberNumber;

var areaCodeLength = phoneUtil.getLengthOfGeographicalAreaCode(number);
if (areaCodeLength > 0) {
  areaCode = nationalSignificantNumber.substring(0, areaCodeLength);
  subscriberNumber = nationalSignificantNumber.substring(areaCodeLength);
} else {
  areaCode = '';
  subscriberNumber = nationalSignificantNumber;
}

N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against using it for most purposes, but recommends using the more general nationalNumber instead. Read the following carefully before deciding to use this method:

  • geographical area codes change over time, and this method honors those changes; therefore, it doesn't guarantee the stability of the result it produces.
  • subscriber numbers may not be diallable from all devices (notably mobile devices, which typically requires the full national_number to be dialled in most regions).
  • most non-geographical numbers have no area codes, including numbers from non-geographical entities.
  • some geographical numbers have no area codes.

PhoneNumber number the PhoneNumber object for which clients want to know the length of the area code. @return {number} the length of area code of the PhoneNumber object passed in.

Implementation

int getLengthOfGeographicalAreaCode(PhoneNumber number) {
  String? regionCode = getRegionCodeForNumber(number);
  PhoneMetadata? metadata = getMetadataForRegion(regionCode: regionCode);
  if (metadata == null) return 0;

  // If a country doesn't use a national prefix, and this number doesn't have
  // an Italian leading zero, we assume it is a closed dialling plan with no
  // area codes.
  if (!metadata.hasNationalPrefix() && !number.italianLeadingZero) return 0;
  if (!isNumberGeographical(phoneNumber: number)) return 0;
  return getLengthOfNationalDestinationCode(number);
}