I’m new to flutter. I have problems with how to fetch the current user document ID/name using syntax.
Future<User?> readUser() async {
final docUser =
FirebaseFirestore.instance.collection('users').doc('How do I get this document ID');
final snapshot = await docUser.get();
if (snapshot.exists) {
return User.fromJson(snapshot.data()!);
} else {
print('User does not exist');
}
}
This is my User class where i store my details
class User {
String uid;
final String name;
final int age;
final String email;
User({
this.uid = '',
required this.name,
required this.age,
required this.email,
});
Map<String, dynamic> toJson() => {
'uid': uid,
'name': name,
'age': age,
'email': email,
};
static User fromJson(Map<String, dynamic> json) => User(
uid: json['id'],
name: json['name'],
age: json['age'],
email: json['email'],
);
}
I tried
final firebaseUser = await FirebaseAuth.instance.currentUser
Future<User?> readUser() async {
final docUser =
FirebaseFirestore.instance.collection('users').doc(firebaseUser.uid);
final snapshot = await docUser.get();
if (snapshot.exists) {
return User.fromJson(snapshot.data()!);
} else {
print('User does not exist');
}
}
But it does not work
2
Answers
To access the current user id use
FirebaseAuth.instance.currentUser!.uid
To access the current user name use
FirebaseAuth.instance.currentUser!.displayName
How to listen to the current user’s document ?
It’s just
snapshot.id
For example