原理:
1.从String列表里面获取某个value:
List<String> jsonStrings = ['{"name": "John", "age": 30}','{"name": "Jane", "age": 25}','{"name": "Bob", "age": 35}',];String key = 'age'; // 假设我们想获取 'age' 对应的值for (String jsonString in jsonStrings) {Map<String, dynamic> jsonObject = json.decode(jsonString);if (jsonObject.containsKey(key)) {print('Value for key "$key": ${jsonObject[key]}');}}
2.flutter List jsonStrings = [
‘{“name”: “John”}’,
‘{“age”: 25}’,
];
如何写一个方法,往列表添加一个’{“class”: 1}’
void addJsonString(List<String> jsonStrings, String newJsonString) {jsonStrings.add(newJsonString);
}void main() {List<String> jsonStrings = ['{"name": "John"}','{"age": 25}',];String newJsonString = '{"class": 1}';addJsonString(jsonStrings, newJsonString);print(jsonStrings); // 输出: [{"name": "John"}, {"age": 25}, {"class": 1}]
}
用sharePreference实现:
//保存翻译词条saveTranslate({required String originalText,required String code,required String translateText}) {List<String> saveTranslateList = [];//获取已经存好的数据if (SPHelper.getTranslateList == null) {SPHelper.setTranslateList([]);}if (SPHelper.getTranslateList != null) {saveTranslateList = SPHelper.getTranslateList;//添加翻译数据saveTranslateList.add('{"${originalText + code}":"$translateText"}');SPHelper.setTranslateList(saveTranslateList);PrintUtil.prints('翻译词条列表-保存-${json.encode(SPHelper.getTranslateList)}');}}//获取翻译词条getTranslateByCode({required String originalText, required String code}) {if (originalText == '') {return '';}//翻译的keyString translateKey = originalText + code;//返回的翻译词条String translatedText = '';List<String> translateList = [];if (SPHelper.getTranslateList == null) {SPHelper.setTranslateList([]);}if (SPHelper.getTranslateList != null) {translateList = SPHelper.getTranslateList;PrintUtil.prints('翻译词条列表-获取保存的数据-${json.encode(translateList)}');for (String jsonString in translateList) {try {Map<String, dynamic> jsonObject = json.decode(jsonString);if (jsonObject.containsKey(translateKey)) {PrintUtil.prints('Value for key "$translateKey": ${jsonObject[translateKey]}');translatedText = jsonObject[translateKey];PrintUtil.prints('翻译词条列表-JSON string: $jsonString');}} catch (e) {PrintUtil.prints('翻译词条列表-Invalid JSON string: $jsonString 错误:$e');}}}return translatedText;}