i am trying to get data to a screen by shared prefrences so i set data here on my login screen:
var displayName=jsondata["username"];
SharedPreferences prefs=await SharedPreferences.getInstance();
prefs.setString('displayName', displayName);
and getting this data on my drawer:
String displayName="0";
initState() {
getData();
super.initState();
}
getData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
displayName=prefs.getString('displayName')?? "0";
}
**it gets the data when i click on drawer button but when go back to main screen and re-enter in my drawer it gets value "0" **here is the demo of issue
what is wrong?
and here is the code of the other screen which I move in between:
late String displayName;
getData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
displayName=prefs.getString('displayName')?? "0";
print(displayName);
}
initState() {
getData();
super.initState();
}
CodePudding user response:
first of all always use a method after super.initState();
inside initState
.
after that assuming that variable displayName
is not updated anywhere else try to log
when ever displayName
changes in your code.
I can see that another screen is opening and then he value changes. so please show us more code of what you write.
CodePudding user response:
Please refer to below code
String displayName="0";
initState() {
getData();
super.initState();
}
getData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if(displayName.isEmpty || displayName == "0"){
displayName=prefs.getString('displayName')?? "0";
await prefs.reload();
}
}
CodePudding user response:
to Keep listening to code even you moved between pages,use StreamBuilder
StreamBuilder<DocumentSnapshot>(
stream:getData(),
builder: ( context, snapshot) {
if(snapshot.connectionState==ConnectionState.waiting){
return CircularProgressIndicator();
}else {
if(snapshot.hasData){
// .......
}
}
}
)