In modern app development, integrating social media authentication has become a standard practice. It offers a seamless and convenient way for users to sign up and log in to your application, reducing friction and improving user experience. Flutter, with its rich ecosystem and cross-platform capabilities, provides excellent tools for handling social media authentication. This post will guide you through implementing social media authentication flows in Flutter, covering popular providers like Google, Facebook, and Apple.
Why Integrate Social Media Authentication?
- User Convenience: Users can log in with accounts they already have.
- Reduced Friction: Simplifies the sign-up process.
- Increased Conversion: Easier login process leads to more users.
- Enhanced User Experience: Streamlined access to app features.
Setting Up Flutter Project
Before diving into the code, ensure you have a Flutter project set up. If not, create one using the following command:
flutter create social_auth_app
cd social_auth_app
1. Google Sign-In
Step 1: Add Dependencies
First, add the google_sign_in package to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
google_sign_in: ^6.1.6
Run flutter pub get to install the package.
Step 2: Configure Google Sign-In
You’ll need to configure your app in the Google Cloud Console:
- Go to the Google Cloud Console.
- Create a new project or select an existing one.
- Go to “APIs & Services” > “Credentials”.
- Create credentials > OAuth client ID.
- Choose “Android” or “iOS” depending on your platform and follow the instructions to get your client ID.
Step 3: Implement Google Sign-In in Flutter
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
class GoogleSignInProvider {
final GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: [
'email',
'profile',
],
);
Future signIn() async {
try {
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
return googleUser;
} catch (error) {
print(error);
return null;
}
}
Future signOut() async {
await _googleSignIn.signOut();
}
}
class GoogleSignInButton extends StatefulWidget {
@override
_GoogleSignInButtonState createState() => _GoogleSignInButtonState();
}
class _GoogleSignInButtonState extends State<GoogleSignInButton> {
bool _isSigningIn = false;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 16.0),
child: _isSigningIn
? CircularProgressIndicator()
: OutlinedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.white),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(40),
),
),
),
onPressed: () async {
setState(() {
_isSigningIn = true;
});
GoogleSignInProvider googleSignInProvider = GoogleSignInProvider();
GoogleSignInAccount? user = await googleSignInProvider.signIn();
setState(() {
_isSigningIn = false;
});
if (user != null) {
// Successfully signed in
print('Google sign-in successful: ${user.displayName}');
// You can navigate to the home screen or perform other actions
} else {
// Sign-in failed
print('Google sign-in failed.');
}
},
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image(image: AssetImage("assets/google_logo.png"), height: 35.0),
Padding(
padding: const EdgeInsets.only(left: 10),
child: Text(
'Sign in with Google',
style: TextStyle(
fontSize: 20,
color: Colors.black54,
fontWeight: FontWeight.w600,
),
),
)
],
),
),
),
);
}
}
Explanation:
- We use the
google_sign_inpackage to handle the authentication flow. GoogleSignInProviderencapsulates the sign-in and sign-out logic.- The
signInmethod triggers the Google sign-in flow, and returns aGoogleSignInAccounton success. - The
signOutmethod signs the user out. GoogleSignInButtonis a widget that displays the sign-in button and handles the UI.
2. Facebook Login
Step 1: Add Dependencies
Add the flutter_facebook_auth package to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
flutter_facebook_auth: ^5.2.0
Run flutter pub get to install the package.
Step 2: Configure Facebook Login
You’ll need to configure your app in the Facebook Developer portal:
- Go to the Facebook for Developers.
- Create a new app or select an existing one.
- Go to “Settings” > “Basic” and provide your app details.
- Add the “Facebook Login” product and configure the Android and iOS platforms.
- Get your App ID and App Secret, and configure the OAuth redirect URI.
Step 3: Implement Facebook Login in Flutter
import 'package:flutter/material.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
class FacebookSignInProvider {
Future<Map?> signIn() async {
try {
final LoginResult result = await FacebookAuth.instance.login(permissions: ['email', 'public_profile']);
if (result.status == LoginStatus.success) {
final userData = await FacebookAuth.instance.getUserData(fields: "name,email,picture.width(200)");
return userData;
} else {
print('Facebook sign-in failed: ${result.status}');
return null;
}
} catch (error) {
print(error);
return null;
}
}
Future signOut() async {
await FacebookAuth.instance.logOut();
}
}
class FacebookSignInButton extends StatefulWidget {
@override
_FacebookSignInButtonState createState() => _FacebookSignInButtonState();
}
class _FacebookSignInButtonState extends State<FacebookSignInButton> {
bool _isSigningIn = false;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 16.0),
child: _isSigningIn
? CircularProgressIndicator()
: OutlinedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.white),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(40),
),
),
),
onPressed: () async {
setState(() {
_isSigningIn = true;
});
FacebookSignInProvider facebookSignInProvider = FacebookSignInProvider();
Map? userData = await facebookSignInProvider.signIn();
setState(() {
_isSigningIn = false;
});
if (userData != null) {
// Successfully signed in
print('Facebook sign-in successful: ${userData['name']}');
// You can navigate to the home screen or perform other actions
} else {
// Sign-in failed
print('Facebook sign-in failed.');
}
},
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image(image: AssetImage("assets/facebook_logo.png"), height: 35.0),
Padding(
padding: const EdgeInsets.only(left: 10),
child: Text(
'Sign in with Facebook',
style: TextStyle(
fontSize: 20,
color: Colors.black54,
fontWeight: FontWeight.w600,
),
),
)
],
),
),
),
);
}
}
Explanation:
- We use the
flutter_facebook_authpackage to handle the authentication flow. FacebookSignInProviderencapsulates the sign-in and sign-out logic.- The
signInmethod triggers the Facebook login flow, and returns user data on success. - The
signOutmethod logs the user out. FacebookSignInButtonis a widget that displays the sign-in button and handles the UI.
3. Apple Sign-In (Sign in with Apple)
Step 1: Add Dependencies
Add the sign_in_with_apple package to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
sign_in_with_apple: ^5.0.0
Run flutter pub get to install the package.
Step 2: Configure Apple Sign-In
You’ll need to configure your app in the Apple Developer portal:
- Go to the Apple Developer portal.
- Enable “Sign In with Apple” capability for your app.
- Configure the return URL in your app’s settings.
- Make sure your App ID is configured correctly and “Sign In with Apple” is enabled.
Step 3: Implement Apple Sign-In in Flutter
import 'package:flutter/material.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
class AppleSignInProvider {
Future signIn() async {
try {
final AuthorizationResult result = await SignInWithApple.instance.signIn(
scopes: [
AppleIDAuthorizationScopes.email,
AppleIDAuthorizationScopes.fullName,
],
);
return result;
} catch (error) {
print(error);
return null;
}
}
}
class AppleSignInButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 16.0),
child: SignInWithAppleButton(
onPressed: () async {
AppleSignInProvider appleSignInProvider = AppleSignInProvider();
AuthorizationResult? result = await appleSignInProvider.signIn();
if (result != null && result.status == AuthorizationStatus.authorized) {
// Successfully signed in
print('Apple sign-in successful: ${result.credential?.userIdentifier}');
// You can navigate to the home screen or perform other actions
} else {
// Sign-in failed
print('Apple sign-in failed.');
}
},
),
);
}
}
Explanation:
- We use the
sign_in_with_applepackage to handle the authentication flow. AppleSignInProviderencapsulates the sign-in logic.- The
signInmethod triggers the Apple Sign-In flow and returns anAuthorizationResult. AppleSignInButtonis a widget that displays the sign-in button and handles the UI.
Conclusion
Integrating social media authentication into your Flutter application can significantly enhance the user experience and streamline the login process. By leveraging packages like google_sign_in, flutter_facebook_auth, and sign_in_with_apple, you can quickly add support for popular social media providers. Remember to configure your apps correctly on each platform’s developer portal and handle the authentication results appropriately to provide a seamless sign-in experience for your users.