我正在尝试在 Flutter 中获取设备国家/地区(Android)。我用了本教程 https://flutter.dev/docs/development/accessibility-and-localization/internationalization,但我认为这对于我的问题来说是错误的方法。
Locale myLocale = Localizations.localeOf(context);
print(myLocale.languageCode.toString() + ' ' + myLocale.countryCode.toString());
基于此,我有几个问题:
- 我总是得到
en US
即使我已将设备语言设置为乌尔都语 - 巴基斯坦。那么我错过了什么?
- 我想根据设备所在的国家/地区显示某些应用程序项目,而不是根据语言,因为居住在巴基斯坦且语言设置为英语(美国)的人将获得实际上针对美国用户的项目。那么,我应该使用
geoLocation
并获取经度和纬度并根据该数据做出决定?或者是否有其他更简单的方法来获取用户所在的国家/地区?
期待中感谢。
如果您希望在不使用“地理定位器”的情况下获取设备所在国家/地区,这样您就不需要获得设备许可,可以使用以下代码:
Future<String> getCountry() async{
Network n = new Network("http://ip-api.com/json");
locationSTR = (await n.getData());
locationx = jsonDecode(locationSTR);
return locationx["country"];
}
网络类代码如下:
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
class Network {
final String url;
Network(this.url);
Future<String> apiRequest(Map jsonMap) async {
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/x-www-form-urlencoded');
request.add(utf8.encode(json.encode(jsonMap)));
HttpClientResponse response = await request.close();
// todo - you should check the response.statusCode
String reply = await response.transform(utf8.decoder).join();
httpClient.close();
return reply;
}
Future<String> sendData(Map data) async {
http.Response response = await http.post(url,
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode(data));
if (response.statusCode == 200)
return (response.body);
else
return 'No Data';
}
Future<String> getData() async {
http.Response response = await http.post(url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'});
if (response.statusCode == 200)
return (response.body);
else
return 'No Data';
}
}
您还可以获取城市和国家代码以及互联网提供商。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)