I have a drawer in my app and I want to maintain the state of toggle switch in it. How can i do this ? This is the code
SizedBox(
height: 40,
child: ListTile(
leading: SizedBox(
height: 25,
width: 25,
child: Image.asset(
'assets/sideMenu/Bell.png',
),
),
title: Transform.translate(
offset: const Offset(-14, 0),
child: const Text('Notifications',
style: TextStyle(
fontSize: 12, color: Colors.white))),
trailing: SizedBox(
height: 20,
width: 40,
child: Transform.scale(
scale: 1.3,
child: Switch.adaptive(
value: value,
activeColor: Colors.white,
activeTrackColor: const Color.fromARGB(
255, 35, 187, 40),
onChanged: (value) =>
setState(() => this.value = value)),
)),
),
),
Anything I can do to make this maintain its state?
This is how it works now :
CodePudding user response:
You can use shared preferences and save the state on press
onChanged: (val)async{
setState((){value = val});
SharedPreferences prefs= await SharedPreferences.getInstance();
prefs.setBool("notificationStatus", val);
}
Then in initstate you can set the value
bool value = true;
@override
initState() {
super.initState();
fetchNotificationStatus();
}
fetchNotificationStatus() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
value = prefs.getBool("notificationStatus")??true;
setState((){});
}