SocialMedia Authentication In Flutter

Social Media Authentication For Android In Flutter

Hello guys, in current Mobile Application trends you might have seen many Mobile Applications that have a Social Media Authentication. so we will discuss the same how to implement SocialMedia Authentication for Android in Flutter Mobile Application.

What we will learn?

First, implement Google authentication for Android in Flutter.

Second, implement Facebook authentication for Android in Flutter.

Create a new project and follow the below steps:-

At the time we are discussing this article, I am using the latest version for Google Sign In, Flutter Facebook Login, HTTP, etc.

Add all plugins like below:

google_sign_in: ^6.2.1,
flutter_facebook_login: ^3.0.0,
http: ^1.2.1

in pubspec.yaml file.

Steps for how to integrate Google authentication:

Step 1: First add Google Sign In plugin in pubspec.yaml file. Run command flutter pub get in the terminal.

Import the plugin file in the dart file.

import 'package:google_sign_in/google_sign_in.dart';

Step 2: To the register app with Firebase Console. We need to add our project details like the app package name, SHA – 1 key for authentication.

SHA – 1 key command:- 

keytool -list -v -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore

Enter the above command and enter the password is “android”. Now SHA – 1 key display in the command prompt. Copy SHA – 1 key and paste in the Firebase Console.

Step 3: Add the latest google-services.json file in the project android -> app folder path mentioned from our project directory (project_location\android\app). Now we need to update our project-level & app-level build.gradle file.

Project-level build.gradle file change:-

File path:- project_location\android\build.gradle

Project Level build.gradle file
Project-level build.gradle file
App-level build.gradle file change:-

File path:- project_location\android\app\build.gradle

App Level build.gradle file change-1
App-level build.gradle file change-1
App Level build.gradle file change-2
App-level build.gradle file change-2

Now our app is registered with Firebase successfully.

Step 4: Go to Firebase Console and open the Authentication option Click on the Sign-in method tab then enable Google from Sign-in providers.

Enable Google Authentication Permission
Enable Google authentication permission

Get more details about Firebase with Flutter.

Now let’s code.

Create variables for Google authentication:-
  • _isGoogleLoggedIn variable is used to check the current user is sign-in as Google.
  • _googleSignIn is the object of GoogleSignIn class. It is used for Google login and logout functionality.
