Access Google Sign-In username globally
FirebaseAuth has an async
method called currentUser
that can be used to access the currently authenticated user.
dummy example:
class SomePage extends StatefulWidget {
@override
_SomePageState createState() => new _SomePageState();
}
class _SomePageState extends State<SomePage> {
String _userName = "...";
_getUserAuth(){
FirebaseAuth.instance.currentUser().then((user){
setState((){this._userName= user.displayName;});
});
print(this._userName);
}
@override
Widget build(BuildContext context) {
return new Center(
child: new FlatButton(
child: new Text(this._userName),
onPressed: _getUserAuth,
),
);
}
}
stefanmuke
Updated on December 04, 2022Comments
-
stefanmuke over 1 year
I have a problem with Firebase Auth in flutter, more specifically the
user.displayName
query. I use mandatory Google Sign In at the first screen of my app, so I can guarantee that on all subsequent screens the user has a name and a userId associated with him.Every time I want to access the username however, all I do right now is essentially authenticate the user again with:
GoogleSignInAccount googleUser = await googleSignIn.signInSilently(); GoogleSignInAuthentication googleAuth = await googleUser.authentication; FirebaseUser user = await auth.signInWithGoogle( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); futureId = user.uid; print("signed in " + user.displayName); return user.displayName;
which obviously takes up unnecessary time and bandwidth.
Is there another way of doing that, since the user has already signed in once before? Could I maybe access the userdata that gets stored by Firebase Auth for use in other Firebase products (like Firestore)?
-
stefanmuke about 6 yearsThanks a lot for your answer! While the code seem to be correct, for me the function still returns null as the current username. This should theoretically not be possible since I use Firestore in the same app that is configured to require authentication on read. Do you know what could be the problem here?
-
Shady Aziza about 6 yearsIt is working just fine with me, maybe show me how are you wiring things up and I will try to help