'Format users' contacts' phone numbers - Flutter

I am building a chat application that takes a user's phone number with a country code for registration. After registration and permission, I use the contacts_service plugin to access the contacts on the local device. Then I go through the phone numbers to check if any of those numbers are already registered on my chat app so that I can show the in-app contacts.

The issue I am facing is that the local phone numbers could be found in many different formats, some have country codes and others do not, etc. Whereas, during the registration process I take the country code with the phone number. So let's suppose a phone number does not start with a country code but instead has a "0" at the start. How can I know which country does this phone number belong to?

Currently, I am using this method to format the phone numbers but it is not very efficient. When I do not find the country code for a phone number, I just append the country code of the device with that phone number.

Future<String> formatPhoneNumber(String number) async {
  number = number.replaceAll(" ", "");
  number = number.replaceAll("-", "");
  number = number.replaceAll("(", "");
  number = number.replaceAll(")", "");
  if (number[0] != "+") {
    /// number is not starting with '+'
    String code = await PhoneNumberUtil().carrierRegionCode(); // get country code
    code = code.toUpperCase();
    if (number[0] == "0") {
      /// starts with '0'
      /// replace '0' with users country code
      number = number.substring(1);
      int countryIndex = CountryCodes.countries
          .indexWhere((element) => element["code"] == code);
      if (countryIndex >= 0) {
        number = CountryCodes.countries[countryIndex]["dial_code"] + number;
      }
    } else {
      if (number.length <= 10) {
        /// number is without '+', '0'  and country code
        int countryIndex = CountryCodes.countries
            .indexWhere((element) => element["code"] == code);
        if (countryIndex >= 0) {
          number = CountryCodes.countries[countryIndex]["dial_code"] + number;
        }
      } else {
        /// numbers is starting with a country code
        number = "+" + number;
      }
    }
    try {
      PhoneNumber formattedNumber =
          await PhoneNumberUtil().parse(number, regionCode: code);
      return formattedNumber.e164;
    } catch (e) {
      log("Error: $e");
    }
  }
  return number;
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source