In modern mobile app development, providing users with convenient login options is crucial for enhancing user experience. Social login, which allows users to authenticate using their existing social media accounts, has become increasingly popular. In Flutter, there are several packages available to implement social login functionality easily. This blog post will guide you through using popular packages like flutter_facebook_auth
and google_sign_in
to integrate social login into your Flutter applications.
Why Use Social Login?
- Convenience: Simplifies the login process for users.
- Reduced Friction: Eliminates the need for users to remember new credentials.
- Increased Conversion: Encourages more users to sign up due to ease of use.
- Enhanced Data: Provides valuable user data (with user consent) for personalized experiences.
Overview of Packages
flutter_facebook_auth
: Allows users to log in with their Facebook accounts.google_sign_in
: Enables users to sign in using their Google accounts.
Setting Up Social Login in Flutter
Part 1: Facebook Login Integration using flutter_facebook_auth
Step 1: Add the flutter_facebook_auth
Package
Add the flutter_facebook_auth
package to your pubspec.yaml
file:
dependencies:
flutter_facebook_auth: ^5.0.6
Run flutter pub get
to install the package.
Step 2: Configure Facebook App
- Create a Facebook App:
- Go to the Facebook Developers website.
- Click on “Create App” and choose “Consumer”.
- Enter a name for your app and click “Create App ID”.
- Configure Facebook Login:
- In your app dashboard, find and click “Set up” on the Facebook Login product.
- Choose the platform (Android and iOS).
Step 3: Configure Android
- Enable the Android Platform:
- Go to the Facebook Login settings and select “Android”.
- Enter your package name and the main Activity class name (usually
com.example.your_app.MainActivity
). - Generate a Key Hash:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
- Copy the generated key hash and paste it into the Facebook Developer portal.
- Enable “Use this key hash in production.”
- Enable Single Sign-On.
Step 4: Configure iOS
- Enable the iOS Platform:
- Go to the Facebook Login settings and select “iOS”.
- Enter your Bundle ID.
- Enable Single Sign-On.
- Update
Info.plist
:- Add the following keys to your
Info.plist
file:
- Add the following keys to your
CFBundleURLTypes
CFBundleURLSchemes
fb[YOUR_APP_ID]
FacebookAppID
[YOUR_APP_ID]
FacebookClientToken
[YOUR_CLIENT_TOKEN]
LSApplicationQueriesSchemes
fbapi
fb-messenger-share-api
fbauth2
fbshareextension
Replace [YOUR_APP_ID]
and [YOUR_CLIENT_TOKEN]
with your actual Facebook App ID and Client Token.
Step 5: Implement Facebook Login in Flutter
import 'package:flutter/material.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
class FacebookLoginPage extends StatefulWidget {
@override
_FacebookLoginPageState createState() => _FacebookLoginPageState();
}
class _FacebookLoginPageState extends State {
Map? _userData;
OAuthCredential? _accessToken;
bool _checking = true;
@override
void initState() {
super.initState();
_checkIfIsLogged();
}
_checkIfIsLogged() async {
final accessToken = await FacebookAuth.instance.accessToken;
if (accessToken != null) {
final userData = await FacebookAuth.instance.getUserData();
setState(() {
_userData = userData;
_checking = false;
});
} else {
setState(() {
_checking = false;
});
}
}
_login() async {
final LoginResult result = await FacebookAuth.instance.login();
if (result.status == LoginStatus.success) {
final OAuthCredential credential = result.credential!;
final userData = await FacebookAuth.instance.getUserData();
setState(() {
_userData = userData;
_accessToken = credential;
});
print(_userData);
} else {
print(result.status);
print(result.message);
}
setState(() {
_checking = false;
});
}
_logout() async {
await FacebookAuth.instance.logOut();
setState(() {
_userData = null;
_accessToken = null;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Facebook Login'),
),
body: _checking
? Center(
child: CircularProgressIndicator(),
)
: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (_userData != null)
Column(
children: [
if (_userData?['picture']?['data']?['url'] != null)
Image.network(
_userData?['picture']?['data']?['url'],
height: 100,
width: 100,
),
Text('Name: ${_userData?['name']}'),
Text('Email: ${_userData?['email'] ?? 'N/A'}'),
ElevatedButton(
onPressed: _logout,
child: Text('Logout'),
),
],
)
else
ElevatedButton(
onPressed: _login,
child: Text('Login with Facebook'),
),
],
),
),
);
}
}
Part 2: Google Sign-In Integration using google_sign_in
Step 1: Add the google_sign_in
Package
Add the google_sign_in
package to your pubspec.yaml
file:
dependencies:
google_sign_in: ^6.1.6
Run flutter pub get
to install the package.
Step 2: Configure Google Sign-In
- Create a Google Cloud Project:
- Go to the Google Cloud Console.
- Create a new project.
- Enable Google Sign-In API:
- Navigate to “APIs & Services” > “Library”.
- Search for “Google Sign-In API” and enable it.
- Configure OAuth Consent Screen:
- Go to “APIs & Services” > “OAuth consent screen”.
- Configure the necessary details (App name, User support email, etc.).
- Add Scopes (e.g.,
email
,profile
).
- Create Credentials:
- Go to “APIs & Services” > “Credentials”.
- Create an OAuth 2.0 Client ID for Android and iOS respectively.
Step 3: Configure Android
- Download
google-services.json
:- Register your Android app in the Firebase Console and download the
google-services.json
file. - Place the
google-services.json
file in theandroid/app/
directory.
- Register your Android app in the Firebase Console and download the
- Configure Gradle Files:
- Add the following to your project-level
build.gradle
file:
- Add the following to your project-level
dependencies {
classpath 'com.google.gms:google-services:4.3.10'
}
- Add the following plugin to your app-level
build.gradle
file:
apply plugin: 'com.google.gms.google-services'
Step 4: Configure iOS
- Download
GoogleService-Info.plist
:- Register your iOS app in the Firebase Console and download the
GoogleService-Info.plist
file. - Add the
GoogleService-Info.plist
file to your Xcode project.
- Register your iOS app in the Firebase Console and download the
- Configure URL Scheme:
- In your Xcode project, go to your target settings, select the “Info” tab, and scroll down to “URL Types”.
- Add a new URL Type. In the “Identifier” field, enter a name. In the “URL Schemes” field, enter your reversed client ID.
Step 5: Implement Google Sign-In in Flutter
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
class GoogleSignInPage extends StatefulWidget {
@override
_GoogleSignInPageState createState() => _GoogleSignInPageState();
}
class _GoogleSignInPageState extends State {
GoogleSignInAccount? _currentUser;
@override
void initState() {
super.initState();
_setUpGoogleSignIn();
}
Future _setUpGoogleSignIn() async {
GoogleSignIn().signInSilently().then((account) {
setState(() {
_currentUser = account;
});
});
}
Future _handleSignIn() async {
try {
final account = await GoogleSignIn().signIn();
setState(() {
_currentUser = account;
});
} catch (error) {
print(error);
}
}
Future _handleSignOut() async {
await GoogleSignIn().signOut();
setState(() {
_currentUser = null;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Google Sign-In'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (_currentUser != null)
Column(
children: [
ListTile(
leading: GoogleUserCircleAvatar(
identity: _currentUser!,
),
title: Text(_currentUser?.displayName ?? ''),
subtitle: Text(_currentUser?.email ?? ''),
),
ElevatedButton(
onPressed: _handleSignOut,
child: Text('Sign Out'),
),
],
)
else
ElevatedButton(
onPressed: _handleSignIn,
child: Text('Sign in with Google'),
),
],
),
),
);
}
}
Conclusion
Social login offers a streamlined and user-friendly authentication experience. By leveraging packages like flutter_facebook_auth
and google_sign_in
, Flutter developers can easily integrate social login functionality into their applications. Implementing these features not only simplifies the user registration and login processes but also enhances user engagement and data collection, driving the success of mobile applications.