How to get the current user id from Firebase in Flutter
final FirebaseAuth _auth = FirebaseAuth.instance;
getCurrentUser() async {
final FirebaseUser user = await _auth.currentUser();
final uid = user.uid;
// Similarly we can get email as well
//final uemail = user.email;
print(uid);
//print(uemail);
}
Call the function getCurrentUser to get the result. For example, I used a button:
RaisedButton(
onPressed: getCurrentUser,
child: Text('Details'),
),
If you are using sign in with Google than you will get this info of user.
final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = new GoogleSignIn();
void initState(){
super.initState();
firebaseAuth.onAuthStateChanged
.firstWhere((user) => user != null)
.then((user) {
String user_Name = user.displayName;
String image_Url = user.photoUrl;
String email_Id = user.email;
String user_Uuid = user.uid; // etc
}
// Give the navigation animations, etc, some time to finish
new Future.delayed(new Duration(seconds: 2))
.then((_) => signInWithGoogle());
}
Future<FirebaseUser> signInWithGoogle() async {
// Attempt to get the currently authenticated user
GoogleSignInAccount currentUser = _googleSignIn.currentUser;
if (currentUser == null) {
// Attempt to sign in without user interaction
currentUser = await _googleSignIn.signInSilently();
}
if (currentUser == null) {
// Force the user to interactively sign in
currentUser = await _googleSignIn.signIn();
}
final GoogleSignInAuthentication googleAuth =
await currentUser.authentication;
// Authenticate with firebase
final FirebaseUser user = await firebaseAuth.signInWithGoogle(
idToken: googleAuth.idToken,
accessToken: googleAuth.accessToken,
);
assert(user != null);
assert(!user.isAnonymous);
return user;
}
Update (2020.09.09)
After firebase_auth version 0.18.0
Few breaking updates were made in firebase_auth 0.18.0. FirebaseUser is now called User, currentUser is a getter, and currentUser is synchronous.
This makes the code for getting uid like this:
final FirebaseAuth auth = FirebaseAuth.instance;
void inputData() {
final User user = auth.currentUser;
final uid = user.uid;
// here you write the codes to input the data into firestore
}
Before firebase_auth version 0.18.0
uid is a property of FirebaseUser object. Since auth.currentUser() return a future, you have to await in order to get the user object like this:
final FirebaseAuth auth = FirebaseAuth.instance;
Future<void> inputData() async {
final FirebaseUser user = await auth.currentUser();
final uid = user.uid;
// here you write the codes to input the data into firestore
}