首页 > 解决方案 > Flutter 中的设备国家

问题描述

我正在尝试在 Flutter 中获取设备所在国家/地区(Android)。我使用了本教程,但我认为这是解决我的问题的错误方法。

Locale myLocale = Localizations.localeOf(context);
print(myLocale.languageCode.toString() + ' ' + myLocale.countryCode.toString());

基于此,我有几个问题/问题:

期待中的感谢。

标签: fluttercountry-codes

解决方案


将这 2 个库添加到pubspec.yaml

geolocator: ^5.1.1
geocoder: ^0.2.1

然后添加Location访问权限。在这里检查

最后在你想要的地方调用这个方法。

Future<String> getCountryName() async {
    Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    debugPrint('location: ${position.latitude}');
    final coordinates = new Coordinates(position.latitude, position.longitude);
    var addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
    var first = addresses.first;
    return first.countryName; // this will return country name
}

推荐阅读