Home > OS >  Can I put two list data in SharedPreferences (flutter)?
Can I put two list data in SharedPreferences (flutter)?

Time:01-18

i need to save 2 list(list book,list tool) in page favorite but the problem is the list book is save in page favorite and the list tool is not save


that the list book file

List<Book> Books_Data = [
  Book(
    id: 'b1',
    categories: [
      'c1',

    ],
    title: 'الوصايا العشر في الامن السيبراني',
writer:'محمد شاكر المبيض',
    price:'5500 ل.س',
    imageUrl:
        'assets/image/Book/1.jpg',
    page: 64,   
  ),
      
 ]

and that the list tool file

List<Tools> tools_Data = [
  Tools(
    id: 't1',
    categories: [
      'c1',

    ],
    title: 'قلم رصاص ميكانيكي',
    price:'750 ل.س',
    imageUrl:
        'assets/image/Tools/1.jpg',
  ),
   
  ]

CodePudding user response:

try to convert your class object to JSON by obj.toJson(); and save the json String into Storage and refactor the json String to your obj class by obj.fromJson();

CodePudding user response:

I think that a simple solution is to convert your list into a json string and then save it to shared preferences.

Example:

//to convert to json string
SharedPreferences prefs = await SharedPreferences.getInstance();
String booksList = jsonDecode(*yourListName*);

prefs.setString("yourTag", bookList);

This is how you can save your list. When you need it you have just to:

SharedPreferences prefs = await SharedPreferences.getInstance();
String json = prefs.getString("yourTag");
var list = jsonEncode(json);

This should return you the list you inserted in shared preferences before.

For any question just comment below.

  •  Tags:  
  • Related