Google Sign In With Flutter

Google sign-in with Flutter using Firebase authentication

Shaiq khan
Jul 29 · 8 min read
Image for post

Firebase authentication, for the most part, helps bolster diverse user authentication certifications. It is, for the most part, a mobile backend as a service that presents you with amazing highlights for the advancement of flutter applications. It further aids in giving SDKs and instant UI libraries. This assists with validating your clients for utilizing the application. There are additionally extraordinary authentication highlights supported. This incorporates passwords, telephone numbers, virtual character suppliers through Google, Facebook, Twitter, and substantially more.

In this article, I will be exploring Google Sign In With Flutter and show demo implement Google sign-in using Firebase authentication in your flutter application.

Table of Content :

Flutter 1.7

Google Sign In

Firebase Project Setup

Authentication

Implementation — Setup Configuration

Code Implement

Code File

Conclusion



Flutter 1.7

After the launch of Flutter 1.7, one of the principal things that should have been fixed was AndroidX incompatibilities. Since this has been dealt with the progressions executed in the last half, through Flutter, you will have the option to build up another venture. This should be possible with the assistance of the AndroidX banner to guarantee that the defined activities focus on the new help library.

The library permits developers to update Android applications without stressing over in reverse similarity. Besides, it has thought of help for building portable applications, satisfying about 64 bits of Android applications. This will be conceivable in solitary accommodation. The other improved highlights remembered for Flutter 1.7 are RangeSlide Widget, OpenType Rich Typography Features, Gamer Controller Support, thus substantially more.

Google Sign In

There are a couple of new advances you need to do so as to utilize Google sign in your application. Without finishing every one of these means, in the event that you attempt to utilize Google sign in, your application will simply crash. How about we perceive how to set up Google sign-in utilizing Firebase.

  • Before consolidating the coding structure, there is a requirement for the usage of plugins and resources. Mostly, two plugins are required for the task. This incorporates firebase_auth and google_sign_in.
  • Regarding resources, there is just one picture required that will help in planning the Google Sign in the application.

Firebase Project Setup

Open the Firebase console and click the “Add project” option.

Image for post

Now choose a Cloud Firestore location

Now read and acknowledge the Terms and Conditions

When done, look down and click “Create Project.”

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.

Image for post

Andriod Configuration :

Register your android app, which is generally your application Id in your app-level build. Gradle.

Image for post

Now download the google-services.json. Move the downloaded google-serivces.json file into your Android app module root directory.

Image for post
  • Add your project level build.gradle file.
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.3'
}
  • Add your project app-level build. Gradle file
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.google.firebase:firebase-analytics:17.2.2'}
apply plugin: 'com.google.gms.google-services'
  • Click on Continue to console and wait for few seconds, and your application will be successfully added with Firebase.
Image for post

Now you have added Firebase to the Flutter app successfully.

IOS Configuration :

Register IOS app to Firebase, and iOS bundle Id must be the same in the Xcode project and on firebase console.

Image for post

Download configuration files for your app and adds it to your project folder.

Image for post

Add firebase dependencies to your project.

Image for post
  • Make the changes needed in the AppDelegate as suggested by the setup wizard then choose next.
  • Presently check the root folder to run the application. After some time, you may see the setup wizard showing that the application has been remembered for Firebase. Then choose “Continue to the Console” to finish the setup.
  • Presently check the root organizer to run the application. After some time, you may see the arrangement wizard indicating that the application has been remembered for Firebase. At that point, pick “Proceed to the Console” to finish the arrangement.

Authentication

  • Click on the Authentication
Image for post
  • Click set up the sign-in method.
Image for post
  • 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.
Image for post
  • Go to project settings and then open the general tab.
Image for post
  • Scroll down the screen and click Add app. Then we will be added the SHA key.
Image for post

Implementation

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:

firebase_auth: ^0.16.0
google_sign_in: ^4.4.4

Step 2: Add Assets

Add assets to pubspec — yaml file.

We will add images in the assets folder

assets:
- assets/

Step 3: Import

import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';

Step 4: Run flutter packages get in the root directory of your app.

Step 5: We will now create an instance of FirebaseAuth and GoogleSignIn.

final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();

Step 6: Enable AndriodX

Add this to your grade.properties file:

org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true

How to implement code in dart file:

You need to implement it in your code respectively:

Create a new dart file called login_screen.dart inside the lib folder.

