I have a list of favorite music, which I retrieve from music when the app is opened for the first time, the app gets a favorite music list from favorite. I want to save this list to shared
preferences.List<Music> favoriteMusic = new List<Music>();
where music class is:
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,
);
}
}
How can I save favorite music list?
You should do these steps
to save the object:
- convert your object to map with
toMap()
method- encode your map to string with
encode(...)
method- save the string to shared preferences
for restoring your object:
- decode shared preference string to a map with
decode(...)
method- use
fromJson()
method to get your object
UPDATE FULL SAMPLE
import 'dart:convert';
void main() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
// Encode and store data in SharedPreferences
final String encodedData = Music.encode([
Music(id: 1, ...),
Music(id: 2, ...),
Music(id: 3, ...),
]);
await prefs.setString('musics_key', encodedData);
// Fetch and decode data
final String musicsString = await prefs.getString('musics_key');
final List<Music> musics = Music.decode(musicsString);
}
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();
}