I want to acess the uname field of the current loggedin user .
I added uname in the registration screen like this :
onPressed: () async {
try {
final newuser = await FirebaseAuth.instance
.createUserWithEmailAndPassword(
email: email ?? 'error',
password: password ?? 'error',
);
await FirebaseFirestore.instance
.collection('Users')
.add({' uname': username});
if (newuser != null) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => home()),
);
}
} catch (e) {
print(e);
}
}
But I dont know how to acess it from another file or more specifically I want to acess it on the profile screen .
How can I acess the uname field from firestore in flutter?
2
Answers
I think the better way to what you want is to set the document ID in the collection("Users") same as the uid of the user authenticated. So fetching details or in this case, uname will be easier.
For creating doc with docID same as user uid:
For fetching details:
You should call the document in the
initState
and set the value of string usingsetState
Code:
Note: This is not recommended ⚠
As future method is called inside the
initState(){}
it is heavily discouraged to do so as it slows down the process of building the widget and also not considered as a good practice.Use
FutureBuilder
for this: