Google Firebase in Flutter Login

Google Firebase in Flutter Login

First Screen

Second Screen
Third Screen

Add below dependency in pubspec.yaml file:

firebase_auth: ^0.18.4+1
google_sign_in: ^4.5.3
firebase_core: ^0.5.0
Entry Point Example:
import 'package:flutter/material.dart';
import 'package:widget_tutorial/firebase/google_auth.dart';
import 'package:widget_tutorial/home.dart';

void main() {
  runApp(MaterialApp(
    home: GoogleLoginDemo(),
  ));
}
Login Page Example:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:widget_tutorial/firebase/homepage.dart';

class GoogleLoginDemo extends StatefulWidget {
  @override
  _GoogleLoginDemoState createState() => _GoogleLoginDemoState();
}

class _GoogleLoginDemoState extends State {
  FirebaseAuth _auth;
  GoogleSignIn _googleSignIn = GoogleSignIn();

  @override
  void initState() {
    initApplication();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Google Login"),
      ),
      body: Container(
        child: Column(children: [
          ElevatedButton(
            onPressed: () {
              _handleSignIn().then((value) => {
                    if (value != null)
                      {
                        goToHomePage(value),
                      }
                  });
            },
            child: Text("Google Sign In"),
          ),
        ]),
      ),
    );
  }

  void initApplication() async {
    FirebaseApp defaultApp = await Firebase.initializeApp();
    _auth = FirebaseAuth.instanceFor(app: defaultApp);
    currentUser();
  }

  Future _handleSignIn() async {
    User _user;
    bool isSignedIn = await _googleSignIn.isSignedIn();
    setState(() {
      print(isSignedIn);
    });

    if (isSignedIn) {
      _user = _auth.currentUser;
    } else {
      GoogleSignInAccount googleUser = await _googleSignIn.signIn();
      GoogleSignInAuthentication googleAuth = await googleUser.authentication;
      AuthCredential credential = GoogleAuthProvider.credential(
          accessToken: googleAuth.accessToken, idToken: googleAuth.idToken);
      _user = (await _auth.signInWithCredential(credential)).user;
    }
    return _user;
  }

  void currentUser() {
    if (_auth.currentUser != null) {
      print("Go To Home Page...");
      goToHomePage(_auth.currentUser);
    }
  }

  void goToHomePage(User _user) {
    Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => FirebaseHomePage(_user,_googleSignIn),
        ));
  }
}

Home Page Example:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:widget_tutorial/firebase/google_auth.dart';

class FirebaseHomePage extends StatefulWidget {
  User _user;
  GoogleSignIn _googleSignIn;

  FirebaseHomePage(this._user, this._googleSignIn);

  @override
  _FirebaseHomePageState createState() => _FirebaseHomePageState();
}

class _FirebaseHomePageState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Home Page"),
      ),
      body: Center(
        child: Container(
          child: Column(
            children: [
              SizedBox(
                height: 10,
              ),
              Text(widget._user.email),
              SizedBox(
                height: 10,
              ),
              ElevatedButton(
                onPressed: () {
                  print("Logout");
                  _signOut();
                },
                child: Text("Logout Here"),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _signOut() {
    setState(() {
      widget._googleSignIn.signOut();
      Navigator.pop(context);
    });
  }
}



Add below dependency in android/app/build.gradle file:

apply plugin: 'com.android.application'

apply plugin: 'com.google.gms.google-services'

apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 29

    lintOptions {
        .....
    }

    dependencies {
        implementation platform('com.google.firebase:firebase-bom:26.1.1')
        implementation 'com.google.firebase:firebase-analytics'
    }

    defaultConfig {
        applicationId "com.example.widget_tutorial"
        minSdkVersion 16
        targetSdkVersion 29
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            .....
        }
    }
}

Add below dependency in android/build.gradle file:

buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath 'com.google.gms:google-services:4.3.4'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

No comments: