I have a simple switch button and I'd like to persist the state of that button whenever I navigate to a new page and/or refresh the current page. I'm trying to use SharedPreferences
to achieve this but haven't been successful.
Any help would be greatly appreciated!
Code:
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class New extends StatefulWidget {
const New({Key? key}) : super(key: key);
@override
State<New> createState() => _NewState();
}
class _NewState extends State<New> {
bool value = false;
var selectFlag = 'false';
@override
void initState() {
super.initState();
getValueFlag();
}
Future<void> getValueFlag() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.getString('selected_displayFlag') != null) {
setState(() {
selectFlag = prefs.getString('selected_displayFlag')!;
});
}
}
Future<void> setValueFlag(String valueFlag) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
selectFlag = valueFlag.toString();
prefs.setString('selected_displayFlag', selectFlag);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Switch(
value: value,
activeColor: Colors.black,
onChanged: (valueFlag) {
selectFlag == "false"
? setState(() {
selectFlag = "true";
value = true;
valueFlag = true;
})
: selectFlag == "true"
? setState(() {
selectFlag = "false";
value = false;
valueFlag = false;
})
: null;
},
),
);
}
}
CodePudding user response:
Switch(
value: selectFlag,
activeColor: Colors.black,
onChanged: (valueFlag) {
selectFlag == "false"
? setState(() {
setValueFlag(true);
selectFlag = "true";
value = true;
valueFlag = true;
})
: selectFlag == "true"
? setState(() {
setValueFlag(false);
selectFlag = "false";
value = false;
valueFlag = false;
})
: null;
},
and these methods should getBool and setBool
Future<void> getValueFlag() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState((){
selectFlag = prefs.getBool('selected_displayFlag')?? true;
});
}
Future<void> setValueFlag(Bool valueFlag) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('selected_displayFlag', valueFlag);
}
In onchanged you missed to call the save method. And the value selectFlag wasnt assigned as the value to the switch
CodePudding user response:
This is what you need. https://biplabdutta.com.np/posts/theme-switching/
I recommend you go through this blog post of mine.