'how to get country code like(+91 ,+1 etc) using user's current location flutter

I'm working on flutter app and I have a text widget where I want to show user's current country code based on his location without any dropdown. I'm getting value like "IN","US" using Locale, but I don't want it, I need numeric country code like +91 (for India), +1 (for US) etc. anyone help me please.



Solution 1:[1]

You can use country_codes package:

Install:

dependencies:
  country_codes: ^2.0.1

Usage:

await CountryCodes.init(); // Optionally, you may provide a `Locale` to get countrie's localizadName

final CountryDetails details = CountryCodes.detailsForLocale();
print(details.alpha2Code); // Displays alpha2Code, for example US.
print(details.dialCode); // Displays the dial code, for example +1.
print(details.name); // Displays the extended name, for example United States.
print(details.localizedName);

Solution 2:[2]

You can use these files countries.dart and country.dart
Get the user country code from http://ip-api.com/json with http package and then use it to get the country phone code from countryList:

 Future<String> getCountryPhoneCode() async {
    var response = await http.get(Uri.parse('http://ip-api.com/json'));
    var jsonResponse = json.decode(response.body);
    final isoCode = jsonResponse['countryCode'];
    print("country code " + isoCode);
    return "+" +
        countryList
            .firstWhere((element) => element.isoCode == isoCode,
                orElse: () => countryList.first)
            .phoneCode;
  }

I tested this and it works for me but you can improve it to avoid http exceptions

Sources

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

Source: Stack Overflow

Solution Source
Solution 1
Solution 2