I've create List<String> favId = []; variable to store item's ID with SharedPreferences, so the favorited items ID didnt lost after I restart the application. And here is my SharedPreferences method and favorite IconButton in detailDoaPage.dart :
...
static List<String> favId = [];
getData() async {
SharedPreferences pref = await SharedPreferences.getInstance();
setState(() {
favId = pref.getStringList("id") ?? [];
});
}
void initState() {
super.initState();
getIds();
}
getIds() async {
favId = getData();
}
void saveData() async {
SharedPreferences pref = await SharedPreferences.getInstance();
pref.setStringList("id", favId);
}
...
IconButton(
icon: Icon(
favId.contains(doa.id.toString())
? Icons.favorite
: Icons.favorite_border,
color: favId.contains(doa.id.toString())
? Colors.red
: Colors.grey,
),
onPressed: () => setState(() {
doa.fav = !doa.fav;
if (favId.contains(doa.id.toString())) {
favId.removeWhere(
(element) => element == doa.id.toString());
} else {
favId.add(doa.id.toString());
}
saveData();
favId.sort();
}),
)
Beside that, I also want to show the favorited item's with ListView.builder in favPage.dart (another page). Of course I want get the favId from detailDoaPage.dart. How can I implement the provider/riverpod across this 2 pages?
Here is the preview of my app :
Thank you :)
