Search code examples
jsonflutterdartencodingsharedpreferences

Encode an objects to json, store it in sharedprefs, then retrieve it as string


In my app, the user chooses the chapter he wants to read, the verse he wants to begin from, and the end verse.

I'm going to store these three strings and show in his "reading history" list, where he can see all of his previous readings.

I read that you can do that by creating a class, storing these in an object and converting it to JSON then storing it inside sharedprefs.(or something like that). But I didn't understand them as they were a little different from my case.

this is the class:

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,
    };
  }
}

these the steps i want to know how to do:

  • store the string in the object.
  • Encode the object to JSON.
  • store it inside sharedprefs.
  • decode it back and choose a certain item from the list.

Solution

  • You can store a JSON (Map) object with shared preferences in Flutter by encoding the Map to raw JSON (it is basically a String).

    To store something with shared preferences you should first of all add it to your dependencies. Here's how. Then somewhere in your code get the instance of SharedPreferences object by doing:

    final prefs = await SharedPreferences.getInstance();
    
    

    After that you should encode the Map that you got from your Segment class by doing this:

    Segment segment = Segment(...);
    String rawJson = jsonEncode(segment.toJson());
    

    To save this new JSON with shared preferences run this command to store the whole JSON as a String:

    prefs.setString('my_string_key', rawJson);
    

    When you want to read your data from shared preferences use this:

    final rawJson = prefs.getString('my_string_key') ?? '';
    Map<String, dynamic> map = jsonDecode(rawJson);
    final Segment = Segment.fromJson(map);
    

    For more details see this article.