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

Flutter中使用easy_localization实现列表项本地化的最优方案

处理Flutter easy_localization列表本地化的方案

你提到的问题确实存在——easy_localization默认更偏向字符串键值对的翻译,但可以通过两种方式实现直接从JSON生成本地化Person列表,或者优化现有方案:

方案1:直接在JSON中存储本地化后的完整Person列表

如果你的Person列表内容固定,可以直接把本地化后的列表写入翻译文件,再手动解析成Dart对象:

翻译文件示例(en.json)

{
  "persons": [
    {"name": "Alice", "profession": "Software Engineer", "age": "24 years old"},
    {"name": "Bob", "profession": "UI/UX Designer", "age": "26 years old"}
  ]
}

Dart中解析代码

import 'package:easy_localization/easy_localization.dart';

// 定义Person类
class Person {
  final String name;
  final String profession;
  final String age;

  Person({required this.name, required this.profession, required this.age});

  factory Person.fromJson(Map<String, dynamic> json) => Person(
        name: json['name'],
        profession: json['profession'],
        age: json['age'],
      );
}

// 获取本地化后的Person列表
List<Person> getLocalizedPersons(BuildContext context) {
  // 从easy_localization的翻译数据中取出数组
  final personsJson = EasyLocalization.of(context)!.translations['persons'] as List;
  return personsJson.map((json) => Person.fromJson(json)).toList();
}

这种方式适合静态列表,无需在Dart中硬编码列表结构,直接从翻译文件读取本地化后的内容。

方案2:存储键列表+动态翻译(复用现有翻译项)

如果需要复用professions、age这类公共翻译项,可以在JSON中存储Person的键标识,再动态生成本地化列表:

翻译文件示例(en.json)

{
  "person_keys": [
    {"name_key": "a", "prof_key": "xxx", "age_key": "24"},
    {"name_key": "b", "prof_key": "yyy", "age_key": "21"}
  ],
  "names": {
    "a": "Alice",
    "b": "Bob"
  },
  "professions": {
    "xxx": "Software Engineer",
    "yyy": "UI/UX Designer"
  },
  "age": {
    "24": "24 years old",
    "21": "21 years old"
  }
}

Dart中生成代码

List<Person> getLocalizedPersons(BuildContext context) {
  final personKeys = EasyLocalization.of(context)!.translations['person_keys'] as List;
  
  return personKeys.map((item) {
    return Person(
      name: 'names.${item['name_key']}'.tr(),
      profession: 'professions.${item['prof_key']}'.tr(),
      age: 'age.${item['age_key']}'.tr(),
    );
  }).toList();
}

这种方式的优势是翻译项可复用,比如多个Person共享同一个职业翻译,修改时只需要改一处。

注意事项

  • 确保使用的easy_localization版本支持直接访问完整翻译数据(部分版本需用translations而非data);
  • 修改JSON翻译文件后,可能需要重启App才能生效(热重载可能无法识别JSON结构变化);
  • 如果Person列表是动态生成的(比如从接口获取),可以结合方案2,把接口返回的键值传入tr()方法完成本地化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:05:43