gpt4 book ai didi

Flutter 国际化 : How to access to nested data in json

转载 作者:行者123 更新时间:2023-12-04 14:15:10 24 4
gpt4 key购买 nike

我想知道如何访问 json 中的嵌套数据。

AppLocalizations.of(context).translate('Information.about');
en.json
{  
"Information" : {
"about": "About"
}

}

我像上面那样尝试过,但它无法访问嵌套数据。

这是翻译方法。
  class AppLocalizations {
final Locale locale;

AppLocalizations(this.locale);

static AppLocalizations of(BuildContext context) {
return Localizations.of<AppLocalizations>(context, AppLocalizations);
}

// Static member to get access to the delegate from 'main.dart' file
static const LocalizationsDelegate<AppLocalizations> delegate = _AppLocalizationsDelegate();

Map<String, String> _localizedValues;

Future<bool> load() async {
// Load a language JSON file from the 'i18n' folder
String value = await rootBundle.loadString('i18n/${locale.languageCode}.json');
Map<String, dynamic> jsonMap = jsonDecode(value);
_localizedValues = jsonMap.map((key, value) {
return MapEntry(key, value.toString());
});
return true;
}

String translate(String key) {
// Returns a localized text
return _localizedValues[key];
}
}

最佳答案

尝试这个:

第一种方法:

AppLocalizations.of(context).translate(“about”);

并将您的翻译功能更改为:
  String translate(String key) {
// Returns a localized text
return _localizedValues[“Information”][key];
}

或者你可以这样做:

第二种方法:
AppLocalizations.of(context).translate(”Information”,“about”);

并将您的翻译功能更改为:
 String translate(String parentkey, String nestedKey) {
// Returns a localized text
return _localizedValues[parentKey][nestedKey];
}

This可能有帮助。

另外, This是一篇学习如何解析复杂json文件的好文章

更新的答案:

尝试代码后,我可以理解问题所在。

问题是您的 _localizedValues["Information"] 将是字符串而不是 map ,因为我们将值转换为 value.toString(),这就是您不能使用第二个键的原因,因为返回的对象不是 map 而是字符串。

所以 _localizedValues["Information"] 是“{about: About}”。

要解决问题,请使用以下代码:
  Map<String, dynamic> _localizedValues; //your values are not String anymore and we use dynamic instead
Future<bool> load() async {
// Load a language JSON file from the 'i18n' folder
String value = await rootBundle.loadString('i18n/${locale.languageCode}.json');
Map<String, dynamic> jsonMap = jsonDecode(value);
_localizedValues = jsonMap.map((key, value) {
return MapEntry(key, value); //not value.toString() so the value will be a map
});
return true;
}
String translate(String parentkey, String nestedKey) {
// Returns a localized text
return _localizedValues[parentKey][nestedKey];
}

然后你必须从下面的代码中获取“关于”:
AppLocalizations.of(context).translate('Information','about');

关于Flutter 国际化 : How to access to nested data in json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60915140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com