I am using ListView.builder to create list of Card‘s.
return ListView.builder(
itemBuilder: (BuildContext context, index) {
return ListTile(
title: MyCard(
cardId: index,
),);},);
In MyCard class i persist boolean shouldRemind
in storage by using shared_preferences plugin.
class MyCard extends StatefulWidget {
const MyCard({
super.key,
required this.cardId,
});
@override
State<MyCard> createState() => _CardState();
final int cardId;
}
class _CardState extends State<MyCard> {
bool shouldRemind = false;
@override
void initState() {
loadData();
super.initState();
}
loadData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
shouldRemind = prefs.getBool('boolSwitcherKey') ?? false;
});
}
saveBool() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setBool('boolSwitcherKey', shouldRemind);
}
@override
Widget build(BuildContext context) {
return Card(
color: shouldRemind
? const Color.fromARGB(255, 108, 0, 0)
: const Color.fromRGBO(32, 32, 32, 1),
child: SizedBox(
height: 180,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton.icon(
onPressed: () {
setState(() {
if (shouldRemind == true) {
shouldRemind = false;
} else {
shouldRemind = true;
}
saveBool();
});
},
icon: const Icon(Icons.alarm),
label: const Text("prr prr")),
Text(shouldRemind.toString())
],
)),
);
}
}
Problem is bool shouldRemind
, after it is changed by clicking button, it is only one of it, so every single copy of MyCard getting value equal to that what i changed before, i think that is the reason it look like this :
video
I want to have unique bool to every widget, so that after rendering my user another Card value of bool won’t change.
2
Answers
While every card have
cardId
, you can use it to save and retrieve fromSharedPreferences
'${widget.cardId} boolSwitcherKey'
Well with
you overwrite the same boolean every single time. You could use the index of the current element or the id of your card to create a unique key.
and the same to get the bool