I am currently learning sharedPreferences
and trying to set and get values to check if a button has been clicked or not.
This is my class for sharedPreferences
class UserSimplePrefences {
static SharedPreferences? _preferences;
static const _keyButton = 'buttonStatus';
static Future init() async {
_preferences = await SharedPreferences.getInstance();
}
static Future setButtonStatus(bool btnStatus) async {
await _preferences?.setBool(_keyButton, btnStatus);
}
static bool? getButtonStatus() {
return _preferences?.getBool(_keyButton);
}
}
here in my main.dart I have a button.
bool? onLineStatus;
//
void initState() {
super.initState();
WidgetsBinding.instance?.addObserver(this);
onLineStatus = UserSimplePrefences.getButtonStatus() !;
displayToastMessage(onLineStatus.toString(), context);
}
//
@override
Widget build(BuildContext context) {
//
RaisedButton(
onPressed: () async {
if (UserOnline! =true) {
UserOnline = true;
await UserSimplePrefences.setButtonStatus(true);
displayToastMessage("You are Online now", context);
} else {
UserOnline =false;
await UserSimplePrefences.setButtonStatus(false);
displayToastMessage("You are Offline now", context);
}}
),
}
UserOnline
is to toggle the button, works fine without SharedPreferences
.
In more simple language, when I hit the button i.e Online
and close the app and reopen the app sometime later I want the init
statement to be called with the toast message as true
and similarly when I click offline
I want the init
statement to call the toast false
.
Issue: My toast message is always true
.
`
add setState to your onPressed