Ask Your Question
3

How can Flutter recover a list of custom objects from a JSON string that is saved in shared preferences?

asked 2023-05-17 13:01:24 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-17 13:05:02 +0000

nofretete gravatar image
  1. Define the custom object class with the fields that match the JSON structure.
  2. Use the fromJson method to convert the JSON string to the list of custom objects.
  3. Retrieve the JSON string from shared preferences.
  4. Convert the JSON string to a list of custom objects using the fromJson method.

Here is an example implementation:

class CustomObject {
  String field1;
  int field2;

  CustomObject({this.field1, this.field2});

  factory CustomObject.fromJson(Map<String, dynamic> json) {
    return CustomObject(
      field1: json['field1'],
      field2: json['field2'],
    );
  }

  Map<String, dynamic> toJson() => {
        'field1': field1,
        'field2': field2,
      };
}

// Retrieve the saved JSON string from shared preferences
final prefs = await SharedPreferences.getInstance();
final jsonString = prefs.getString('customObjects');

// Convert the JSON string to a list of custom objects
final List<dynamic> jsonList = jsonDecode(jsonString);
final List<CustomObject> customObjects = jsonList.map((e) => CustomObject.fromJson(e)).toList();

Note: This example assumes that the saved JSON string is valid and contains a list of custom objects that follow the defined structure. You should include error handling in your implementation to handle cases where the JSON string is invalid or the mapping fails.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-17 13:01:24 +0000

Seen: 10 times

Last updated: May 17 '23