How to read nested json in flutter localization?
Here is my working solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class AppLocalizations { final Locale locale; static const LocalizationsDelegate<AppLocalizations> delegate = _AppLocalizationsDelegate(); AppLocalizations(this.locale); static AppLocalizations of(BuildContext context) { return Localizations.of<AppLocalizations>(context, AppLocalizations); } Map<String, dynamic> _localizeStrings; Future<bool> load() async { String jsonString = await rootBundle.loadString('lang/${locale.languageCode}.json'); Map<String, dynamic> jsonMap = json.decode(jsonString); _localizeStrings = jsonMap.map((key, value) { return MapEntry(key, value); }); return true; } String translate(String key) { var nestedMap = _getNestedValue(key); return nestedMap.toString(); } dynamic _getNestedValue(String keyPath) { Map keyMap = keyPath.split('.').asMap(); var nestedMap; keyMap.forEach((index, key) { if (index == 0) { nestedMap = _localizeStrings[key]; } else nestedMap = nestedMap[key]; }); return nestedMap; } } class _AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> { const _AppLocalizationsDelegate(); @override bool isSupported(Locale locale) { return ['en', 'de'].contains(locale.languageCode); } @override Future<AppLocalizations> load(Locale locale) async { AppLocalizations localizations = new AppLocalizations(locale); await localizations.load(); return localizations; } @override bool shouldReload(LocalizationsDelegate<AppLocalizations> old) => false; } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.