Roc*_*ock 2 internationalization flutter
我有一个问题,如何检测设备语言,并据此在应用程序最初启动时给出正确的语言?如果可能,请提供带有代码的示例。
调用Localizations.localeOf(context).languageCode应该返回您的语言代码。如果未提供,MaterialApp 将创建并使用默认本地化,然后您可以在 MaterialApp 之后调用它,以了解设备当前使用的语言,并使用您的州管理人员使用该信息更新您的应用程序。
对于一个简单的项目,我的建议是在 VS IDE 中使用这个插件(或者在 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
Run Code Online (Sandbox Code Playgroud)
在 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(),
);
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以在 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
}
}
Run Code Online (Sandbox Code Playgroud)
如果设备使用的是您不支持的语言(在我的例子中是法语),它将使用该类的默认语言 en('英语),如果您想使用另一种语言作为默认语言,请检查 pubspec 中的 main_locale
如果您想尝试不同的东西,请查看此示例,了解如何使用 JSON 键进行国际化。
| 归档时间: |
|
| 查看次数: |
7934 次 |
| 最近记录: |