I want to retrieve the userName
from firebase firestore per each user logins. So i wan't to retreive user data using the userID from firebase and display it.
I have attached my current code below.
How can i adjust the below code to get the userName
from firestore using the user_ID
as the primary key?
Current code :
class GetUserName extends StatelessWidget {
final String documentId;
GetUserName(this.documentId);
@override
Widget build(BuildContext context) {
CollectionReference users = FirebaseFirestore.instance.collection('users');
return FutureBuilder<DocumentSnapshot>(
future: users.doc(documentId).get(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasError) {
return Text("Something went wrong");
}
if (snapshot.hasData && !snapshot.data!.exists) {
return Text("Document does not exist");
}
if (snapshot.connectionState == ConnectionState.done) {
Map<String, dynamic> data =
snapshot.data!.data() as Map<String, dynamic>;
return Text("Hello, ${data['userName']}");
}
return Text("loading");
},
);
}
}
Thank you in advance :)
CodePudding user response:
You'll want to use a StreamBuilder
on `` to deal with the current user, something like this:
return StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.active) {
return Center(child: CircularProgressIndicator()); //