Flutterexperts

Crafting Next-Gen Apps with Flutter Power
Google Sign In With Flutter

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.

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.

Andriod Configuration :

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

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

  • 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.

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.

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

Add firebase dependencies to your project.

  • 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
  • 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.
  • Go to project settings and then open the general tab.
  • Scroll down the screen and click Add app. Then we will be added the SHA key.

Implementation

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:

firebase_auth: ^latest version
google_sign_in: ^latest versioin

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 gradle.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.

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;Google sign-in with Flutter using Firebase authentication

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.

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

https://gist.github.com/ShaiqAhmedkhan/ffa2e941bd94916abdcbf1b967c8739f#file-login_screen-dart

You will see a full code on 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.

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:

flutter-devs/flutter_google_sign_in_demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a 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 FacebookGitHubTwitter, 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.


Leave comment

Your email address will not be published. Required fields are marked with *.