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 ayahnum;
bookmarkModel({this.title, this.subtitle, this.ayahnum});
bookmarkModel.fromJson(Map<String,dynamic> json) :
title = json['title'],
subtitle = json['sutitle'],
ayahnum = json['ayahnum'];
Map<String, dynamic> toJson()=>{
'title':title,
'subtitle':subtitle,
'ayahnum': ayahnum
};
}
CodePudding user response:
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 List
s (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.
CodePudding user response:
You already have toJosn
and fromJson
ready to use, you just need to convert bookM
to a map josnEnode()
and the get it back using josnDecode()
.
try the code below:
void saveBookmark() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
final String List = jsonEncode(bookM, toEncodable: (c)=> c.toJson());
await prefs.setString('BookMarkList', List);
}
void loadBookMark() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
final String saved = prefs.getString('BookMarkList');
final List<dynamic> decoded = jsonDecode(saved);
bookM = decoded.map((bookmark) => bookmarkModel.fromJson(bookmark));
}