Here we will learn how to use map inside map or created nested map in dart flutter. Map itself could be a little confusing for beginners in Dart. So map inside map is complex at first sight.
But it’s actually easy. First take a look at a Map object. What’s the format or syntax of basic map?
It’s Map<String, dynamic>
In general the key String and value is dynamic.
In our case we have to put Map inside Map, so we will replace the value dynamic with another Map.
Let’s see two json files.
First one en.json
{
"select_language": "Select Language",
"save": "Save",
"you_can_change_language": "You can change your language",
"select_a_language": "Select a language",
"home": "Home",
"back_to_home": "back to home"
}
Second one is bn.json
{
"select_language": "একটি ভাষা নির্বাচন করুন",
"save": "সংরক্ষণ",
"you_can_change_language": "আপনি আপনার ভাষা পরিবর্তন করতে পারেন",
"select_a_language": "একটি ভাষা নির্বাচন করুন",
"home": "প্রথম পৃষ্ঠা",
"back_to_home": "প্রথম পৃষ্ঠা ফিরে যাও"
}
If we want to put the above json files together in one Map object, then we need
Map<String, Map<String, String>>
See the code for this
Map<String, Map<String, String>> _languages = Map();
for(LanguageModel languageModel in AppConstants.languages) {
String jsonStringValues = await rootBundle.loadString('assets/language/${languageModel.languageCode}.json');
Map<String, dynamic> _mappedJson = json.decode(jsonStringValues);
Map<String, String> _json = Map();
_mappedJson.forEach((key, value) {
_json[key] = value.toString();
// print("${_json[key]}");
});
//en_US bn_BD
_languages['${languageModel.languageCode}_${languageModel.countryCode}'] = _json;
}
To create a map inside map, in the last line we created a new key. it’s more like en_US or bn_BD.
And inside those keys we put the en.json and bn.json file info.
It’s going to be end of mine day, but before finish I am reading this
fantastic piece of writing to increase my knowledge.
I’m not certain where you’re getting your info, but good topic.
I neewds to spend some time finding out more or woreking outt more.
Thanks for excellent info I used to be looking
for this info for my mission.