【问题标题】:Flutter: How use flutter_localizations in packageFlutter:如何在包中使用 flutter_localizations
【发布时间】:2022-12-15 18:30:33
【问题描述】:
我计划将一些常用功能/页面移动到“flutter package”
但是如何处理这些包中的本地化?
我试着按照步骤https://docs.flutter.dev/development/accessibility-and-localization/internationalization
但它似乎是应用程序级别的本地化,如何在子模块/包中添加本地化?
更新:
我试图在子模块中添加 flutter_intl / flutter_localizations ,让它像应用程序级别一样工作。
我还像这样在 localizationsDelegates 中添加模块委托
return MaterialApp(
localizationsDelegates: const [
S.delegate,
module_a.S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
], ...
测试后,结果如下:
- 它可以建造。
- 但它似乎没有使用子模块的翻译。在这种情况下它总是显示英语。
- 如果我将翻译项目从子模块复制到应用程序,它似乎可以工作。看起来应用程序翻译字符串将覆盖子模块的翻译字符串
我是否使用正确的方式在 flutter 子模块中实现翻译?
【问题讨论】:
标签:
flutter
package
localization
git-submodules
【解决方案1】:
我无法测试您的代码,但我希望这会有所帮助。
关于
- 但它似乎没有使用子模块的翻译。在这种情况下它总是显示英语。
正如 MaterialApp 的文档中所述:
/// * [supportedLocales], which must be specified along with
/// [localizationsDelegates].
如果我不指定 supportedLocales,我的应用程序只会以英文显示。
关于
- 如果我将已翻译的项目从子模块复制到应用程序,似乎可行。看起来应用程序翻译字符串将覆盖子模块翻译字符串
我认为您是对的,选择了第一个 S.type,在本例中为 S.delegate,因为 S.delegate 和 module_a.S.delegate 具有相同的 LocalizationsDelegate.type=S。
在 MaterialApp 的文档中可以找到类似的内容:
/// Constructing a [MaterialApp] with a `FooLocalizationsDelegate` overrides
/// the automatically included delegate for [MaterialLocalizations] because
/// only the first delegate of each [LocalizationsDelegate.type] is used and
/// the automatically included delegates are added to the end of the app's
/// [localizationsDelegates] list.
我将我的 flutter 项目拆分成不同的包,我选择的解决方案是为每个包(模块)生成一个单独的委托类。
模块 l10n.yaml 的示例:
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-class: moduleALocalizations
output-localization-file: module_a_localizations.dart
synthetic-package: false # important, if you want to import the delegate in another package or app
output-dir: lib/l10n/generated # this is optional, if synthetic-package=false and not stated, defaults to arb-dir location
我将 output-class 和 output-localization-file 设置为我想用于模块的类和文件名。像往常一样将委托添加到 [localizationsDelegates]。