Flutter - Google Sign in UI and Authentication - GeeksforGeeks

16 Jan, 2022
 In this article, we will look into how to make a beautiful Google Sign In screen and authenticate the same with Google. 
To do so follow the below steps:
Step 1: First create the flutter project in your  IDE.
Step 2: After that just remove the default code and start from scratch.
Step 3: Now just import the material library and call the runApp( ) function into the main function name as GoogleSignIn. 
     
 Step 4: Now make a stateful widget with the name ‘GoogleSignIn‘.
Dart
// main.dart fileimport 'package:firebase_core/firebase_core.dart';import 'package:flutter/material.dart';import 'package:GoogleSignIn/SignInScreen.dart'; void main() async {  WidgetsFlutterBinding.ensureInitialized();     // initializing the firebase app  await Firebase.initializeApp();      // calling of runApp  runApp(GoogleSignIn());  } class GoogleSignIn extends StatefulWidget {  GoogleSignIn({Key key}) : super(key: key);   @override  _GoogleSignInState createState() => _GoogleSignInState();} class _GoogleSignInState extends State<GoogleSignIn> {  @override  Widget build(BuildContext context) {         // we return the MaterialApp here ,    // MaterialApp contain some basic ui for android ,    return MaterialApp(                //materialApp title      title: 'GEEKS FOR GEEKS',       debugShowCheckedModeBanner: false,      theme: ThemeData(        primarySwatch: Colors.green,      ),             // home property contain SignInScreen widget      home: SignInScreen(),      );  }}
 
 
Here we return the MaterialApp( ) where  title property  is ‘GEEKS FOR GEEKS’, the home property is SignInScreen.
 
Now let’s create the SignInScreen() widget that we have given to the home property. Now, before creating SignInScreen(), we have to create a project on firebase.
 
Step 5: Now simply return the scaffold. In the scaffold body, we have a container for the gradient decorations as shown below:
 
 
Step 6: Now there is a card child property that contains a column widget, In the column widget, we have a first widget text contain ‘ Geeks for Geeks’:
 
 
Step 7: The second widget is a material button which contains child property in which there is a Row, Row has is children’s, first there is a google logo and second is a text ‘ google sign in’, In on pressed we call the function signIn. Let’s create it.
 
 
Our screen contains in the center “google sign in ” and below this there is a button of signup by which we have a sign up successfully and move to the home screen.
 
Dart
//SignInScreen import 'package:firebase_auth/firebase_auth.dart';import 'package:flutter/material.dart';import 'package:google_sign_in/google_sign_in.dart';import 'package:GoogleSignIn/homepage.dart';  class SignInScreen extends StatefulWidget {  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: BoxDecoration(          gradient: LinearGradient(            colors: [              Colors.blue,              Colors.red,            ],          ),        ),        child: Card(          margin: EdgeInsets.only(top: 200, bottom: 200, left: 30, right: 30),          elevation: 20,          child: Column(            mainAxisAlignment: MainAxisAlignment.spaceEvenly,            children: [              Text(                "GEEKS FOR GEEKS",                style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),              ),              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: BoxDecoration(                          image: DecorationImage(                              image:                                  AssetImage('assets/images/googleimage.png'),                              fit: BoxFit.cover),                          shape: BoxShape.circle,                        ),                      ),                      SizedBox(                        width: 20,                      ),                      Text("Sign In with Google")                    ],                  ),                                     // by onpressed we call the function signup function                  onPressed: ()                    signup(context);                   },                ),              )            ],          ),        ),      ),    );  }}
 
 
Our Signup screen looks pretty,
 
 
Now create a function named signup.
 
Step 8: Now just import the auth and google_sign up from the library.
 
 
Step 9: Now we have created an auth instance of type FirebaseAuth. We have made a request of GoogleSignIn, It signup by user credentials. If the result is not Null, we simply call the pushReplacement function to navigate to the home screen.
 
See the code below:
 
Dart
// function to implement the google signin // creating firebase instancefinal FirebaseAuth auth = FirebaseAuth.instance;    Future<void> signup(BuildContext context) async {    final GoogleSignIn googleSignIn = GoogleSignIn();    final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();    if (googleSignInAccount != null) {      final GoogleSignInAuthentication googleSignInAuthentication =          await googleSignInAccount.authentication;      final AuthCredential authCredential = GoogleAuthProvider.credential(          idToken: googleSignInAuthentication.idToken,          accessToken: googleSignInAuthentication.accessToken);             // Getting users credential      UserCredential result = await auth.signInWithCredential(authCredential);       User user = result.user;            if (result != null) {        Navigator.pushReplacement(            context, MaterialPageRoute(builder: (context) => HomePage()));      }  // if result not null we simply call the MaterialpageRoute,        // for go to the HomePage screen    }  }
  
Don’t  forget to add dependencies in pubspec yaml file.
firebase_auth: ^1.0.3
google_sign_in: ^5.0.1
Note : Use the latest available version of the package.
 
Now let’s create the Homescreen.
 
Step 10: Our home screen contains only a simple text “home screen ” with an appbar titled ‘GEEKS FOR GEEKS’ in green color.
 
 
Dart
// Home page screen import 'package:flutter/material.dart';class HomePage extends StatefulWidget {  HomePage({Key? key}) : super(key: key);   @override  _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> {  @override  Widget build(BuildContext context) {    return Scaffold(      appBar: AppBar(        backgroundColor: Colors.green,        centerTitle: true,                 // on appbar text containing 'GEEKS FOR GEEKS'        title: Text("GEEKS FOR GEEKS"),                  // In body text containing 'Home page ' in center        body: Center(child:Text('Home page'),    );  }}
 
 
This is how the home screen will look like:
 
 
Output : 
 
 
adnanirshad158
android
Flutter UI-components
Android
Dart
Flutter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Android Listview in Java with Example
Retrofit with Kotlin Coroutine in Android
Listview.builder in Flutter
Flutter - DropDownButton Widget
Flutter - Asset Image
Splash Screen in Flutter
Flutter - Custom Bottom Navigation Bar