What we will create in this article?
We will create a simple screen with google login.
For getting this we must have a google account for creating a firebase console account. If you have already a Google account then continued on that otherwise create an account.
Steps to follow
First of all, create a new project and make your project compatible with Androidx.
If your project is compatible with Androidx then skip this step and move forward otherwise follow the steps.
How to Migrate Flutter project to Compatible with Androidx?
For migrating an existing flutter project to Androidx we have two methods.
- One is a very simple method is that open your existing flutter project in Android Studio and from the menu select Refactor and choose Migrate to AndroidX, which converts all project with compatible to Androidx with a single click.
- The second is to migrate manually with copy and paste the Androidx compatible code to the Gradle files and properties. follow this article to learn how to migrate a Flutter project to Androidx compatible?
Create a Project in Firebase console.
Open your Firebase console and click on Add project.
Now you have to provide Android Package Name. You can get Package name in the App level build.gradle file with named applicationId. After this create the SHA1 key. SHA1 key can be generated by the command.
keytool -list -v -keystore "C:\Users\yourusernamehere\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
in the place of
yourusernamehere
write your PC User Name and press enter You will get your SHA1 key.
Now fill the entire fields correctly and click on Register. and Download google-services.json file.
Paste the JSON file into android’s app directory and add the Firebase SDK by adding classpath ‘com.google.gms:google-services:4.3.2’ into Project-level Gradle file and add Dependency implementation ‘com.google.firebase:firebase-analytics:17.2.0’ and Add to the bottom of the file apply plugin: ‘com.google.gms.google-services’ into the App-level Gradle file and hot restart your project. Now you will see that the app is successfully connected with firebase.
Add Dependencies into your pubspec.yaml file.
Add the following dependencies into pubspec.yaml
firebase_core: any firebase_auth: any cloud_firestore: any google_sign_in: any
Replace the code of main.dart with
main.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() => runApp(App()); class App extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'SignIn with Google', debugShowCheckedModeBanner: false, theme: ThemeData( primaryColor: Colors.deepPurple, ), home: HomePage(), ); } }
Enable google authentication from the firebase console. To enable Google auth, go inside your projects and click on Authentication and on the Authentication page click on the sign-in-method tab and enable google auth.
Now create a new dart file for HomeScreen.
HomePage.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:google_sign_in/google_sign_in.dart'; final GoogleSignIn googleSignIn = GoogleSignIn(); final FirebaseAuth firebaseAuth = FirebaseAuth.instance; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State { bool isAuth = false; @override void initState() { super.initState(); googleSignIn.onCurrentUserChanged.listen((account){ handleSignIn(account); },onError: (err){ print("signin !$err"); }); googleSignIn.signInSilently(suppressErrors: false).then((account){ handleSignIn(account); }).catchError((err){ print('Error signin $err'); }); } handleSignIn(GoogleSignInAccount account){ if(account != null){ setState(() { isAuth = true; }); }else{ setState(() { isAuth = false; }); } } login() async{ 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 authResult = await firebaseAuth.signInWithCredential(credential); final FirebaseUser user = authResult.user; final FirebaseUser currentUser = await firebaseAuth.currentUser(); } logout(){ googleSignIn.signOut(); } Widget buildAuthScreen(){ return Scaffold( body: Center( child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [ CircleAvatar( backgroundImage: NetworkImage( googleSignIn.currentUser.photoUrl), radius: 75,), Text(googleSignIn.currentUser.displayName, style: TextStyle(fontSize: 25),), RaisedButton( onPressed: logout, child: Text("Logout", style: TextStyle(fontSize: 35),),) ], ), ), ); } Scaffold buildUnAuthScreen(){ return Scaffold( body: Container(width: 500, decoration: BoxDecoration( gradient: LinearGradient(colors: [ Theme.of(context).primaryColor, Theme.of(context).accentColor, ],begin: Alignment.topRight, end: Alignment.bottomLeft ), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text("Google login", style:TextStyle(fontSize: 55), ), GestureDetector( child: Container( child: Card( child: Text("SignIn with Google", style: TextStyle( fontSize: 45, fontWeight: FontWeight.bold ), ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(25) ), elevation: 10, ), ), onTap: login, ), ], ), ), ); } @override Widget build(BuildContext context) { return isAuth ? buildAuthScreen() : buildUnAuthScreen(); } }
Now when you run your app you will get exceptional platform error that your app is missing support for the following URL schemes: com.googleusercontent.apps…..
To remove the above error we must authenticate our project with google cloud API.
Click on this link and go to your projects cloud platform and inside your project’s name click on OAuth consent screen and make the changes with uploading the application logo and copy the highlighted URL in all text fields with http:// or https://
Now run your App it will work properly.
Output:
I am passionate about learning and teaching new technology. Here You will get all information about Flutter, Laravel and New Technologies.
Very good articles