使用变量进行 Flutter 本地化

Kir*_*bel 6 dart flutter

我正在尝试按照文档本地化我的 Flutter 应用程序。

我想要实现的是,在动态构建小部件时,我想翻译来自我的模型的数据。这是我到目前为止所尝试过的

List.generate(services.length, (index) {
  final Service service = services[index];
  return Material(
    borderRadius: BorderRadius.circular(10.0),
    child: Text(
      AppLocalizations.of(context).{{service.title}} // Here I wanted to translate the service title
    ),
  );
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能在 Flutter 中实现这一目标?或任何其他可能的方法来翻译动态内容。

Mol*_*0ko 9

Flutter 本地化包不支持动态翻译。您可以尝试在您的应用程序中集成谷歌翻译API。但我坚信它应该是服务器端功能,并且 Flutter 客户端应该在模型中获取已翻译的消息。例如,为了实现此目的,您可以将 http-headers 与您的设备区域设置一起使用,以将客户端的语言告知服务器。

您还需要根据本指南使用 Intl 消息的参数。以下是带有字符串参数的消息示例AppLocalizations

  String someLocalizedString(String argument) => Intl.message(
        'Localized part - $argument',
        name: 'someLocalizedString',
        locale: localeName,
        args: [argument],
      );
Run Code Online (Sandbox Code Playgroud)

文件内的该字符串.arb

  "someLocalizedString": "Localized part - {argument}",
  "@someLocalizedString": {
    "type": "text",
    "placeholders": {
      "argument": {}
    }
  }
Run Code Online (Sandbox Code Playgroud)