A month of Flutter: Sign in with Google
Building on the work configuring Firebase Auth for Android and iOS, it's time to go get a user's details. This will be leveraging the already installed google_sign_in
and firebase_auth
packages.
The big change is the addition of the Auth
class.
class Auth {
Auth({
@required this.googleSignIn,
@required this.firebaseAuth,
});
final GoogleSignIn googleSignIn;
final FirebaseAuth firebaseAuth;
Future<FirebaseUser> signInWithGoogle() async {
final GoogleSignInAccount googleAccount = await googleSignIn.signIn();
// TODO(abraham): Handle null googleAccount
final GoogleSignInAuthentication googleAuth =
await googleAccount.authentication;
return firebaseAuth.signInWithGoogle(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
}
}
This class gets passed a FirebaseAuth
instance and a GoogleSignIn
instance for interactions with the external authentication services. On GoogleSignIn
the signIn
method will trigger a user account selection prompt. When the user confirms their account selection a GoogleSignInAccount
instance will be returned. On GoogleSignInAccount
I'll call authentication
to get the current user's tokens. Finally I'll exchange the GoogleSignInAuthentication
for a FirebaseUser
with signInWithGoogle
.
I added a TODO to improve error handling so it doesn't get forgotten.
The app now has an authenticated FirebaseUser
with all the accompanying details.
I'll now update SignInFab
to leverage the new Auth
service and print out the user's displayName
in the Flutter logs.
void _handleSignIn() {
auth
.signInWithGoogle()
.then((FirebaseUser user) => print('Hi ${user.displayName}'));
}
I/flutter (29142): Hi Birb Dev
SignInFab
will also need to be passed an Auth
instance in _MyHomePageState
.
SignInFab(
auth: Auth(
firebaseAuth: FirebaseAuth.instance,
googleSignIn: GoogleSignIn(),
),
)
This is what the account selector looks like on Android:
iOS prompts to allow access to google.com:
Most of the new code is actually tests and mocking the external Google and Firebase APIs. It's complected and deserves it's own article so come back tomorrow to learn more.