0

I created these two classes to save a list in sharedpreferences.

My questions:

  • how to access the list and add to it? I tried Segments.segments but no good.
  • how do I convert the list tojson using the class?
  • how to retrieve the items inside the list.

I saw so many examples and videos, but I still don't get it.

class Segment {
  final String chapter;
  final String from;
  final String to;

  Segment({this.chapter, this.from, this.to});

  factory Segment.fromJson(Map<String, dynamic> json) {
    return Segment(
      chapter: json['chapter'],
      from: json['from'],
      to: json['to'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'chapter': chapter,
      'from': from,
      'to': to,
    };
  }
}

&

class Segments {
  List<Segment> segments;

  Segments({this.segments});

  Segments.fromJson(Map<String, dynamic> json) {
    if (json['segments'] != null) {
      segments = [];
      json['segments'].forEach((v) {
        segments.add(new Segment.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.segments != null) {
      data['segments'] = this.segments.map((v) => v.toJson()).toList();
    }
    return data;
  }
}
EissaB93
  • 5
  • 3
  • Check if this helps: https://stackoverflow.com/questions/61316208/how-to-save-listobject-to-sharedpreferences-flutter – Darshan May 27 '21 at 15:34
  • What is the error you're seeing? Can you add some code from the actual place you're using `Segments`? – dgilperez May 27 '21 at 15:46
  • @dgilperez I didn't get errors because I don't know how to do it, I'm new to programming, I didn't understand what's in the link even though I should. I'll give it another try when I'm feeling smart, thank you both for your time! – EissaB93 May 28 '21 at 12:44
  • @DarShan ^^^^^^ – EissaB93 May 28 '21 at 12:44

1 Answers1

0

Would this work?

final list = Segments.fromJson({
  segments: [
    {
      'chapter': '1',
      'from': '1',
      'to': '1',
    },
    {
      'chapter': '2',
      'from': '2',
      'to': '2',
    },
  ]
});

print(list.segments);

In the first step you instantiate a Segments class with a json containing the list, then you access the segments list in the instance.

After that you should be able to do

list.toJson();

to obtain the json list.

And finally, you can always use an iterator on the List like this to return each Segment:

list.segments.forEach((segment) => print(segment));

Finally, I'd advice some renamings, segments.segments containing instances of Segment it's a bit of a tongue twister :)

dgilperez
  • 10,716
  • 8
  • 68
  • 96