I am having trouble identifying as to why setState() is returning null on my shared preferences getString method. I am calling an async function outside of the initState and the constantly printing null when i check the return string of getString on page load. I have checked that setString is saving the correct string to the key. Here is my code:
void initState() {
super.initState();
retrieve();
}
retrieve() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
name = prefs.getString("displayName");
print(name);
});
}
Here is where I setString(in the register user page):
try {
UserCredential result =
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
);
final user = FirebaseAuth.instance.currentUser;
final name = _usernameController.text;
// if (user != null) {
await user?.updateDisplayName(name);
Navigator.pushNamed(context, homeRoute);
print(name);
CodePudding user response:
You should set ,username via shared preference before accessing it.
final prefs = await SharedPreferences.getInstance();
In register page.(where you want to set name via SharedPreference before accessing it)
await prefs.setString('displayName', 'name');
After setting it in registeration you can access like above
name = prefs.getString("displayName");
CodePudding user response:
When SharedPreferences
return null value it means you have not set value with your key
yet. So firstly set something like this:
final prefs = await SharedPreferences.getInstance().reload();
await prefs.setString('displayName', 'Mark');
then try to call it.