I have the class below which I set and get the bool value to remember the user and auto-login next time.
import 'package:shared_preferences/shared_preferences.dart';
class SettingHelper {
static Future<bool> getValue(String key) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
var s = prefs.getBool(key);
print("GetValue ${s.toString()}"); //prints "GetValue true"
return s;
}
static Future<void> setValue(String key, bool value) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool(key, value);
}
}
I set my value in Login page with a CheckBox value.
onPressed: () {
...
SettingHelper.setValue("rememberMe", checkBoxValue);
...
}
When I start debugging I saw setValue worked. But when I hot restart getValue returns null in initState() but returns true in function. Here is the code:
class LandingPage extends StatefulWidget {
@override
_LandingPageState createState() => _LandingPageState();
}
class _LandingPageState extends State<LandingPage> {
bool rememberMe;
void _getRememberMeChoice() async {
rememberMe = await SettingHelper.getValue("rememberMe");
}
@override
void initState() {
super.initState();
_getRememberMeChoice();
}
@override
Widget build(BuildContext context) {
print(rememberMe); //Returns null
if (rememberMe == true) {
return BridgeList();
} else
return LoginScreen();
}
}
These are the outputs:
I/flutter (11724): null
I/flutter (11724): GetValue true
Please tell me if I'm doing something wrong...