bool _isGoogleLoggedIn = false;
GoogleSignIn _googleSignIn = GoogleSignIn(scopes: ['email'],);
Create an outline button for call _googleLogin() method:-
Widget _googleSignInButton() {
    return OutlineButton(
      splashColor: ColorConstants.kgreyColor,
      onPressed: () {
        _googleLogin();
      },
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),
      highlightElevation: 0,
      borderSide: BorderSide(color: ColorConstants.kgreyColor),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image(
                image: AssetImage("assets/images/google_logo.png"),
                height: 35.0),
            Padding(
              padding: const EdgeInsets.only(left: 10),
              child: Text(
                'Sign in with Google',
                style: GoogleFonts.alata(
                  fontSize: 20,
                  fontWeight: FontWeight.w500,
                  color: ColorConstants.kgreyColor,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
Google Button
Google button
Google sign-in method code:-
_googleLogin() async {
    try {
      await _googleSignIn.signIn();
      setState(() {
        _googleSignIn.currentUser != null ?
        _isGoogleLoggedIn = true : _isGoogleLoggedIn = false;
      });
    } catch (err) {
      print(err);
    }
  }
Create an outline button for call _googleLogout() method:-
Widget _googleSignOutButton() {
    return OutlineButton(
      splashColor: ColorConstants.kgreyColor,
      onPressed: () {
        _googleLogout();
      },
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),
      highlightElevation: 0,
      borderSide: BorderSide(color: ColorConstants.kgreyColor),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(left: 10),
              child: Text(
                'Sign out',
                style: GoogleFonts.alata(
                  fontSize: 20,
                  fontWeight: FontWeight.w500,
                  color: ColorConstants.kgreyColor,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
Google sign-out method:-
_googleLogout() {
    _googleSignIn.signOut();
    setState(() {
      _isGoogleLoggedIn = false;
    });
  }
How to display Google’s current logged in user data? 

We can get a current sign-in Google user detail by GoogleSignIn class object. Here _googleSignIn is an object of GoogleSignIn class.

CircleAvatar(
  backgroundColor: ColorConstants.kgreyColor,
  radius: 37,
  child: CircleAvatar(
    backgroundImage: NetworkImage(
      _googleSignIn.currentUser.photoUrl,),
    radius: 35,
  ),
),
Text(_googleSignIn.currentUser.displayName,
  style: GoogleFonts.alata(
    fontSize: 25,
    fontWeight: FontWeight.w500,
    color: ColorConstants.kblackColor,
  ),
),

We will get Google authentication output like below:

Google Authentication

Google authentication

Steps for How to integrate Facebook authentication:

Step 1: First add Flutter Facebook Login and HTTP plugins in the pubspec.yaml file. Run command flutter pub get in the terminal.

Import the plugin files in the dart file.

import 'package:flutter_facebook_login/flutter_facebook_login.dart';
import 'package:http/http.dart' as http;

Step 2: To the register Flutter app in Facebook Developers. Click on the “Create a new app” button then choose the option “For Everything Else“. 

Add our project name, and email address to Facebook Developers.

Now click on the button “Create App ID” then click on the checkbox. Again click on the “Submit” button.

Our new app created with a app id of Facebook in the dashboard. We need to complete all remaining steps define in Facebook Developers.

Similarly, we need to add our project details like the package name, default activity class name then need to update the app-level build.gradle file.

File path:- project_location\android\app\build.gradle

App Level build.gradle - file
App-level build.gradle – file

Step 3: Go to this path and create a new strings.xml file. 

project_location\android\app\src\main\res\values

In a string.xml file facebook_app_id, and fb_login_protocol_scheme values copy from Facebook Developers. So our string.xml file looks like below:

string.xml - file
string.xml – file

Step 4: Add internet permission, add meta-data, and activity of Facebook in the AndroidManifest.xml file. Add our app package name and default activity class name on Facebook Developers.

File path:- project_location\android\app\src\main\AndroidManifest.xml

AndroidManifest.xml - file
AndroidManifest.xml – file

Step 5: Download openssl windows setup then extract the zip file and open the command prompt. Go to installed JDK directory then run the below command to generate key hashes.

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Admin\.android\debug.keystore" | "C:\Users\Admin\Downloads\openssl-0.9.8k_X64\bin\openssl" sha1 -binary | "C:\Users\Admin\Downloads\openssl-0.9.8k_X64\bin\openssl" base64

Now enter a password “android” and generate key hashes in the command prompt. This key copy from the command prompt and paste into Facebook Developers.

The new app is registered on Facebook Developers with a unique Facebook id.

Create variables for Facebook authentication:-
  • _isFBLoggedIn variable is used to check the current user is sign-in as Facebook.
  • userProfile is a Map variable. It is used for mapping with Facebook user data response.
  • facebookLogin is the object of the FaceBook class. It is used for Facebook login & logout functionality.
bool _isFBLoggedIn = false;
Map userProfile;
final facebookLogin = FacebookLogin();
Create an outline button for call _facebookLogin() method:-
Widget _facebookSignInButton() {
    return OutlineButton(
      splashColor: ColorConstants.kgreyColor,
      onPressed: () {
        _facebookLogin();
      },
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),
      highlightElevation: 0,
      borderSide: BorderSide(color: ColorConstants.kgreyColor),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image(
                image: AssetImage("assets/images/facebook_logo.png"),
                height: 35.0),
            Padding(
              padding: const EdgeInsets.only(left: 10),
              child: Text(
                'Sign in with FB',
                style: GoogleFonts.alata(
                  fontSize: 20,
                  fontWeight: FontWeight.w500,
                  color: ColorConstants.kgreyColor,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
Facebook Button
Facebook button
Facebook sign-in method code:-
_facebookLogin() async {
  final result = await facebookLogin.logIn(['email']);

  switch (result.status) {
    case FacebookLoginStatus.loggedIn:
      final token = result.accessToken.token;
      final graphResponse = await http.get(
 'https://graph.facebook.com/v2.12/me?fields=name,picture,email&access_token=${token}');
      final profile = JSON.jsonDecode(graphResponse.body);
      print(profile);
      setState(() {
        userProfile = profile;
        _isFBLoggedIn = true;
      });
      break;

    case FacebookLoginStatus.cancelledByUser:
      setState(() => _isFBLoggedIn = false);
      break;

    case FacebookLoginStatus.error:
      setState(() => _isFBLoggedIn = false);
      break;
  }
}
Create an outline button for call _facebookLogout() method:-
Widget _facebookSignOutButton() {
    return OutlineButton(
      splashColor: ColorConstants.kgreyColor,
      onPressed: () {
        _facebookLogout();
      },
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),
      highlightElevation: 0,
      borderSide: BorderSide(color: ColorConstants.kgreyColor),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(left: 10),
              child: Text(
                'Sign out',
                style: GoogleFonts.alata(
                  fontSize: 20,
                  fontWeight: FontWeight.w500,
                  color: ColorConstants.kgreyColor,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
Facebook sign-out method code:-
_facebookLogout() {
    facebookLogin.logOut();
    setState(() {
      _isFBLoggedIn = false;
    });
  }
How to display Facebook current logged in user data? 
  • We can get a current sign-in Facebook user detail get by JSON format.
  • We need to use jsonDecode() function for accessing the current sign-in Facebook user data.
  • Now JSON object decoding output variable assign to Map variable userProfile.
CircleAvatar(
  backgroundColor: ColorConstants.kgreyColor,
  radius: 37,
  child: CircleAvatar(
    backgroundImage: NetworkImage(userProfile["picture"]["data"]["url"],),
    radius: 35,
  ),
),
Text(userProfile["name"],
  style: GoogleFonts.alata(
    fontSize: 25,
    fontWeight: FontWeight.w500,
    color: ColorConstants.kblackColor,
  ),
),

We will get Facebook authentication output like below:

Facebook Authentication

Facebook authentication

The complete source code snippet will look like below:

import 'package:flutter/material.dart';
import 'package:Social_Media_Login/common/colors.dart';
import 'package:flutter/services.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:flutter_facebook_login/flutter_facebook_login.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' as JSON;

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Demo',
      home: MyApp(),
    ),
  );
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _isGoogleLoggedIn = false;

  bool _isFBLoggedIn = false;

  Map userProfile;

  final facebookLogin = FacebookLogin();

  GoogleSignIn _googleSignIn = GoogleSignIn(
    scopes: ['email'],
  );

  _googleLogin() async {
    try {
      await _googleSignIn.signIn();
      setState(() {
        _googleSignIn.currentUser != null ?
        _isGoogleLoggedIn = true : _isGoogleLoggedIn = false;
      });
    } catch (err) {
      print(err);
    }
  }

  _googleLogout() {
    _googleSignIn.signOut();
    setState(() {
      _isGoogleLoggedIn = false;
    });
  }

  _facebookLogin() async {
    final result = await facebookLogin.logIn(['email']);

    switch (result.status) {
      case FacebookLoginStatus.loggedIn:
        final token = result.accessToken.token;
        final graphResponse = await http.get(
        'https://graph.facebook.com/v2.12/me?                           fields=name,picture,email&access_token=${token}');
        final profile = JSON.jsonDecode(graphResponse.body);
        print(profile);
        setState(() {
          userProfile = profile;
          _isFBLoggedIn = true;
        });
        break;

      case FacebookLoginStatus.cancelledByUser:
        setState(() => _isFBLoggedIn = false);
        break;

      case FacebookLoginStatus.error:
        setState(() => _isFBLoggedIn = false);
        break;
    }
  }

  _facebookLogout() {
    facebookLogin.logOut();
    setState(() {
      _isFBLoggedIn = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(
        statusBarColor: ColorConstants.kwhiteColor,
        statusBarIconBrightness: Brightness.dark,
      ),
    );
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          _isGoogleLoggedIn == false && _isFBLoggedIn == false ?
          FlutterLogo(size: 150) : Container(),
          Center(
            child: _isGoogleLoggedIn == false
                ? Column(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                SizedBox(height: 20),
                _isFBLoggedIn == false ?
                _googleSignInButton() : Container(),
                SizedBox(height: 20),
              ],
            )
                : Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('Successfully Login with Google', style: GoogleFonts.alata(
                  fontSize: 20,
                  fontWeight: FontWeight.w500,
                  color: ColorConstants.kgreenColor,
                ),),
                SizedBox(
                  height: 20,
                ),
                CircleAvatar(
                  backgroundColor: ColorConstants.kgreyColor,
                  radius: 37,
                  child: CircleAvatar(
                    backgroundImage: NetworkImage(
                      _googleSignIn.currentUser.photoUrl,),
                    radius: 35,
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                Text(_googleSignIn.currentUser.displayName,
                  style: GoogleFonts.alata(
                    fontSize: 25,
                    fontWeight: FontWeight.w500,
                    color: ColorConstants.kblackColor,
                  ),),
                SizedBox(
                  height: 10,
                ),
                _googleSignOutButton(),
              ],
            ),
          ),

          Center(
            child: _isFBLoggedIn == false
                ? Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                _isGoogleLoggedIn == false ?
                _facebookSignInButton() : Container(),
              ],)
                : Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  'Successfully Login with FaceBook', style: GoogleFonts.alata(
                  fontSize: 20,
                  fontWeight: FontWeight.w500,
                  color: ColorConstants.kgreenColor,
                ),),
                SizedBox(
                  height: 20,
                ),
                CircleAvatar(
                  backgroundColor: ColorConstants.kgreyColor,
                  radius: 37,
                  child: CircleAvatar(
                    backgroundImage: NetworkImage(
                      userProfile["picture"]["data"]["url"],),
                    radius: 35,
                  ),),
                SizedBox(
                  height: 10,
                ),
                Text(userProfile["name"],
                  style: GoogleFonts.alata(
                    fontSize: 25,
                    fontWeight: FontWeight.w500,
                    color: ColorConstants.kblackColor,
                  ),),
                SizedBox(
                  height: 5,
                ),
                SizedBox(
                  height: 10,
                ),
                _facebookSignOutButton(),
              ],),
          ),
        ],
      ),
    );
  }

  Widget _googleSignInButton() {
    return OutlineButton(
      splashColor: ColorConstants.kgreyColor,
      onPressed: () {
        _googleLogin();
      },
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),
      highlightElevation: 0,
      borderSide: BorderSide(color: ColorConstants.kgreyColor),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image(
                image: AssetImage("assets/images/google_logo.png"),
                height: 35.0),
            Padding(
              padding: const EdgeInsets.only(left: 10),
              child: Text(
                'Sign in with Google',
                style: TextStyle(
                  fontSize: 20,
                  color: ColorConstants.kgreyColor,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _googleSignOutButton() {
    return OutlineButton(
      splashColor: ColorConstants.kgreyColor,
      onPressed: () {
        _googleLogout();
      },
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),
      highlightElevation: 0,
      borderSide: BorderSide(color: ColorConstants.kgreyColor),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(left: 10),
              child: Text(
                'Sign out',
                style: TextStyle(
                  fontSize: 20,
                  color: ColorConstants.kgreyColor,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _facebookSignInButton() {
    return OutlineButton(
      splashColor: ColorConstants.kgreyColor,
      onPressed: () {
        _facebookLogin();
      },
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),
      highlightElevation: 0,
      borderSide: BorderSide(color: ColorConstants.kgreyColor),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image(
                image: AssetImage("assets/images/facebook_logo.png"),
                height: 35.0),
            Padding(
              padding: const EdgeInsets.only(left: 10),
              child: Text(
                'Sign in with FB',
                style: TextStyle(
                  fontSize: 20,
                  color: ColorConstants.kgreyColor,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _facebookSignOutButton() {
    return OutlineButton(
      splashColor: ColorConstants.kgreyColor,
      onPressed: () {
        _facebookLogout();
      },
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),
      highlightElevation: 0,
      borderSide: BorderSide(color: ColorConstants.kgreyColor),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(left: 10),
              child: Text(
                'Sign out',
                style: TextStyle(
                  fontSize: 20,
                  color: ColorConstants.kgreyColor,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
Conclusion: 

In this article, We have been through How to implement Social Media Authentication in Flutter.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

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


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields