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

7.1k Views Asked by At

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.

3

There are 3 best solutions below

1
Rohith Nambiar On

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);
3
Youssef Elmoumen On

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

0
Mohamed Hamzaoui On

If you have any country code and wants to get corresponding country name, use country_picker package like this

Country.tryParse(countryCode)?.name; // for name in english
Country.tryParse(countryCode)?.phoneCode; // for phone code