Flutter sharedpreferences save list of objects

Sure! Here is an example of the HTML content within a div tag:

“`html

Flutter – SharedPreferences: Save List of Objects

SharedPreferences is a popular way to store simple data in Flutter apps. However, it does not directly support saving a list of objects. To achieve this, you can use the `shared_preferences` package in combination with JSON encoding and decoding.

Example:

  // Import necessary packages
  import 'package:shared_preferences/shared_preferences.dart';
  import 'dart:convert';
  
  // Define a class for the object
  class MyObject {
    String name;
    int age;
  
    MyObject(this.name, this.age);
  
    // Convert object to JSON string
    Map toJson() => {
      'name': name,
      'age': age,
    };
  
    // Create object from JSON string
    factory MyObject.fromJson(Map json) => MyObject(
      json['name'],
      json['age'],
    );
  }
  
  // Save list of objects to SharedPreferences
  Future saveObjectsList(List objectsList) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
  
    // Encode the list of objects to JSON string
    List encodedList = objectsList.map((object) => json.encode(object.toJson())).toList();
  
    // Save the list to SharedPreferences
    prefs.setStringList('objectsList', encodedList);
  }
  
  // Read list of objects from SharedPreferences
  Future> readObjectsList() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
  
    // Retrieve the encoded list from SharedPreferences
    List encodedList = prefs.getStringList('objectsList');
  
    // Decode the list of objects from JSON strings
    List objectsList = encodedList.map((encodedObject) => MyObject.fromJson(json.decode(encodedObject))).toList();
  
    return objectsList;
  }
  

In the example above, we have a class called `MyObject` which represents the objects we want to store and retrieve from SharedPreferences. The `toJson` method converts the object to a JSON string and the `fromJson` factory method creates the object from a JSON string.

The `saveObjectsList` function takes a list of `MyObject` objects, encodes each object to JSON using the `toJson` method, and saves the list as a `String` list in SharedPreferences using the `setStringList` method.

The `readObjectsList` function retrieves the encoded list from SharedPreferences using the `getStringList` method, decodes each JSON string using the `fromJson` factory method, and returns a list of `MyObject` objects.

Remember to import the necessary packages, including `shared_preferences` and `dart:convert` for JSON encoding and decoding.

“`
This HTML content gives a detailed example of how to use the `shared_preferences` package in Flutter to store and retrieve a list of objects using JSON encoding and decoding.

Leave a comment