Google Sign In With Flutter
![google sign in with flutter](https://devblog.link/wp-content/uploads/2022/07/Google_signin_with_flutter.png)
In this article, we will look into how to make a beautiful Google Sign In using Firebase authentication in your flutter application.
Check out other state-management related article over devblog.link.
Google Sign In
- Before consolidating the coding structure, there is a requirement for the usage of plugins and resources. Mostly, three plugins are required for the task. This plugins include google_sign_in firebase_auth and firebase_core.
Firebase Project Setup
Open the Firebase console and click the “Add project” option. Create project on console, Here the of project is set to Skeleton-flutter
![](https://devblog.link/wp-content/uploads/2022/07/google_consol-1024x537.png)
The platform might take some time to go through your application. Once completed, then click the continue option to open the overview page of the project you made.
IOS Configuration :
Register IOS app to Firebase, and iOS bundle Id must be the same in the Xcode project and on firebase console.
![](https://devblog.link/wp-content/uploads/2022/07/register_app_ios.png)
Download configuration files for your app and adds it to your project folder of iOS.
![](https://devblog.link/wp-content/uploads/2022/07/google_info_plist.png)
- Move or copy
GoogleService-Info.plist
into the[my_project]/ios/Runner
directory. - Open Xcode, then right-click on
Runner
directory and selectAdd Files to "Runner"
. - Select
GoogleService-Info.plist
from the file manager. - A dialog will show up and ask you to select the targets, select the
Runner
target. - Then add the
CFBundleURLTypes
attributes below into the[my_project]/ios/Runner/Info.plist
file.
<!-- Put me in the [my_project]/ios/Runner/Info.plist file -->
<!-- Google Sign-in Section -->
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<!-- TODO Replace this value: -->
<!-- Copied from GoogleService-Info.plist key REVERSED_CLIENT_ID -->
<string>com.googleusercontent.apps.861823949799-abcdxyz</string>
</array>
</dict>
</array>
<!-- End of the Google Sign-in Section -->
Android Configuration :
Register your android app In Firebase.
Add your application Id in your app-level build. Gradle or AndroidManifest.xml file.
Add app name for project(optional)
Generate SHA-1 from debug app and add it while registering app.
Read my another article to know how to Generate SHA-1 fingerprint of keystore certificate.
![](https://devblog.link/wp-content/uploads/2022/07/add_android_app.png)
Now download the google-services.json. Move the downloaded google-serivces.json file into your Android app module root directory.
![](https://devblog.link/wp-content/uploads/2022/07/Screenshot-2022-07-05-at-11.05.56-AM-1024x515.png)
After adding google-service.json file to project app folder add dependencies for android platform in Project level build.gradle file.
You can find following code from app registering instruction from firebase.
![](https://devblog.link/wp-content/uploads/2022/07/Screenshot-2022-07-05-at-11.05.31-AM-1024x798.png)
Lastly add google service plugin on App-level build-gradle file that is:
apply plugin: 'com.google.gms.google-services'
![](https://devblog.link/wp-content/uploads/2022/07/Screenshot-2022-07-05-at-11.37.55-AM-1024x182.png)
That’s it, all configuration are done from android side.
Authentication
- On your firebase console go to Authentication section.
![](https://devblog.link/wp-content/uploads/2022/07/google_authenticate-1024x473.png)
- Click set up the sign-in method.
- Presently edit google sign-in, and you need to enter the project name and support email. Empower this by tapping the switch on the upper right corner. At that point, click Save.
![](https://devblog.link/wp-content/uploads/2022/07/Screenshot-2022-07-04-at-8.19.06-PM-1024x718.png)
Implementation
Add above plugin in pubspec.ymal file in your flutter project.
![](https://devblog.link/wp-content/uploads/2022/07/Screenshot-2022-07-04-at-7.46.28-PM-300x136.png)
Initialise Firebase at very starting of the app;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// initializing the firebase app
await Firebase.initializeApp();
// calling of runApp
runApp(MyApp());
}
Create Sign in screen for making user interaction like screen_login.dart in lib folder:
import 'package:flutter/material.dart';
import 'package:skeleton_flutter/view/screens/auth/social_media_login_helper.dart';
class SignInScreen extends StatefulWidget {
const SignInScreen({Key? key}) : super(key: key);
@override
SignInScreenState createState() => SignInScreenState();
}
class SignInScreenState extends State<SignInScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
width: double.infinity,
height: double.infinity,
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.blue,
Colors.red,
],
),
),
child: Card(
margin: const EdgeInsets.only(top: 200, bottom: 200, left: 30, right: 30),
elevation: 20,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Padding(
padding: const EdgeInsets.only(left: 20, right: 20),
child: MaterialButton(
color: Colors.teal[100],
elevation: 10,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
height: 30.0,
width: 30.0,
decoration: const BoxDecoration(
image: DecorationImage(
image:
AssetImage('assets/images/google_icon.png'),
fit: BoxFit.cover),
shape: BoxShape.circle,
),
),
const SizedBox(
width: 20,
),
const Text("Sign In with Google")
],
),
// by on Pressed we call the function signup function
onPressed: ()=> SocialMediaAuth.signInWithGoogle(),
),
)
],
),
),
),
);
}}
The above code will look like following;
![flutter google sign in](https://devblog.link/wp-content/uploads/2022/07/Screenshot-2022-07-04-at-8.44.29-PM-502x1024.png)
On Pressing button will call Google sign in code : onPressed:()=> SocialMediaAuth.signInWithGoogle()
Create Login helper class for global project:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_sign_in/google_sign_in.dart';
class SocialMediaAuth{
static Future<dynamic> signInWithGoogle() async {
final FirebaseAuth auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();
GoogleSignInAccount? googleSignInAccount = await googleSignIn.signIn();
if (googleSignInAccount != null) {
GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication;
AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
UserCredential authResult = await auth.signInWithCredential(credential);
var user = authResult.user;
if(user !=null) {
assert(!user.isAnonymous);
Get.defaultDialog(
title: "User Info",
middleText: "User Name: ${user.displayName} \n\n User Email ${user.email}",
titleStyle: const TextStyle(color: Colors.black),
middleTextStyle: const TextStyle(color: Colors.black),
radius: 30,
actions: [
TextButton(
child: const Text("SignOut"),
onPressed: () {
googleSignIn.signOut();
Get.back();
}
),
],
);
Get.log("User Name: ${user.displayName}");
Get.log("User Email ${user.email}");
}
}
else{
//TODO: Handel google login failure
Get.log("Login Failed");
}
}
}
We display dialog after successful authentication of user and display info on it.
![google sign in flutter](https://devblog.link/wp-content/uploads/2022/07/google_sign_in.gif)
Conclusion
In the blog, I have explained the basic architecture of Google Sign In, you can modify this code according to your choice, and this was a small introduction of Google Sign-In using Firebase authentication from my side and its working using Flutter.
I hope this blog will provide you with sufficient information in Trying up Google Sign-In in your flutter projects.