Flutter 中的设备国家/地区

Ale*_*eem 11 country-codes flutter

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

Locale myLocale = Localizations.localeOf(context);
print(myLocale.languageCode.toString() + ' ' + myLocale.countryCode.toString());
Run Code Online (Sandbox Code Playgroud)

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

  • en US即使我将设备语言设置为乌尔都语 - 巴基斯坦,我也总是收到。那么我错过了什么?
  • 我想根据设备所在的国家/地区显示某些应用项目,而不是基于语言,因为居住在巴基斯坦且语言设置为英语(美国)的人将获得实际面向美国用户的项目。那么,我应该使用geoLocation并获取经度和纬度并根据该数据做出决定吗?或者有没有其他更简单的方法来获取用户所在的国家/地区?

期待中的感谢。

Rah*_*rma 11

将这 2 个库添加到 pubspec.yaml

geolocator: ^5.1.1
geocoder: ^0.2.1
Run Code Online (Sandbox Code Playgroud)

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

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

geolocator: ^5.1.1
geocoder: ^0.2.1
Run Code Online (Sandbox Code Playgroud)

  • @DarkNeuron 我来自印度,我在我的设备中使用美国英语。我将从你的方法中获得 en_US,并从我的方法中获得 India。 (3认同)
  • 我提出三个小评论。1. 不要再在 Dart 中使用 `new` 了。2. 更简单的“location”插件也可以工作,并且(截至撰写本文时)也可以在网络上运行。3.国内确实没必要要求太高的精度,可以要求最低的,省电。 (2认同)

Cen*_*MUR 5

尝试这个

import 'dart:io' show Platform;

String localeName = Platform.localeName;
Run Code Online (Sandbox Code Playgroud)

  • 它给了我en_us。这是操作系统中使用的语言,而不是国家/地区 (3认同)
  • locale 始终是 language_countryname,您可以只提取 iso 国家/地区名称 (2认同)

Mal*_*aht 5

如果您想在不使用“地理定位器”的情况下获取设备国家/地区,因此您不需要获得设备许可,您可以使用以下代码:

  Future<String> getCountry() async{
  Network n = new Network("http://ip-api.com/json");
  locationSTR = (await n.getData());
  locationx = jsonDecode(locationSTR);
  return locationx["country"];
}
Run Code Online (Sandbox Code Playgroud)

网络类代码如下:

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';
  }
}
Run Code Online (Sandbox Code Playgroud)

您还可以获得城市和国家/地区代码以及互联网提供商。

  • 根据他们的网站,您这样做是违反他们的使用条款“免费用于非商业用途”。如果它有效,并不意味着您允许使用它。所以要小心 (3认同)

chu*_*han 0

请使用包https://pub.dev/packages/devicelocale
我已经用真实设备进行了测试,它工作正常

代码片段

String locale = await Devicelocale.currentLocale;
Run Code Online (Sandbox Code Playgroud)

完整代码

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:devicelocale/devicelocale.dart';

void main() => runApp(MyApp());

/// Demo getting a device locale
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List _languages = List();
  String _locale;

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    List languages;
    String currentLocale;

    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      languages = await Devicelocale.preferredLanguages;
      print(languages);
    } on PlatformException {
      print("Error obtaining preferred languages");
    }
    try {
      currentLocale = await Devicelocale.currentLocale;
      print(currentLocale);
    } on PlatformException {
      print("Error obtaining current locale");
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _languages = languages;
      _locale = currentLocale;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              Text("Current locale: "),
              Text('$_locale'),
              Text("Preferred Languages: "),
              Text(_languages.toString()),

            ],
          )
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案未按要求提供国家/地区代码。 (3认同)