parsePhoneNumber method

Future<Map<String, String>> parsePhoneNumber(
  1. String phoneNumber
)

Implementation

Future<Map<String, String>> parsePhoneNumber(String phoneNumber) async {
  try {
    // Check if the phone number starts with a '+'
    if (!phoneNumber.startsWith('+')) {
      phoneNumber = '+$phoneNumber'; // Ensure it starts with '+'
    }

    // Parse the phone number
    PhoneNumber parsedNumber =
        await PhoneNumber.getRegionInfoFromPhoneNumber(phoneNumber);
    // Extract the country code and the national number
    String countryCode = parsedNumber.dialCode ?? '';
    String nationalNumber = parsedNumber.phoneNumber ?? '';

    return {
      'countryCode': countryCode,
      'number': nationalNumber
          .replaceFirst(countryCode, '')
          .trim(), // Remove country code from the number
    };
  } catch (e) {
    print('Error parsing phone number: $e');
    return {
      'countryCode': '',
      'number': '',
    };
  }
}