I want to use dark mode in my flutter calculator app. I used Dynamic Theme plugin to switch from dark to light mode.
Previously, I was using _darkmode variable through which I made the color of my button customized for dark and light mode. But whenever I closed my app its color used to get switched or mismatched combination of different colors appeared. And I thus wanted to solve this using shared preferences. So, if _darkMode variable is not present in SP then define it with False initially. And according to the SharedPreference get data I want to set the colors of the buttons. Also, I used a switch to set and change the Shared preference.
So this is my code:
init state where I am initially defining the _darkmode.
class _SimpleCalculatorState extends State<SimpleCalculator> {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance(); // shared preferences
Future<bool> _darkmode; // this variable to store in SP and for darkmode.
@override
void initState() {
// ! init
super.initState();
_darkmode = _prefs.then((SharedPreferences prefs) {
return (prefs.getBool('darkMode') ?? false);
});
}
To set the values of darkmode varibale on shared preferences:
// to set the values on SP
void setBoolToSP(bool boolValue) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('darkMode', boolValue);
}
To get the value of darkmode varibale from shared preferences:
// to get values from sp
getBoolValuesSP() async {
try {
SharedPreferences prefs = await SharedPreferences.getInstance();
print("inside getboolvaluesf");
return prefs.getBool('darkMode');
} catch (e) {
print("getbool" + e);
}
}
So, now I want to call this getBoolValuesSP() to here so that i can dynamically change the colors of the buttons based on values of _darkMode variable:
child: FlatButton(
// ! here
color: getBoolValuesSP() // here
? (buttonColor != Colors.white ? buttonColor : Colors.black54)
: buttonColor,
}
But I'm getting an error like "A value of type 'bool' can't be assigned to a variable of type 'Future"
and I'm using a switch to toggle the dark and light mode.
Switch(
activeColor: Colors.orange,
inactiveThumbColor: Colors.black,
value: _darkMode, // !
onChanged: (value) {
setState(() {
DynamicTheme.of(context).setBrightness(
Theme.of(context).brightness == Brightness.dark ? Brightness.light : Brightness.dark);
darkMode = !darkMode;
setBoolToSF(darkMode);
print("check " + darkMode.toString());
});
})
can anyone tell me how to call the getBoolValuesSP in the color and how to dynamically change the colors of buttons using Shared preference?