NANDHOO.

Social Authentication

While email and password are standard, many users prefer the "one-click" convenience of social logins. In this chapter, we'll integrate Google Sign-In with Firebase. This allows users to log into your app using their existing Google accounts.

Why This Topic Matters

Reducing friction is key to getting users to sign up. A "Sign in with Google" button can significantly increase your conversion rate. Firebase Auth handles the complex exchange of tokens between Google and your app, making what used to be a very difficult task quite straightforward.

How To Study This Chapter

Social authentication involves two steps: first, the user signs in with the social provider (Google), and second, you use the credentials from that sign-in to authenticate with Firebase. You'll need an additional plugin called google_sign_in.

Step 1: Configuration

  1. Firebase Console: Go to Authentication > Sign-in method > Add new provider > Google. Enable it.
  2. Android: You'll need to provide your SHA-1 fingerprint in the Firebase project settings. You can get this by running ./gradlew signingReport in your project's android folder.
  3. iOS: You'll need to add a custom URL scheme to your Info.plist (found in the Firebase Console under the Google provider settings).

Step 2: Add the Plugin

flutter pub add google_sign_in

Step 3: Implement Google Sign-In

import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';

Future<UserCredential?> signInWithGoogle() async {
  // 1. Trigger the authentication flow
  final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();

  // 2. Obtain the auth details from the request
  final GoogleSignInAuthentication? googleAuth = await googleUser?.authentication;

  // 3. Create a new credential
  final credential = GoogleAuthProvider.credential(
    accessToken: googleAuth?.accessToken,
    idToken: googleAuth?.idToken,
  );

  // 4. Once signed in, return the UserCredential
  return await FirebaseAuth.instance.signInWithCredential(credential);
}

UI Implementation

You can use a simple button to trigger this flow.

ElevatedButton.icon(
  icon: Icon(Icons.login),
  label: Text('Sign in with Google'),
  onPressed: () async {
    try {
      await signInWithGoogle();
      // AuthWrapper (Chapter 8) will automatically handle the navigation!
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to sign in with Google: $e')),
      );
    }
  },
)

Best Practices

  • Loading State: Always show a loading spinner while the sign-in is in progress.
  • Error Handling: Users might cancel the sign-in flow. Handle the case where googleUser is null gracefully.
  • Platform Specifics: Remember that the configuration for iOS and Android is different. Double-check your SHA-1 and URL schemes!

In our final chapter, we'll look at how to secure our app and prepare it for the world!