【发布时间】:2020-04-11 23:35:00
【问题描述】:
【问题讨论】:
-
我认为您喜欢的解决方案是最好的方法。
-
试过了,但没有得到结果。:(
-
查看我下面的答案
标签: flutter flutter-dependencies
【问题讨论】:
标签: flutter flutter-dependencies
够了
WidgetsBinding.instance.window.locale.countryCode
【讨论】:
您可以使用系统语言环境。
final List<Locale> systemLocales = WidgetsBinding.instance.window.locales;
String isoCountryCode = systemLocales.first.countryCode;
【讨论】:
WidgetApp 的supportedLocales 中添加对每个国家/地区代码的明确支持。它只是检索系统的语言配置,而不需要 OP 所要求的 3rd 方插件。
您可以使用以下包devicelocale
在你的 pupspec.yaml 中添加依赖
dependencies:
devicelocale: ^0.2.1
在你想要的类中导入
import 'package:devicelocale/devicelocale.dart';
然后就可以通过下面的方式获取当前设备本地了
String locale = await Devicelocale.currentLocale;
【讨论】:
只需使用内置的Locale dart 类即可获取国家代码和语言。
Locale myLocale = Localizations.localeOf(context);
获取国家代码:
print(myLocale.countryCode);
获取语言代码:
print(myLocale.languageCode);
【讨论】:
你可以使用country_codes包:
安装:
dependencies:
country_codes: ^2.0.1
用法:
await CountryCodes.init(); // Optionally, you may provide a `Locale` to get countrie's localizadName
final Locale deviceLocale = CountryCodes.getDeviceLocale();
print(deviceLocale.languageCode); // Displays en
print(deviceLocale.countryCode); // Displays US
final CountryDetails details = CountryCodes.detailsForLocale();
print(details.alpha2Code); // Displays alpha2Code, for example US.
print(details.dialCode); // Displays the dial code, for example +1.
print(details.name); // Displays the extended name, for example United States.
print(details.localizedName); // Displays the extended name based on device's language (or other, if provided on init)
【讨论】:
你只需要写下面的代码。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
Locale myLocale = Localizations.localeOf(context);
print(myLocale.languageCode); //You can get locale here...
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
key: Key('counterKey'),
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
【讨论】: