Search code examples
flutterdartsharedpreferencesprovider

how can i store List<object> in sharedpreferences using provider?


so basically this is my provider, what i want is how can i store the model data coming from provider to a shared preferences, and then how to decode it to show it in a bookmark page?

class bookmark extends ChangeNotifier{
  int _count = 0;
  List<bookmarkModel> bookM = [];
  
  void addCount(){
    _count++;
   notifyListeners();
  }
  
  void addItems(bookmarkModel i){
   bookM.add(i);
   notifyListeners();
  }

  int get  count => _count;
  List<bookmarkModel> get  bookMList => bookM;

}

here is my model:

import 'package:flutter/cupertino.dart';

class bookmarkModel{
  String title;
  String subtitle;
  int num;

  bookmarkModel({this.title, this.subtitle, this.num});

  bookmarkModel.fromJson(Map<String,dynamic> json) :
  title = json['title'], 
  subtitle = json['sutitle'], 
  num = json['num'];

  Map<String, dynamic> toJson()=>{
    'title':title,
    'subtitle':subtitle,
    'num': num
  }; 
}

Solution

  • SharedPreferences should only be used to store small and simple values. It's not meant to be used as a Database.

    You can use sharedPreferences to store bool, String, int and simple Lists (not lists of objects or maps). As far as I know, it even cannot store doubles.

    Try using a SQflite or Hive (No-SQL) to store more complex or extensive data locally.