Flutter国际化插件split_intl的使用
Flutter国际化插件split_intl的使用
关于
当按照官方指南添加自定义本地化到您的应用时,您会接触到intl包。此包要求您在项目根目录创建一个配置文件,名为l10n.yaml
。通常,这个配置文件看起来像这样:
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
这基本上告诉生成器在目录lib/l10n
中查找本地化文件,并且模板文件名为app_en.arb
(有关更多信息,请参阅"Configuring the l10n.yaml file")。因此,生成器将查找lib/l10n/app_en.arb
并根据您在模板arb文件中指定的值生成名为app_localizations.dart
的dart文件。通过在lib/l10n
中添加更多具有不同语言代码(arb文件名称末尾的两个字符)的文件,您可以为您的应用程序添加更多本地化,例如app_de.arb
用于德语。
但是,通过这种模式,您很快会发现将所有语言的本地化放入单个文件中会极大地降低该文件的可读性。此外,无法向.arb
或.json
文件添加注释也未必有帮助。
这就是split_intl
插件的作用所在。split_intl
允许您:
- 将单个
.arb
文件拆分为多个.arb
、.json
或.jsonc
文件。 - 向您的本地化文件中添加注释(通过使用
.jsonc
格式)。
如何使用split_intl
没有split_intl
时,您的项目结构可能看起来像这样:
📦my_localized_flutter_app
┣ 📂lib
┃ ┣ 📂l10n
┃ ┃ ┗ 📜app_en.arb
┃ ┗ 📜main.dart
┣ 📂linux
┣ 📂test
┣ 📂windows
┣ 📜.gitignore
┣ 📜.metadata
┣ 📜analysis_options.yaml
┣ 📜l10n.yaml
┣ 📜pubspec.lock
┗ 📜pubspec.yaml
并且lib/l10n/app_en.arb
的内容可能如下所示:
{
"appTitle": "The best app",
"@appTitle": {
"description": "The title of the application."
},
"fieldRequired": "required",
"@fieldRequired": {
"description": "The message for a field that requires user input (cannot be empty)."
},
"inputFormOptionsPageTitle": "Add",
"@inputFormOptionsPageTitle": {
"description": "The title for the OptionsPage in the InputFormView widget."
},
"inputFormPanelPageTitle": "Input values",
"@inputFormPanelPageTitle": {
"description": "The title for the PanelPage in the InputFormView widget."
}
}
但通过使用split_intl
,您可以更改结构以使其看起来像这样:
📦my_localized_flutter_app
┣ 📂lib
┃ ┣ 📂l10n
┃ ┃ ┗ 📂en
┃ ┃ ┃ .jsonc
┃ ┃ ┃ general.arb
┃ ┃ ┗ input_form_panel.jsonc
┃ ┗ 📜main.dart
┣ 📂linux
┣ 📂test
┣ 📂windows
┣ 📜.gitignore
┣ 📜.metadata
┣ 📜analysis_options.yaml
┣ 📜l10n.yaml
┣ 📜pubspec.lock
┗ 📜pubspec.yaml
lib/l10n/en/.jsonc
的内容如下:
{
// 这是一个注释。
"fieldRequired": "required",
"@fieldRequired": {
"description": "The message for a field that requires user input (cannot be empty)."
}
}
lib/l10n/en/general.arb
的内容如下:
{
"appTitle": "The best app",
"@appTitle": {
"description": "The title of the application."
},
}
lib/l10n/en/input_form_view.jsonc
的内容如下:
{
// 所有值都由InputFormView小部件使用
"inputFormOptionsPageTitle": "Add",
"@inputFormOptionsPageTitle": {
"description": "The title for the OptionsPage in the InputFormView widget."
},
/*
我喜欢块注释
*/
"inputFormPanelPageTitle": "Input values",
"@inputFormPanelPageTitle": {
"description": "The title for the PanelPage in the InputFormView widget."
}
/**
* 我真的非常喜欢它们
*/
}
split_intl
只是将lib/l10n/en
中的所有文件合并在一起,并去除所有注释。要添加更多语言,只需添加一个新目录,其名称为语言代码,如lib/l10n/de
。生成的文件将输出到lib/l10n
中,例如lib/l10n/en
-> lib/l10n/app_en.arb
。要做到这一点,您只需要运行:
flutter pub run split_intl:generate
此命令生成lib/l10n/app_en.arb
文件,该文件可以被
flutter gen-l10n
更多关于Flutter国际化插件split_intl的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html