Sign In With Google In Flutter Using GetX State Management

firebase_core: ^0.5.0
google_sign_in: ^4.0.14
firebase_auth: ^0.18.1
$ flutter pub get
void main() async {
await Firebase.initializeApp();
runApp(MyApp());
}
class LoginPage extends StatelessWidget {
final LoginController controller = Get.put(LoginController());

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Login'),
),
body: Padding(
padding: EdgeInsets.all(12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
FlatButton(
color: Colors.blue,
onPressed: () => controller.loginWithGoogle,
child: Center(
child: Text(
"Login with google",
style: TextStyle(color: Colors.white),
)),
)
],
),
),
);
}
}
class LoginController extends GetxController {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();

loginWithGoogle() async {
try {
final GoogleSignInAccount googleSignInAccount =
await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
final authResult = await _auth.signInWithCredential(credential);

final User user = authResult.user;
assert(!user.isAnonymous);
assert(await user.getIdToken() != null);
final User currentUser = _auth.currentUser;
assert(user.uid == currentUser.uid);
Get.toNamed('/homeView'); // navigate to your wanted page
return;
} catch (e) {
throw (e);
}
}

Future<void> logoutGoogle() async {
await googleSignIn.signOut();
Get.back(); // navigate to your wanted page after logout.
}

}

--

--

--

Flutter || Android Developer Since 2018

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Setting up Amazon Aurora to read from S3

The story behind my first English book

7 Tips to Help You Learn Programming Faster

Coding Journey Update 25/11/2020

Adaptive Navbar in Flutter by Mouli Bheemaneti

Using supervisor for process management

Amazon Elastic Kubernetes Cluster(EKS)- How to create a Managed Kubernetes Service Using AWS

Enabling NVIDIA GPUs on K3s for CUDA workloads

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Akshay Papneja

Akshay Papneja

Flutter || Android Developer Since 2018

More from Medium

How to design an adaptive Launcher icon for your app and implement using Android Studio?

Setup Flutter: IDE Configuration — Android

Image/Logo Background Removal with Flutter