我想将列表List<Word> myList
转换为String
并将其放入sharedPreference,稍后我也想将该字符串(从sharedPreference)转换回List<Word>
。
这是我的模型课程Word
class Word {
int id;
String word;
String meaning;
String fillInTheGapSentence;
Word.empty();
Word(int id, String word, String meaning, String fillInTheGapSentence){
this.id = id;
this.word = word;
this.meaning = meaning;
this.fillInTheGapSentence = fillInTheGapSentence;
}
}
我可以将List<Word> myList
转换为String
var myListString = myList.toString();
但是无法从List<Word> myListFromString
中获得myListString
。
谢谢。
答案 0 :(得分:0)
您将需要某种序列化,并且其中有很多。最受欢迎的一种是JSON序列化。
Flutter的文档很好,如何做到这一点: https://flutter.dev/docs/development/data-and-backend/json
您要:
答案 1 :(得分:0)
首先,myList.toString()
并非JSON格式,除非您覆盖toString()
方法。您要做的是手动将对象转换为Dictionary,然后将其编码为JSON字符串。相反,您需要将字符串转换为字典,然后将其转换为对象。像这样:
import 'dart:convert';
class Word {
int id;
String word;
String meaning;
String fillInTheGapSentence;
Word.empty();
Word(int id, String word, String meaning, String fillInTheGapSentence) {
this.id = id;
this.word = word;
this.meaning = meaning;
this.fillInTheGapSentence = fillInTheGapSentence;
}
Map<String, dynamic> toMap() {
return {
'id': this.id,
'word': this.word,
'meaning': this.meaning,
'fillInTheGapSentence': this.fillInTheGapSentence,
};
}
factory Word.fromMap(Map<String, dynamic> map) {
return new Word(
map['id'] as int,
map['word'] as String,
map['meaning'] as String,
map['fillInTheGapSentence'] as String,
);
}
}
String convertToJson(List<Word> words) {
List<Map<String, dynamic>> jsonData =
words.map((word) => word.toMap()).toList();
return jsonEncode(jsonData);
}
List<Word> fromJSon(String json) {
List<Map<String, dynamic>> jsonData = jsonDecode(json);
return jsonData.map((map) => Word.fromMap(map)).toList();
}