I want to have the username (in Arabic) on the home page from firebase. When I ran the app the first time every time I turn on the emulator it returns null. But if I run it one more time/hot reload it is good.
I tried using toString()
but it also did not work.
Here is my code:
//user's info
late User user;
final _auth = FirebaseAuth.instance;
late User signedInUser;
var sex;
var age;
var name;
Future<void> _getData() async {
FirebaseFirestore.instance
.collection('users')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
if (doc["email"] == signedInUser.email) {
name = doc['name'];
age = doc['age'];
sex = doc['sex'];
print(doc['name']); //might delete
}
});
});
}
Widget build(BuildContext context) {
return FutureBuilder(
future: _getData(),
builder: (context, snapshot) => snapshot.connectionState ==
ConnectionState.waiting
? //more code
Text(
'$name'.toString(),
style: TextStyle(
),
) ```
CodePudding user response:
Since _getData
is an asynchronous method, it needs to return a Future
, or it can use await
, but in your code it does neither of those things.
For example, this now uses await to ensure the method only completes once the name
is set:
Future<void> _getData() async {
var querySnapshot = await FirebaseFirestore.instance
.collection('users')
.get();
querySnapshot.docs.forEach((doc) {
if (doc["email"] == signedInUser.email) {
name = doc['name'];
age = doc['age'];
sex = doc['sex'];
print(doc['name']); //might delete
}
});
}