我正在尝试将城市名称数组添加到我的本地化 json 文件中,但在将其转换为字符串后我无法将其解码回数组。
en-US.json
{
"title" : "My account",
"name" : "John",
"cities" : ["Paris", "Lyon", "Nice"]
}
AppLocalization.dartclass 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());
});
如何将其解析回数组?我愿意接受各种建议。谢谢
最佳答案
我知道这可能不是最好的方法,但这只是我发现的一种方法。您还可以将您的值保存在不同的 json Assets 文件中,并使用 json.decode() 正常解析它,但我需要它来通过本地化更轻松地处理它。
所以我找到了一个简单的解决方案,而不是向本地化类添加函数。
我从我的本地化文件(像任何其他本地化字符串)中以字符串的形式获取小部件中的数组,如下所示:
var list = AppLocalization.of(context).translate('cities');//this will return [Paris, Lyon, Nice] as a string
然后我执行以下操作:list = list.replaceAll(RegExp("\\[|\\]"), ''); //removes square brackets from the string
var cityList = list.split(','); //splits the city names by the comma as a
print(cityList); //prints [Paris, Lyon, Nice] as List<String>
我还实现了另一种获取嵌套 json 数组的方法,例如{
"title" : "My account",
"name" : "John",
"cities" : ["Paris", "Lyon", "Nice"],
"areas" :
{
"paris" : ["area1", "area2", "area3"],
"lyon": ["area1", "area2", "area3"]
}
}
我这样做是为了获得巴黎地区... var areas = AppLocalization.of(context).translate('areas'); //this gets the whole map as a string.
areas = areas.replaceAll(RegExp("\\[|\\]|\\{|\\}"), '');//this removes leading and trailing {[ ]}
var splitValues = areas.split(':');
var mapValues = Map.fromIterable(test, key: (item) => splitValues[0],value: (item) => item.split(','),);
var parisAreas = mapValues.map((key, value) =>
MapEntry<String, List<String>>(key, List<String>.from(value)));
关于arrays - Flutter 解析来自本地化 JSON 文件的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64202118/