You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter枚举国际化实现:能否用标准i18n?求推荐合适插件

Flutter枚举遍历与本地化实现方案

可以用Flutter标准i18n实现枚举值的遍历与翻译输出,也可以借助第三方插件简化流程,具体方案如下:

一、使用Flutter标准i18n实现

  1. 先将你的枚举定义为Dart标准枚举:
enum ItemType { typeA, typeB, typeC }
  1. 在本地化arb文件中添加对应翻译条目:
    比如英文资源文件app_en.arb:
{
  "typeA": "Type A",
  "typeB": "Type B",
  "typeC": "Type C"
}

中文资源文件app_zh.arb:

{
  "typeA": "类型A",
  "typeB": "类型B",
  "typeC": "类型C"
}
  1. 给枚举添加扩展方法,映射到对应的翻译键:
extension ItemTypeLocalization on ItemType {
  String get translationKey {
    switch (this) {
      case ItemType.typeA:
        return 'typeA';
      case ItemType.typeB:
        return 'typeB';
      case ItemType.typeC:
        return 'typeC';
    }
  }
}
  1. 遍历枚举并输出翻译内容:
    在使用本地化上下文的Widget中,通过AppLocalizations获取翻译:
for (final type in ItemType.values) {
  print(AppLocalizations.of(context)!.translate(type.translationKey));
}

这种方式需要手动维护枚举与翻译键的映射,但完全基于Flutter官方i18n体系,不需要额外依赖。

二、推荐第三方插件:easy_localization

如果觉得手动映射繁琐,可以使用easy_localization插件,它提供了更简洁的枚举本地化支持:

  1. 配置好插件后,给枚举添加本地化注解:
enum ItemType {
  @LocaleKey('typeA')
  typeA,
  @LocaleKey('typeB')
  typeB,
  @LocaleKey('typeC')
  typeC
}
  1. 同样在arb文件中添加对应翻译条目(和标准i18n的写法一致)。

  2. 直接通过插件提供的方法获取翻译并遍历:

for (final type in ItemType.values) {
  print(type.tr());
}

该插件还支持自动生成本地化代码,进一步减少手动维护成本,适合枚举较多或频繁修改的场景。

内容的提问来源于stack exchange,提问作者user1117605

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 12:52:11