Calling Localizations.localeOf(context).languageCode
应该返回你的语言代码。如果未提供,MaterialApp 将创建并使用默认本地化,然后您可以在 MaterialApp 之后调用它,以了解设备当前使用的语言,并使用您的州管理人员使用该信息更新您的应用程序。
我对一个简单项目的建议是使用这个对于 VS IDE(或this https://plugins.jetbrains.com/plugin/13666-flutter-intl对于 Android Studio,它来自同一作者)。安装后只需将依赖项添加到 pubspec.yaml 中
dependencies:
// Other dependencies...
flutter_localizations:
sdk: flutter
...
flutter_intl:
enabled: true
class_name: S # Optional. Sets the name for the generated localization class. Default: S
main_locale: en # Optional. Sets the main locale used for generating localization files. Provided value should comply with ISO-639-1 and ISO-3166-1 (e.g. "en", "en_GB"). Default: en
在 Android Studio 中(我真的不知道在 VS 中哪里,抱歉)检查Tools > Flutter intl
(它应该在最后),您可以在那里初始化您的项目并添加区域设置。您的项目中现在应该有一个文件夹lib/l10n
对于 arb 文件,它们看起来像 JSON 文件,只需添加一个带字符串的键。为您想要的每种语言环境创建一个,并为它们提供每种语言的字符串参数
intl_en.arb
{
"name": "我有一个名字"
}
intl_es.arb
{
“name”:“Yo tengo un Nombre”
}
它应该自动运行构建。之后创建您的Material App并委托S(将生成的代码的名称,如果需要,您可以稍后更改名称)。
import 'package:flutter_localizations/flutter_localizations.dart';
import 'generated/l10n.dart';
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
localizationsDelegates: [
S.delegate, //The class S
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: S.delegate.supportedLocales,
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
现在您可以在 Widget 树中使用它
class MyHomePage extends StatelessWidget{
@override
Widget build(BuildContext context){
return Text(S.of(context).name)
// now it prints the string of name depending the language the device is
}
}
如果设备使用的是您不支持的语言(在我的例子中是法语),它将使用该类的默认语言 en('英语),如果您想使用另一种语言作为默认语言,请检查 pubspec 中的 main_locale
检查这个Example https://medium.com/flutter-community/flutter-internationalization-the-easy-way-using-provider-and-json-c47caa4212b2如果您想尝试不同的东西,如何使用 JSON 键进行国际化。