Thats my Favorite.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Favoriten extends StatefulWidget {
@override
_FavoritenState createState() => _FavoritenState();
}
Future<List<bool>> getBoolList() async {
List<bool> prefList = [];
var sharedPreferences = await SharedPreferences.getInstance();
Set<String> keys = sharedPreferences.getKeys();
for (int i = 0; i < keys.length; i++) {
bool value = sharedPreferences.getBool(keys.elementAt(i));
prefList.add(value);
}
return prefList;
}
class _FavoritenState extends State<Favoriten> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Favorites'),
),
body: FutureBuilder<List<bool>>(
future: getBoolList(),
builder: (context, future) {
if (!future.hasData)
return Container(child: Text('X'),); // Display empty container if the list is empty
else {
List<bool> list = future.data;
return ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
return Container(child: Text(list[index].toString()));
});
}
}),
);
}
}
and this is the details.dart here i save bools
@override
_DetailsState createState() => _DetailsState();
}
const String spKey = 'myBool';
class _DetailsState extends State<Details> {
SharedPreferences sharedPreferences;
bool isfavorit;
@override
void initState() {
super.initState();
SharedPreferences.getInstance().then((SharedPreferences sp) {
sharedPreferences = sp;
isfavorit = sharedPreferences.getBool('${widget.id}');
// will be null if never previously saved
if (isfavorit == null) {
isfavorit = false;
persist(isfavorit); // set an initial value
}
setState(() {});
});
}
void persist(bool value) {
setState(() {
isfavorit = value;
});
sharedPreferences?.setBool('${widget.id}', value);
}
// ignore: missing_return
IconData favicon() {
if (isfavorit == true) {
return Icons.favorite;
} else
if (isfavorit == false) {
return Icons.favorite_border;
}
}
// ignore: missing_return
Color favicolor() {
if (isfavorit == true) {
return Colors.red;
} else
if (isfavorit == false) {
return Colors.white;
}
}
void changefav() {
if (isfavorit == true) {
return persist(false);
} else
if (isfavorit == false) {
return persist(true);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: Icon(
favicon(),
color: favicolor(),
),
onPressed: () => changefav(),
),
],
title: Text(
AppLocalizations.of(context).translate(widget.name),
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
centerTitle: true,
),