Thursday, January 21, 2021

Facebook Login | Google Login | Apple Login

 Flutter Facebook Login | How To Add Facebook Login Into Flutter App - Step By Step Guide


Create a Facebook App in Facebook Developer Console,
FaceBook Developer page https://developers.facebook.com/
Then, create a new app using MyApp => Create App, give an app name and create the app. Check out the below screenshot.

Click the Create App tab

In Mycase is Business Integrations


Enter the Project Name and choose App purpose

Now created APP ID and Secret




Go back to firebase console
https://console.firebase.google.com/?pli=1

Create a Firebase project
In the Firebase console, Click Add Project


As shown in the screencap below, enter a name for your Firebase project and click "Continue".



Next, configure Google Analytics, so you can turn it off, then click "Create project".


After a minute or so, your Firebase project will be ready. Click Continue.


Enable Facebook Sign-In method in Firebase 

Now, you need to enable the Facebook Sign-In method in Firebase. For that, you need to go to the Authentication tab and then Sign-in method tab. From there, enable Facebook Sign-In method. Please check the screenshot.


You need an App ID and App secret. Get that from your Facebook app that you have created in previous steps. You will get the App Id and App secret from Settings => Basic. Note: Click on "Show App Secrete" to copy it.


Now look like Facebook Enabled


Go to the Dashboard tab. Under "Products", you will find Facebook Login=>Settings (click on that).
Then, on the left side, you will find QuickStart under Facebook Login menu. Just click on it.
Select Android.


Platform-specific Facebook configuration and mycase is Platform Android


Click the Next 

Next

On the next two screens, just click "Next". After that, you will get a screen asking for your Android project. Give the package name and default Activity Class name as I have given in the below screenshot. And go to Save => Use This Package => Continue.




Save and Next
On the next screen, you need to add your development and release key hashes. Follow Mac or Windows as per your OS and enter the hash key. Please note that the default Android Keystore password is "android". Copy the hash key and paste there and go to Save => Continue.
Now, click "Next".

Add Your Development and Release Key Hashes
Generating a Release Key Hash
Note -  don't put here debug key, because when our app will be release mode that time should be change it again.
Setp for Release key

openssl-for-windows (download it)
https://code.google.com/archive/p/openssl-for-windows/downloads
Then set path  upto bin, ie
C:\Users\sapan\Downloads\openssl-0.9.8k_X64\bin

Run the command for release key and password default is android

keytool -genkey -v -keystore C:\Users\sapan\.android\key.jks -storetype JKS -keyalg RSA -keysize 2048 -validity 10000 -alias key

Once done the above command , we'll get key.jks

keytool -exportcert -alias YOUR_RELEASE_KEY_ALIAS -keystore YOUR_RELEASE_KEY_PATH | openssl sha1 -binary | openssl base64

More info

Final Command is 
keytool -exportcert -alias key -keystore C:\Users\sapan\.android\key.jks | openssl sha1 -binary | openssl base64

Password default is android

Save and Next

Next, you need to put a lot of stuff in your app.

Go to your project's android/app/src/main/res/values folder. Under the Values folder, create a new file named strings.xml and put the below string (you have in your Facebook project ) in this file.

Code available there https://pub.dev/packages/flutter_facebook_login

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Enter project name</string>
   <string name="facebook_app_id">1835494063281995</string>
<string name="fb_login_protocol_scheme">fb1835494063281995</string>

</resources>




Open the /app/manifest/AndroidManifest.xml file.
  <uses-permission android:name="android.permission.INTERNET"/>


Then, go to android/app/src/main/AndroidManifest.xml and paste the below code (you have in your Facebook project) under first activity and in the application tag. Please check the screenshot for better undestanding.

<meta-data android:name="com.facebook.sdk.ApplicationId" 
        android:value="@string/facebook_app_id"/>
    
    <activity android:name="com.facebook.FacebookActivity"
        android:configChanges=
                "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:label="@string/app_name" />
    <activity
        android:name="com.facebook.CustomTabActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="@string/fb_login_protocol_scheme" />
        </intent-filter>
    </activity>


Click "Next" for all further screens.

Copy the OAuth redirect from the Firebase app and paste in Facebook App. Facebook Login=>Settings >> Valid OAuth Redirect URIs. Please check the below screenshot.
Copy from Firebase App


Add Privacy Policy URL


