X
    Categories: Flutter

Flutter Google Login Integration Using Firebase

 

Flutter firebase google login :

Flutter firebase google login is used to authenticate users into flutter app this is also considered as a easiest way to authenticate.

Implementing login mechanism requires a good knowledge on back end and front end services although you may be well-versed in front end code but back end will be trouble.

To avoid the back end server maintenance and server side coding we make use of firebase which makes it much easier and better for even beginners to start developing these apps.

Firebase has several other services analytics, push notifications and login using different providers like phone based authentication, google, facebook based login integration.

In the series of tutorials we have covered flutter firebase authentications and integrations by using which we have dealt with dynamic links can have a look here.

pubspec.yaml :

Add the necessary dependencies for firebase authentications, firebase core and google sign in to make use of google properties.

dependencies:
  flutter:
    sdk: flutter
  firebase_auth:
  firebase_core:
  google_sign_in: ^5.2.0

 

main.dart :

Initialize void main with async and initialize firebase as below.

WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();

 

Specify App inside runApp()

runApp(App());

Now specify the StatelessWidget App class

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Login"),),
        body: MyApp(),
      ),
    );
  }
}

 

Specify the GoogleSignIn and String variable to populate information every time based on login and logout.

 

String welcome = "Login with Google";

final GoogleSignIn googleSignIn = GoogleSignIn();

GoogleSignInAccount? googleUser;

 

 

Add signIn() method with async

Future<UserCredential> signIn() async {

  GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();

  setState(() {
    welcome = googleUser!.email;
  });

  final GoogleSignInAuthentication? googleAuth =  await googleUser!.authentication;

  final credential =  GoogleAuthProvider.credential(
    accessToken: googleAuth?.accessToken,
    idToken: googleAuth?.idToken,
  );

  return await FirebaseAuth.instance.signInWithCredential(credential);

}

 

Add signOut() method with async

Future<void> signOut() async {
  googleSignIn.disconnect();
  setState(() {
    welcome = "Logged out";
  });

}

 

Add Text Button’s to make Login and Logout based on the above declared async methods.

 

TextButton(onPressed: (){
  signIn();
}, child: const Text("Login",style: const TextStyle(fontSize: 20.0),)),


TextButton(onPressed: (){
  signOut();
}, child: const Text("Logout",style: const TextStyle(fontSize: 20.0),)),

 

Now add a Text Widget to display status accordingly

 

Padding(
  padding: const EdgeInsets.all(20.0),
  child: Text(welcome,style: const TextStyle(fontSize: 30.0),),
),

 

Also we will be specifying the init() block to access the user information on app start for flutter firebase google login.

@override
void initState() {
  // TODO: implement initState
  super.initState();
  googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount? account){
    setState(() {
      googleUser = account;
    });

    if(googleUser!= null){
      // Perform your action
    }
    googleSignIn.signInSilently();

  });
}

 

Providing the full code for flutter firebase google login.

 

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';

Future<void> main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(App());
}

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Login"),),
        body: MyApp(),
      ),
    );
  }
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {

  String welcome = "Login with Google";

  final GoogleSignIn googleSignIn = GoogleSignIn();

  GoogleSignInAccount? googleUser;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount? account){
      setState(() {
        googleUser = account;
      });

      if(googleUser!= null){
        // Perform your action
      }
      googleSignIn.signInSilently();

    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Padding(
            padding: const EdgeInsets.all(20.0),
            child: Text(welcome,style: const TextStyle(fontSize: 30.0),),
          ),

          TextButton(onPressed: (){
            signIn();
          }, child: const Text("Login",style: const TextStyle(fontSize: 20.0),)),
          TextButton(onPressed: (){
            signOut();
          }, child: const Text("Logout",style: const TextStyle(fontSize: 20.0),)),


        ],
      ),
    );
  }

  Future<UserCredential> signIn() async {

    GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();

    setState(() {
      welcome = googleUser!.email;
    });

    final GoogleSignInAuthentication? googleAuth =  await googleUser!.authentication;

    final credential =  GoogleAuthProvider.credential(
      accessToken: googleAuth?.accessToken,
      idToken: googleAuth?.idToken,
    );

    return await FirebaseAuth.instance.signInWithCredential(credential);

  }

  Future<void> signOut() async {
    googleSignIn.disconnect();
    setState(() {
      welcome = "Logged out";
    });

  }

}



Output :

This image below depicts the usage of flutter firebase google login.

 

If you have any query’s in the implementation of flutter firebase google login do let me know in the comment section below.

If you like this tutorial do like and share us for more interesting updates.

 

abhishek:
Related Post

This website uses cookies.