I'm trying to add an array of cities' names to my localization json file but I can't decode it back to an array after it is converted to string.
en-US.json
{
"title" : "My account",
"name" : "John",
"cities" : ["Paris", "Lyon", "Nice"]
}
AppLocalization.dart
class AppLocalizations {
final Locale locale;
AppLocalizations(this.locale);
static AppLocalizations of(BuildContext context) {
return Localizations.of<AppLocalizations>(context, AppLocalizations);
}
static const LocalizationsDelegate<AppLocalizations> delegate =
_AppLocalizationsDelegate();
Map<String, String> _localizationStrings;
Future<bool> load() async {
String jsonString = await rootBundle.loadString(
'assets/translations/${locale.languageCode}-${locale.countryCode}.json');
Map<String, dynamic> jsonMap = json.decode(jsonString);
_localizationStrings = jsonMap.map((key, value) {
return MapEntry(key, value.toString());
});
return true;
}
Future<void> setLocale(Locale locale) async {
final SharedPreferences _prefs = await SharedPreferences.getInstance();
final _languageCode = locale.languageCode;
await _prefs.setString('locale', _languageCode);
print('locale saved!');
}
static Future<Locale> getLocale() async {
final SharedPreferences _prefs = await SharedPreferences.getInstance();
final String _languageCode = _prefs.getString('locale');
if (_languageCode == null) return null;
Locale _locale;
_languageCode == 'en'
? _locale = Locale('en', 'US')
: _locale = Locale('ar', 'EG');
return _locale;
}
String translate(String key) {
return _localizationStrings[key];
}
}
class _AppLocalizationsDelegate
extends LocalizationsDelegate<AppLocalizations> {
const _AppLocalizationsDelegate();
@override
bool isSupported(Locale locale) {
return ['en', 'ar'].contains(locale.languageCode);
}
@override
Future<AppLocalizations> load(Locale locale) async {
AppLocalizations localization = AppLocalizations(locale);
await localization.load();
return localization;
}
@override
bool shouldReload(LocalizationsDelegate<AppLocalizations> old) {
return false;
}
}
In my widget I try to access the array through List<String> _cities = AppLocalization.of(context).translate('cities');
this works and if I print _cities.toString() it prints [Paris, Lyon, Nice].
THE PROBLEM
When I try to decode _cities to an array using json.decode(_cities) I always get a format error Unhandled Exception: FormatException: Unexpected character (at character 2).
I believe the array is converted to String in this function
_localizationStrings = jsonMap.map((key, value) {
return MapEntry(key, value.toString());
});
How can I parse it back to an array??
I'm open to all kind of suggestions. Thank you