我有一个博客应用程序,我可以在其中编写全球业务内容以及一些特定国家/地区的内容。喜欢印度、印度尼西亚等的特别帖子
这就是为什么我需要一种方法来查找用户要从哪个国家/地区提供特定内容。
但是,我不想使用 GeoLocator 插件,因为它会询问 用户获取位置。我只想要用户的国家/地区,而不是具体的 位置,但权限对话框没有指定可以使 用户担心为什么这个应用程序需要位置权限。那是 为什么我想要一种无需隐式许可即可获取用户国家/地区的方法 对话框询问他们的位置。
我尝试了以下方法,但都没有给出确切的国家名称。
import 'dart:io' show Platform;
String localeName = Platform.localeName;
// this returns language device is using which mostly comes us en_US so this is of no use
Locale myLocale = Localizations.localeOf(context);
// This returned the US as the country despite the App being opened and used in India.
好吧,我终于找到了一种简单易行的方法来获取用户的国家/地区。
此链接以 JSON 格式返回用户的位置。因此,现在要做的就是向上述链接/API 发出 Get 请求并将 JSON 解码为 Map。
对于首次安装 HTTP 软件包:
Pubspec.yaml:
dependencies:
http:
代码:
import 'package:http/http.dart' as http;
import 'dart:convert';
Response data = await http.get('http://ip-api.com/json');
Map data = jsonDecode(data.body);
String country = data['country'];
编辑: 正如好心人所说,
Free Version Limit is 45 HTTP requests per second from an IP address.
区域设置为您提供设备用户设置的语言。它不一定表明他们的出生国。它绝对不会告诉您他们的居住国。在许多情况下,该人可能位于语言代码所在的国家/地区,但这并不能保证。了解他们所在位置的唯一方法是通过位置。
更新 关于您的评论。如果您想根据从设备区域设置获得的语言代码从哪里获取国家/地区名称,请查看这篇文章。我自己还没有尝试过,但看起来很有希望。 https://dev.to/thealphamerc/get-search-filter-countries-data-using-countryprovider-flutter-plugin-1epc
试试这个
import 'dart:io' show Platform;
String localeName = Platform.localeName
或者试试这个
请使用包devicelocale 我已经用真机测试过,效果很好
代码片段
String locale = await Devicelocale.currentLocale;