0

我正在开发颤振应用程序,并且我有一个文本小部件,我想根据用户的位置显示用户当前的国家/地区代码,而无需任何下拉菜单。我正在使用区域设置获得像“IN”、“US”这样的值,但我不想要它,我需要像 +91(印度)、+1(美国)等数字国家代码。请任何人帮助我。

4

2 回答 2

0

您可以使用这些文件countries.dartcountry.dart从http
包 中获取用户国家代码http://ip-api.com/json,然后使用它从以下位置获取国家电话代码: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;
  }

我对此进行了测试,它对我有用,但您可以对其进行改进以避免 http 异常

于 2022-02-11T11:10:35.453 回答
0

您可以使用country_codes包:

安装:

dependencies:
  country_codes: ^2.0.1

用法:

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);
于 2022-02-11T10:18:52.723 回答