So I am trying to get data from my Firebase Firestore but its value randomly changes. In the method getUserData it is what it should be, yet when initState() is called the value is set to default again. I am new to flutter so I don't know how to fix it.
String email = '';
String username = '';
Future<void> getUserData(User user) async {
username = await FirebaseFirestore.instance
.collection('users_info')
.doc(user.uid)
.get()
.then((value) {
return value['username'];
});
print(username);
}
@override
void initState() {
User user = FirebaseAuth.instance.currentUser!;
email = user.email!;
getUserData(user);
print(username);
super.initState();
}
I/flutter (15550): I/flutter (15550): Kiaule5
CodePudding user response:
print(username)
in initState
get executed before getUserData(user);
executed, it's not random value.
For this you can use getUserData.then()
method in initState
and after that you can get correct value or set the variable.
Example :
getUserData.then((String value) {
print(value);
}).catchError((e) {
return 499;
});