SingleChildScrollView(
child:Column(
children: <Widget>[
Container(
height: deviceSize.height/2.4,
width: deviceSize.width/3,
decoration: BoxDecoration(
image: DecorationImage(
image:
AssetImage('assets/weddinglogo.png'),
),),),
Container(
child: Form(
key: _userLoginFormKey,
child: Padding(
padding: const EdgeInsets.only(top:5.0,bottom:15,left: 10,right: 10),
child: Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(15.0),
child: Text("Login",style:TextStyle(fontWeight: FontWeight.w800,fontSize: 25),),
),
Padding(
padding: const EdgeInsets.only(top:15.0,right: 14,left: 14,bottom: 8),
child: TextFormField(
controller: model.userIdController,
style: TextStyle(color: Colors.black,fontWeight:FontWeight.bold,fontSize: 15),
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius
.all(
Radius.circular(15)),
),
hintText: "Email",
hintStyle: TextStyle(fontSize: 15) ,
contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
),
cursorColor:Colors.black,
keyboardType: TextInputType.emailAddress,
inputFormatters: [
BlacklistingTextInputFormatter
.singleLineFormatter,
],),),
Padding(
padding: const EdgeInsets.only(top:5.0,right: 14,left: 14,bottom: 8),
child: TextFormField(
controller: model.passwordController,
obscureText: !model.passwordVisible,
style: TextStyle(color: Colors.black,fontWeight:FontWeight.bold,fontSize: 15),
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius
.all(
Radius.circular(15)),
),
hintText: "Password",
contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
hintStyle: TextStyle(fontSize: 15) ,
suffixIcon: IconButton(
icon: Icon(model
.passwordVisible
? Icons.visibility
: Icons.visibility_off,color: Color(0xFFE6E6E6),),
onPressed: () {
model.passwordVisible =
!model
.passwordVisible;
}),),
cursorColor:Colors.black,
inputFormatters: [
BlacklistingTextInputFormatter
.singleLineFormatter,
],),),
SizedBox(height: 16,),
InkWell(
child: Container(
width: deviceSize
.width/2,
height: deviceSize.height/18,
margin: EdgeInsets.only(top: 25),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color:Colors.black
),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
height: 30.0,
width: 30.0,
decoration: BoxDecoration(
image: DecorationImage(
image:
AssetImage('assets/google.jpg'),
fit: BoxFit.cover),
shape: BoxShape.circle,
),
),
Text('Sign in with Google',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
color: Colors.white
),
),
],
)
)
),
onTap: ()
async{
hp signInWithGoogle(model)
.then((FirebaseUser user){
model.clearAllModels();
Navigator.of(context).pushNamedAndRemoveUntil
(RouteName.Home, (Route<dynamic> route) => false
);}
).catchError((e) => print(e));
},
),
SizedBox(height: 16,),
],),
),),
),),
],),
),

In this login screen, we will add a logo, two text fields, and sign with the Google button. Login Screen should be a Stateful Widget since we will roll out certain improvements to the UI later, which will require the widgets to be redrawn.

Image for post

Now we have to design the Sign in with Google button inside the function signInWithGoogle.

Future<FirebaseUser> signInWithGoogle(SignInViewModel model) async {
model.state =ViewState.Busy;
GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn(); GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication; AuthCredential credential = GoogleAuthProvider.getCredential( accessToken: googleSignInAuthentication.accessToken, idToken: googleSignInAuthentication.idToken, ); AuthResult authResult = await _auth.signInWithCredential(credential); _user = authResult.user; assert(!_user.isAnonymous); assert(await _user.getIdToken() != null); FirebaseUser currentUser = await _auth.currentUser(); assert(_user.uid == currentUser.uid);
model.state =ViewState.Idle; print("User Name: ${_user.displayName}");
print("User Email ${_user.email}");
}

In the signInWithGoogle strategies, we need to utilize the Google sign-in information to authenticate a FirebaseUser and afterward return that user.

If Google sign-in is successful, we will be taken to the HomeScreen which we will be implementing next.

Create a new dart file called home_screen.dart inside the lib folder.

body: Container(
child: Padding(
padding: const EdgeInsets.all(48.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Center(
child: Text(
'Welcome User',
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
color: Colors.black54),
),
),
SizedBox(height: 40),
Image.asset("assets/girl.jpg",scale: 5,),
SizedBox(height: 40),
RaisedButton(
onPressed: () {
signOutGoogle();
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) {return LoginScreen();}), ModalRoute.withName('/'));
},
color: Colors.black,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Sign Out',
style: TextStyle(fontSize: 25, color: Colors.white),
),
),
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(40)),
)
],
),
),
),

In this screen, we will add a title, image, and sign out button.HomeScreen Should be a Stateful / Stateless Widget.

Image for post

Now we have to design the Sign Out button inside the function signoutGoogle.

void signOutGoogle() async{
await _googleSignIn.signOut();
print("User Sign Out");
}

In the signOutGoogle methods, we have to just sign out of the current Google account.

Code File

You will see a full code on a GitHub, and this is a small demo program to integrate with Google Sign-In using Firebase authentication, and the below video shows how Google Sign-In will work.

Image for post

Conclusion

In the article, 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. This is a demo program that will integrate Google Sign-In using firebase authentication in a flutter, So please try it.

❤ ❤ Thanks for reading this article ❤❤


If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

find the source code of the Flutter Google Sign In Demo:


FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.


Image for post

FlutterDevs

FlutterDevs intent to deliver Flutter apps with high…

Shaiq khan

Written by

Flutter Developer

FlutterDevs

FlutterDevs intent to deliver Flutter apps with high quality. We’ve adopted Design First attitude which helps us deliver applications of highest quality.

Shaiq khan

Written by

Flutter Developer

FlutterDevs

FlutterDevs intent to deliver Flutter apps with high quality. We’ve adopted Design First attitude which helps us deliver applications of highest quality.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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