formatAsPhoneNumber function

String? formatAsPhoneNumber(
  1. String phone, {
  2. InvalidPhoneAction invalidPhoneAction = InvalidPhoneAction.ShowUnformatted,
  3. bool allowEndlessPhone = false,
  4. String? defaultMask,
  5. String? defaultCountryCode,
})

allowEndlessPhone if this is true, the

Implementation

String? formatAsPhoneNumber(
  String phone, {
  InvalidPhoneAction invalidPhoneAction = InvalidPhoneAction.ShowUnformatted,
  bool allowEndlessPhone = false,
  String? defaultMask,
  String? defaultCountryCode,
}) {
  if (!isPhoneValid(
    phone,
    allowEndlessPhone: allowEndlessPhone,
    defaultCountryCode: defaultCountryCode,
  )) {
    switch (invalidPhoneAction) {
      case InvalidPhoneAction.ShowUnformatted:
        if (defaultMask == null) return phone;
        break;
      case InvalidPhoneAction.ReturnNull:
        return null;
      case InvalidPhoneAction.ShowPhoneInvalidString:
        return 'invalid phone';
      case InvalidPhoneAction.DoNothing:
        break;
    }
  }
  phone = toNumericString(
    phone,
    errorText: null,
    allowAllZeroes: true,
  );
  PhoneCountryData? countryData;
  if (defaultCountryCode != null) {
    countryData = PhoneCodes.getPhoneCountryDataByCountryCode(
      defaultCountryCode,
    );
  } else {
    countryData = PhoneCodes.getCountryDataByPhone(
      phone,
    );
  }

  if (countryData != null) {
    return _formatByMask(
      phone,
      countryData.getCorrectMask(defaultCountryCode),
      countryData.getCorrectAltMasks(defaultCountryCode),
      0,
      allowEndlessPhone,
    );
  } else {
    return _formatByMask(
      phone,
      defaultMask!,
      null,
      0,
      allowEndlessPhone,
    );
  }
}