This question which I found here is working for me for encoding an Object to a String in order to save to prefs, but how would I convert this code to encode a List of Objects?
import 'dart:convert';
void main() {
final String encodedData = Music.encode([
Music(id: 1, ...),
Music(id: 2, ...),
Music(id: 3, ...),
]);
final List<Music> decodedData = Music.decode(encodedData);
print(decodedData);
}
class Music {
final int id;
final String name, size, rating, duration, img;
bool favorite;
Music({
this.id,
this.rating,
this.size,
this.duration,
this.name,
this.img,
this.favorite,
});
factory Music.fromJson(Map<String, dynamic> jsonData) {
return Music(
id: jsonData['id'],
rating: jsonData['rating'],
size: jsonData['size'],
duration: jsonData['duration'],
name: jsonData['name'],
img: jsonData['img'],
favorite: false,
);
}
static Map<String, dynamic> toMap(Music music) => {
'id': music.id,
'rating': music.rating,
'size': music.size,
'duration': music.duration,
'name': music.name,
'img': music.img,
'favorite': music.favorite,
};
static String encode(List<Music> musics) => json.encode(
musics
.map<Map<String, dynamic>>((music) => Music.toMap(music))
.toList(),
);
static List<Music> decode(String musics) =>
(json.decode(musics) as List<dynamic>)
.map<Music>((item) => Music.fromJson(item))
.toList();
}
Someone commented that you just need to create a List of Maps, but I just can't get my head around what that means. Please show me using this code.
question from:
https://stackoverflow.com/questions/65836016/how-do-i-encode-listobject-to-save-to-prefs-setstringlist-in-flutter 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…