In Flutter app development, providing users with multiple authentication options is a common practice. Social login simplifies the signup process, allowing users to authenticate with their existing social media accounts, like Facebook, Google, or Apple. Leveraging packages such as flutter_facebook_auth, google_sign_in, and sign_in_with_apple makes it straightforward to implement these social login methods in your Flutter application. This comprehensive guide covers the integration of these packages, complete with code samples.
Why Use Social Login?
- Improved User Experience: Simplifies the registration process by eliminating the need to create new accounts.
- Increased Conversion Rates: Easier signup process can lead to higher engagement and retention.
- Data Acquisition: Gain access to valuable user data with user consent, enabling personalized experiences.
Prerequisites
Before diving into the implementation, ensure you have the following:
- A Flutter development environment set up.
- A Firebase project configured for your Flutter app (if you plan to use Firebase Authentication as the backend).
- Required OAuth client IDs and secrets for each social provider, obtained from their respective developer consoles.
Step 1: Add Dependencies
Add the necessary packages to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
flutter_facebook_auth: ^5.0.6 # Use the latest version
google_sign_in: ^6.1.6 # Use the latest version
sign_in_with_apple: ^5.0.0 # Use the latest version
firebase_auth: ^4.15.3 # Use the latest version (if using Firebase Authentication)
dev_dependencies:
flutter_test:
sdk: flutter
Run flutter pub get to install the packages.
Step 2: Set Up Social Login Providers
Setting up Facebook Login with flutter_facebook_auth
- Create a Facebook App: Go to the Facebook Developers site and create a new app.
- Configure Facebook Login: Add Facebook Login as a product to your app and configure the required settings, including valid OAuth redirect URIs.
- Add Required Keys in
Info.plist(iOS): Add the following to yourios/Runner/Info.plistfile:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb{your_app_id}</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>{your_app_id}</string>
<key>FacebookClientToken</key>
<string>{your_client_token}</string>
<key>FacebookDisplayName</key>
<string>{your_app_name}</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-share-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
Setting up Google Sign-In with google_sign_in
- Create a Google Project: Go to the Google Cloud Console and create a new project.
- Enable the Google Sign-In API: In the APIs & Services section, enable the Google Sign-In API.
- Create OAuth Client ID: Create an OAuth client ID for your app. For Android, you’ll need the SHA-1 certificate fingerprint. For iOS, provide the bundle ID.
- Configure
Info.plist(iOS): Add the following to yourios/Runner/Info.plistfile:
<key>GIDClientID</key>
<string>{your_google_client_id}</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>com.googleusercontent.apps.{your_google_client_id_without_dots}</string>
</array>
</dict>
</array>
Setting up Sign In with Apple with sign_in_with_apple
- Enable Sign In with Apple: In the Apple Developer portal, enable Sign In with Apple for your app ID.
- Configure the Service ID: Create a Service ID and configure it with the return URL for your app.
- Configure Return URL: Add the return URL to your app’s configuration.
- Update Xcode Project: Make sure to enable Sign In with Apple capability in your Xcode project.
Step 3: Implement Social Login Methods in Flutter
Implementing Facebook Login
import 'package:flutter/material.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
class FacebookAuthService {
Future<void> signInWithFacebook() async {
try {
final LoginResult result = await FacebookAuth.instance.login(
permissions: ['email', 'public_profile']);
if (result.status == LoginStatus.success) {
final AccessToken accessToken = result.accessToken!;
final userData = await FacebookAuth.instance.getUserData();
print('Facebook Access Token: ${accessToken.token}');
print('Facebook User Data: $userData');
// TODO: Send token to your backend for verification and user creation
} else {
print('Facebook Login failed: ${result.status}');
print('Facebook Login error: ${result.message}');
}
} catch (e) {
print('Error signing in with Facebook: $e');
}
}
Future<void> signOutFacebook() async {
await FacebookAuth.instance.logOut();
print('Logged out from Facebook');
}
}
class FacebookLoginButton extends StatelessWidget {
final FacebookAuthService _authService = FacebookAuthService();
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () async {
await _authService.signInWithFacebook();
},
child: Text('Login with Facebook'),
);
}
}
Implementing Google Sign-In
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
class GoogleAuthService {
final GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: [
'email',
'profile',
],
);
Future<void> signInWithGoogle() async {
try {
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
if (googleUser != null) {
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final String? accessToken = googleAuth.accessToken;
final String? idToken = googleAuth.idToken;
print('Google Access Token: $accessToken');
print('Google ID Token: $idToken');
print('Google User ID: ${googleUser.id}');
print('Google User Email: ${googleUser.email}');
print('Google User Display Name: ${googleUser.displayName}');
// TODO: Send tokens to your backend for verification and user creation
} else {
print('Google Sign-In cancelled by user.');
}
} catch (e) {
print('Error signing in with Google: $e');
}
}
Future<void> signOutGoogle() async {
await _googleSignIn.signOut();
print('Logged out from Google');
}
}
class GoogleLoginButton extends StatelessWidget {
final GoogleAuthService _authService = GoogleAuthService();
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () async {
await _authService.signInWithGoogle();
},
child: Text('Login with Google'),
);
}
}
Implementing Sign In with Apple
import 'package:flutter/material.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
class AppleAuthService {
Future<void> signInWithApple() async {
try {
final AuthorizationCredentialAppleID result = await SignInWithApple.sharedInstance.signIn();
print('Apple User ID: ${result.userIdentifier}');
print('Apple User Email: ${result.email}');
print('Apple User Name: ${result.givenName} ${result.familyName}');
print('Authorization Code: ${result.authorizationCode}');
print('Identity Token: ${result.identityToken}');
// TODO: Send token to your backend for verification and user creation
} catch (e) {
print('Error signing in with Apple: $e');
}
}
}
class AppleLoginButton extends StatelessWidget {
final AppleAuthService _authService = AppleAuthService();
@override
Widget build(BuildContext context) {
return SignInWithAppleButton(
onPressed: () async {
await _authService.signInWithApple();
},
);
}
}
Step 4: Use Social Login Buttons in Your UI
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Social Login Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FacebookLoginButton(),
SizedBox(height: 20),
GoogleLoginButton(),
SizedBox(height: 20),
AppleLoginButton(),
],
),
),
),
);
}
}
Step 5: Handle Social Login in Backend (Optional)
For enhanced security and user management, handle the authentication process in your backend. This usually involves sending the tokens (e.g., access token, ID token) to your backend for verification against the social provider’s API and creating a user account in your database.
Firebase Authentication with Social Login
If you’re using Firebase for your app’s backend, you can easily integrate social login providers via Firebase Authentication.
Setting up Firebase Authentication
- Enable Social Login Providers: In the Firebase Console, go to Authentication -> Sign-in method and enable Facebook, Google, and/or Apple as sign-in providers.
- Configure OAuth Credentials: Add the OAuth client IDs and secrets for each provider.
Firebase Social Login Example
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
class FirebaseSocialAuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
// Sign in with Facebook using Firebase
Future<UserCredential?> signInWithFacebook() async {
try {
final LoginResult result = await FacebookAuth.instance.login(
permissions: ['email', 'public_profile']);
if (result.status == LoginStatus.success) {
final OAuthCredential credential = FacebookAuthProvider.credential(result.accessToken!.token);
return await _auth.signInWithCredential(credential);
}
return null;
} catch (e) {
print('Error signing in with Facebook via Firebase: $e');
return null;
}
}
// Sign in with Google using Firebase
Future<UserCredential?> signInWithGoogle() async {
try {
final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
final GoogleSignInAuthentication googleAuth = await googleUser!.authentication;
final OAuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
return await _auth.signInWithCredential(credential);
} catch (e) {
print('Error signing in with Google via Firebase: $e');
return null;
}
}
// Sign in with Apple using Firebase
Future<UserCredential?> signInWithApple() async {
try {
final AuthorizationCredentialAppleID result = await SignInWithApple.sharedInstance.signIn();
final OAuthCredential credential = OAuthProvider('apple.com').credential(
idToken: result.identityToken,
accessToken: result.authorizationCode,
);
return await _auth.signInWithCredential(credential);
} catch (e) {
print('Error signing in with Apple via Firebase: $e');
return null;
}
}
Future<void> signOut() async {
await _auth.signOut();
await GoogleSignIn().signOut();
await FacebookAuth.instance.logOut(); // Optionally, logout from Facebook as well
print('User signed out');
}
}
class FirebaseSocialLoginExample extends StatelessWidget {
final FirebaseSocialAuthService _authService = FirebaseSocialAuthService();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Firebase Social Login'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () async {
final userCredential = await _authService.signInWithFacebook();
if (userCredential != null) {
print('Facebook sign-in success: ${userCredential.user!.displayName}');
}
},
child: Text('Sign in with Facebook'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
final userCredential = await _authService.signInWithGoogle();
if (userCredential != null) {
print('Google sign-in success: ${userCredential.user!.displayName}');
}
},
child: Text('Sign in with Google'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
final userCredential = await _authService.signInWithApple();
if (userCredential != null) {
print('Apple sign-in success: ${userCredential.user!.displayName}');
}
},
child: Text('Sign in with Apple'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
await _authService.signOut();
},
child: Text('Sign Out'),
),
],
),
),
);
}
}
void main() {
runApp(MaterialApp(
home: FirebaseSocialLoginExample(),
));
}
Conclusion
Implementing social login in Flutter apps using packages like flutter_facebook_auth, google_sign_in, and sign_in_with_apple enhances user experience and simplifies authentication. By integrating these packages with services like Firebase Authentication, you can efficiently manage user authentication in a secure and scalable way. This comprehensive guide and its accompanying code samples will help you seamlessly add social login to your Flutter applications.