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.
how to get country code like(+91 ,+1 etc) using user's current location flutter
7.1k Views Asked by RahulZx At
3
There are 3 best solutions below
3
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
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
You can use country_codes package:
Install:
Usage: