I have a favorite image button for images which turns red when clicked but it doesn't store it, when I reopen the image it's not liked. So I was wondering if we could give shared preference on it to store the liked button.Does anyone know how it can be done?
the complete code-
class FavoriteWidget extends StatefulWidget {
@override
_FavoriteWidgetState createState() => _FavoriteWidgetState();
}
class _FavoriteWidgetState extends State<FavoriteWidget> {
bool liked = false;
_pressed() {
setState(() {
liked = !liked;
});
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
child: IconButton(
icon: Icon(liked ?Icons.favorite: Icons.favorite_border,
color: liked ? Colors.red :Colors.grey ),
onPressed: () => _pressed(),
),
),
],
);
}
}
You can use the shared_preferences plugin to persist whether the favorite button has been pressed or not, and then restore the persisted value when the Widget
initializes.
class FavoriteWidget extends StatefulWidget {
@override
_FavoriteWidgetState createState() => _FavoriteWidgetState();
}
class _FavoriteWidgetState extends State<FavoriteWidget> {
static const likedKey = 'liked_key';
bool liked;
@override
void initState() {
super.initState();
_restorePersistedPreference();
}
void _restorePersistedPreference() async {
var preferences = await SharedPreferences.getInstance();
var liked = preferences.getBool(likedKey) ?? false;
setState(() => this.liked = liked);
}
void _persistPreference() async {
setState(() => liked = !liked);
var preferences = await SharedPreferences.getInstance();
preferences.setBool(likedKey, liked);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: liked == null
? Center(child: CircularProgressIndicator())
: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
child: IconButton(
icon: Icon(
liked ? Icons.favorite : Icons.favorite_border,
color: liked ? Colors.red : Colors.grey,
),
onPressed: _persistPreference,
),
),
],
),
);
}
}