【发布时间】:2021-01-19 22:26:50
【问题描述】:
我正在尝试将一组城市名称添加到我的本地化 json 文件中,但在将其转换为字符串后,我无法将其解码回数组。
zh-CN.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;
}
}
在我的小部件中,我尝试通过 List<String> _cities = AppLocalization.of(context).translate('cities'); 访问数组
这可行,如果我打印 _cities.toString() 它会打印 [Paris, Lyon, Nice]。
问题
当我尝试使用 json.decode(_cities) 将 _cities 解码为数组时,我总是收到格式错误 Unhandled Exception: FormatException: Unexpected character (at character 2)。
我相信数组在这个函数中被转换为字符串
_localizationStrings = jsonMap.map((key, value) {
return MapEntry(key, value.toString());
});
如何将其解析回数组??
我愿意接受各种建议。谢谢
【问题讨论】: