flutter - Flutter 中的设备国家
问题描述
我正在尝试在 Flutter 中获取设备所在国家/地区(Android)。我使用了本教程,但我认为这是解决我的问题的错误方法。
Locale myLocale = Localizations.localeOf(context);
print(myLocale.languageCode.toString() + ' ' + myLocale.countryCode.toString());
基于此,我有几个问题/问题:
en US
即使我已将设备语言设置为乌尔都语 - 巴基斯坦,我总是会得到。那么我错过了什么?- 我想根据设备所在的国家/地区显示某些应用程序项目,而不是基于语言,因为居住在巴基斯坦且语言设置为英语(美国)的人将获得实际针对美国用户的项目。那么,我应该使用
geoLocation
并获取经度和纬度并根据该数据做出决定吗?或者有没有其他更简单的方法来获取用户国家?
期待中的感谢。
解决方案
将这 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
}