我在这里发现的这个问题对我来说是为了将对象编码为字符串以保存到prefs,但是我如何将此代码转换为编码List的对象?
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();
}
有人评论说,你只需要创建一个地图列表,但我只是不明白这意味着什么。请告诉我如何使用这个代码。
setStringList和setString都可以存储对象列表。但对我来说,第二种方法,将整个列表编码一次会更好
与setStringList
var encodedMusic1 = json.encode(Music(id: 1, ...).toMap());
var encodedMusic2 = json.encode(Music(id: 2, ...).toMap());
List<String> list = [encodedMusic1, encodedMusic2];
prefs.setStringList('key', list);
与setString
var encodedListOfMusic = Music.encode([Music(id: 1, ...), Music(id: 2, ...),]);
prefs.setString('key', encodedListOfMusic);