在 GetX 中使用 JSON 文件进行本地化

发布于 2025-01-09 15:19:36 字数 832 浏览 1 评论 0原文

我正在尝试阅读翻译文件,例如。 en.json 用于 GetX 本地化。我尝试了以下代码但没有成功。有更好的方法吗?有人建议将 auto_localize 与 GetX 一起使用,但如果我可以在没有额外软件包的情况下继续进行,我将非常

  Map<String, Map<String, String>> get keys => {
        "ar": readJson("ar"),
        "en": readJson("en"),
}

感激尝试使用以下函数 DebugPrint() 加载本地化信息

 // Fetch content from the json file
  Map<String, String> readJson(String languageCode) {
    Map data = {};
    rootBundle
        .loadString('assets/translations/$languageCode.json')
        .then((response) {
      data = json.decode(response);
    });
    return data.map((key, value) {
      return MapEntry(key, value.toString());
    });
  }

,显示文件已成功加载。但是,尝试显示加载的地图不起作用

I am trying to read translation files eg. en.json to use with GetX localization. I tried the following code but no success. Is there any better way of doing it? Somebody suggested using auto_localize with GetX, but I'll really appreciate if I can proceed without an extra package

  Map<String, Map<String, String>> get keys => {
        "ar": readJson("ar"),
        "en": readJson("en"),
}

I tried loading the localization information using the following function

 // Fetch content from the json file
  Map<String, String> readJson(String languageCode) {
    Map data = {};
    rootBundle
        .loadString('assets/translations/$languageCode.json')
        .then((response) {
      data = json.decode(response);
    });
    return data.map((key, value) {
      return MapEntry(key, value.toString());
    });
  }

DebugPrint() gets shows that the files were successfully loaded. However, trying to display the loaded Maps doesn't work

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

金兰素衣 2025-01-16 15:19:36

readJson 应该是 Future,因此最后返回空 Map。

方式

  • 我创建 languages.json 文件并将所有文本放入其中的
[
  {
    "name": "English",
    "code": "en_US",
    "texts": {
      "hello": "Hello World"
    }
  },
  {
    "name": "Arabic",
    "code": "ar_AE",
    "texts": {
      "hello": "مرحبا بالعالم"
    }
  }
]
  • 。像这样实现本地化类
class LocalizationService extends Translations {

  @override
  Map<String, Map<String, String>> get keys => {};

  static Future<void> initLanguages() async {
    final _keys = await readJson();
    Get.clearTranslations();
    Get.addTranslations(_keys);
  }

  static Future<Map<String, Map<String, String>>> readJson() async {
    final res = await rootBundle.loadString('assets/languages.json');
    List<dynamic> data = jsonDecode(res);
    final listData = data.map((j) => I18nModel.fromJson(j)).toList();
    final keys = Map<String, Map<String, String>>();
    listData.forEach((value) {
      final String translationKey = value.code!;
      keys.addAll({translationKey: value.texts!});
    });
    return keys;
  }
}

正如您在获取地图数据后所看到的,我使用 Get.addTranslations(); 设置语言键。
这是一个 GetX 函数,用于在广播中添加语言!

  • 创建模型类来解析 json 数据
class I18nModel {
  String? name;
  String? code;
  Map<String, String>? texts;

  I18nModel(
      {this.name, this.code, this.texts});

  I18nModel.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    code = json['code'];
    if (json['texts'] != null) {
      texts = Map<String, String>.from(json['texts']);
    }
  }
}
  • 最后在进入第一个路由之前调用 await LocalizationService.initLanguages();

The readJson should be Future and because of that the empty Map returned at the end.

The way i did

  • create languages.json file and put all texts to it.
[
  {
    "name": "English",
    "code": "en_US",
    "texts": {
      "hello": "Hello World"
    }
  },
  {
    "name": "Arabic",
    "code": "ar_AE",
    "texts": {
      "hello": "مرحبا بالعالم"
    }
  }
]
  • implement localization class like this
class LocalizationService extends Translations {

  @override
  Map<String, Map<String, String>> get keys => {};

  static Future<void> initLanguages() async {
    final _keys = await readJson();
    Get.clearTranslations();
    Get.addTranslations(_keys);
  }

  static Future<Map<String, Map<String, String>>> readJson() async {
    final res = await rootBundle.loadString('assets/languages.json');
    List<dynamic> data = jsonDecode(res);
    final listData = data.map((j) => I18nModel.fromJson(j)).toList();
    final keys = Map<String, Map<String, String>>();
    listData.forEach((value) {
      final String translationKey = value.code!;
      keys.addAll({translationKey: value.texts!});
    });
    return keys;
  }
}

As you see after getting the Map data, i used Get.addTranslations(); to set language keys.
this is a GetX function to add languages on air!

  • create model class to parse json data
class I18nModel {
  String? name;
  String? code;
  Map<String, String>? texts;

  I18nModel(
      {this.name, this.code, this.texts});

  I18nModel.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    code = json['code'];
    if (json['texts'] != null) {
      texts = Map<String, String>.from(json['texts']);
    }
  }
}
  • And finally call await LocalizationService.initLanguages(); before going to your first Route.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文