0

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.

steveny909
  • 95
  • 1
  • 3
  • 10
  • This is very good example of encoding/decoding list of Music object. You can modify or create from scratch based on your needs. What's not clear for you ? If you give more detail, i'd be helpful for you. – blackkara Jan 21 '21 at 21:56
  • Currently, `Music.decode(encodedData)` results in a valid JSON array. Isn't it what you're looking for? – Riwen Jan 21 '21 at 21:58
  • Thanks @blackkara. As you can see when I execute `encode` it produces a String. I'm looking to produce a List with the ultimate goal of saving to prefs with `.setStringList`. I just can't get my head around how to change this code to work for a list instead of just one object. – steveny909 Jan 21 '21 at 22:03
  • @Riwen, I'm looking for a `List` in order to save in `prefs.setStringList` and then to be able to decode back to an Object when reading from prefs. – steveny909 Jan 21 '21 at 22:05
  • Why not save the JSON array as `setString` then decode it accordingly? – Riwen Jan 21 '21 at 22:51
  • @Riwen, of course! I was so hung up on making it work with setStringList that I didn't consider just using setString with the code as it currently exists. Thank you! – steveny909 Jan 21 '21 at 23:16

1 Answers1

0

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);
blackkara
  • 4,900
  • 4
  • 28
  • 58