How to save List<Object> to SharedPreferences flutter?

时光怂恿深爱的人放手 提交于 2020-12-01 09:38:19

问题


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?


回答1:


You should do these steps

to save the object:

  1. convert your object to map with toMap() method
  2. encode your map to string with encode(...) method
  3. save the string to shared preferences

for restoring your object:

  1. decode shared preference string to a map with decode(...) method
  2. use fromJson() method to get your object

UPDATE FULL SAMPLE

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();
}



回答2:


Convert it to a string, you can store it

import 'dart:convert';
...
var s = json.encode(myList);
// or var s = jsonEncode(myList);

json.decode() //convert a string to List when you load it



回答3:


First, You can convert your model to string and then you can save List<String> in SharedPreferences. Here is how you should do it.

  prefs.setStringList("key", yourList);

SharedPreferences prefs;
List<String> list;
// ...


Future<bool> _saveList() async {
  return await prefs.setStringList("key", list);
}

List<String> _getList() {
  return prefs.getStringList("key");
}


来源:https://stackoverflow.com/questions/61316208/how-to-save-listobject-to-sharedpreferences-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!