Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

json - How do I encode List<Object> to save to prefs.setStringList in Flutter?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's okay both setStringList, setString to store list of objects. But for me, the second one, encoding the whole list once is better

With 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);

With setString

var encodedListOfMusic = Music.encode([Music(id: 1, ...), Music(id: 2, ...),]);

prefs.setString('key', encodedListOfMusic);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...