Privacy Policy Generator

https://www.freeprivacypolicy.com/


Last step is Click the Remove App Type

Enabled it


All done with Firebase Setup. 

Dependency Setup in Firebase project 

Get back to the project and open the pubspec.yaml file in the root of the project. Pubspec.yaml is used to define all the dependencies and assets of the project. Add the below dependencies and save the file.

add dependencies
https://pub.dev/packages/firebase_auth/install
  firebase_auth: ^0.20.0+1

https://pub.dev/packages/flutter_facebook_login/install
  flutter_facebook_login: ^3.0.0

Now, we are done with all dependency setup at project side as well.
 We need to programmatically handle the Facebook login in Google Firebase.

Code Here

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_facebook_login/flutter_facebook_login.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

Future<FacebookLoginResult> facebookLogin() async {
      FacebookLogin facebookLogin = FacebookLogin();

    FacebookLoginResult facebookLoginResult =
        await facebookLogin.logIn(['email', 'public_profile']);

       switch (facebookLoginResult.status) {
      case FacebookLoginStatus.cancelledByUser:
        print("Cancelled");
        break;
      case FacebookLoginStatus.error:
        print("error");
        break;
      case FacebookLoginStatus.loggedIn:
        print("Logged In");
        break;
    }
    return facebookLoginResult;
  }

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Facebook"),
        ),
        body: Center(
          child: Column(
            children: [
              RaisedButton(
                onPressed: () {
                  facebookLogin();
                  print("Hello");
                },
                child: Text('Facebook login'),
              ),
            ],
          ),
        ));
  }
}
Happy Coding :)
...........................................................................................................................................................................................................................
Future<FacebookLoginResult> facebookLogin() async {
      FacebookLogin facebookLogin = FacebookLogin();
    FacebookLoginResult facebookLoginResult =
        await facebookLogin.logIn(['email','public_profile']);
        final accessToken = facebookLoginResult.accessToken.token;

       if(facebookLoginResult.status ==FacebookLoginStatus.loggedIn) {
      final facebookAuthCred =
              FacebookAuthProvider.credential(accessToken);
              
      final user = await FirebaseAuth.instance.signInWithCredential(facebookAuthCred);
      print("User :  + $user");
    }
    return facebookLoginResult;
  }



...........................................................................................................................................................................................................................

...........................................................................................................................................................................................................................

https://firebase.google.com/support/release-notes/android#kotlin+ktx
above site help us to find out of current  stable versions

app/build.gradle
   // implementation 'com.google.firebase:firebase-analytics'
   // implementation 'com.google.firebase:firebase-analytics:17.5.0'
    implementation 'com.google.firebase:firebase-analytics-ktx:18.0.2'



Add this to your package's pubspec.yaml file

https://pub.dev/packages/google_sign_in/install
dependencies:
  google_sign_in: ^4.5.9

https://pub.dev/packages/firebase_core/install
  firebase_core: ^0.7.0

https://pub.dev/packages/firebase_auth/install  
firebase_auth: ^0.20.0+1

https://pub.dev/packages/provider/install  
provider: ^4.3.3

https://pub.dev/packages/flutter_signin_button
  flutter_signin_button: ^1.1.0
...........................................................................................................................................................................................................................
Flutter Signin Button

Add dependencies
https://pub.dev/packages/flutter_signin_button
  flutter_signin_button: ^1.1.0

Code Here
import 'package:flutter/material.dart';
import 'package:flutter_signin_button/button_list.dart';
import 'package:flutter_signin_button/button_view.dart';
import 'package:googlesignin1/screens/home.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SignInButton(Buttons.Google,
            onPressed: ()=>Navigator.of(context).pushReplacement(
              MaterialPageRoute(builder: (context)=>Home()))
            ),
            SignInButton(Buttons.FacebookNew,
            onPressed: ()=>Navigator.of(context).pushReplacement(
              MaterialPageRoute(builder: (context)=>Home()))
            ),
            SignInButton(Buttons.Twitter,
            onPressed: ()=>Navigator.of(context).pushReplacement(
              MaterialPageRoute(builder: (context)=>Home()))
            ),
          ],
        ),
      ),
    );
  }
}

Happy Coding :)
...........................................................................................................................................................................................................................


...........................................................................................................................................................................................................................


...........................................................................................................................................................................................................................



No comments:

Post a Comment