Dart:无法访问嵌套的地图对象 [英] Dart: Can't access to nested map object
问题描述
我正在创建Flutter应用程序,但无法访问 dart
中的嵌套地图对象。
我的代码如下。
I am creating a Flutter application and I can't access to nested map object in dart
.
My code is as below.
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 parent, String key) {
// Returns a localized text
return _localizedValues[parent][key];
}
发生错误 [key]
这部分。它说
不能将参数类型'String'分配给参数类型'int'。
The argument type 'String' can't be assigned to the parameter type 'int'.
JSON文件就是这样。
JSON file is like this.
{
"Parent": {
"key": "key"
}
}
这有什么问题?
推荐答案
我将针对此问题提出另一种解决方案更方便您使用。
您可以在使用多维json对象之前先对其进行展平。
I will propose a different solution to this problem that might be easier for you to work with. You can simply flatten the multidimensional json object before working with it.
Map<String, String> _localizedValues;
Map flattenTranslations(Map<String, dynamic> json, [String prefix = '']) {
final Map<String, String> translations = {};
json.forEach((String key, dynamic value) {
if (value is Map) {
translations.addAll(flattenTranslations(value, '$prefix$key.'));
} else {
translations['$prefix$key'] = value.toString();
}
});
return translations;
}
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 = flattenTranslations(jsonMap);
return true;
}
您将获得一个简单的Map对象,其中包含json的所有键
You will get a simple Map object that will contain all the keys of your json with every subtree key prefixed by their parent's key.
例如:
{
"Parent": {
"key": "key",
"key1": "key",
"key2": "key",
"key3": "key",
"someOtherKey": {
"key213": "keyeye",
"oneMoreLevel": {
"key123412": "asdasdasd"
}
}
}
}
将转换为包含 Parent.someOtherKey.oneMoreLevel.key123412键的地图。
之后,您可以使用此函数获取翻译:
Will convert to a map with "Parent.someOtherKey.oneMoreLevel.key123412" key included. After this you can use this function to get the translation:
String translate(String key) {
// Returns a localized text or KEY if there's no localization
return _localizedValues[key] ?? key;
}
print(translate('Parent.someOtherKey.oneMoreLevel.key123412'));
这篇关于Dart:无法访问嵌套的地图对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!