Google Sign-In With Supabase In Flutter: A Quick Guide
Google Sign-In with Supabase in Flutter: A Quick Guide
Hey guys! Ever wanted to add that slick “Sign in with Google” feature to your Flutter app using Supabase? Well, you’re in the right place! This guide will walk you through the process step-by-step, making it super easy to implement. We’re talking about a seamless user experience, boosting your app’s credibility, and saving you a ton of coding headaches. So, buckle up, and let’s dive into the world of Flutter and Supabase!
Table of Contents
Setting Up Your Supabase Project
First things first, you need a Supabase project. Think of Supabase as your backend-as-a-service (BaaS) buddy. It handles all the heavy lifting of databases, authentication, and real-time updates, so you can focus on building that awesome user interface in Flutter. Setting up your Supabase project is straightforward. Head over to the Supabase website and create a new project. Choose a name, set a secure database password, and pick a region closest to your users for optimal performance. Once your project is ready, grab the API URL and anon key from your project dashboard. These keys are essential for your Flutter app to communicate with your Supabase backend. Store these keys securely; you’ll need them soon! Remember, your API URL is the address of your Supabase project, and the anon key is like a public key that allows your Flutter app to access your Supabase project. Make sure you keep these credentials safe and never expose them in your client-side code. Once you have these keys, you are ready to move on to the next step: setting up Google Sign-In.
Configuring Google Sign-In
Now, let’s get Google Sign-In working. This involves setting up a Google Cloud project and configuring the necessary OAuth credentials. To start, go to the Google Cloud Console and create a new project. Give it a meaningful name and enable the
Google Sign-In API
. This allows your app to use Google’s authentication services. Next, you’ll need to create OAuth client IDs. An OAuth client ID is a unique identifier for your application when it requests authorization from Google. Create two client IDs: one for Android and one for iOS if you’re targeting both platforms. For Android, you’ll need to provide your app’s package name and the SHA-1 certificate fingerprint. For iOS, you’ll need the bundle ID. Make sure these values match your Flutter app’s configuration. Once you’ve created the OAuth client IDs, download the
google-services.json
file for Android and the
GoogleService-Info.plist
file for iOS. Place these files in the appropriate directories in your Flutter project. These files contain the necessary configuration for your app to communicate with Google’s authentication servers. The
SHA-1 certificate fingerprint
is a unique identifier for your app’s signing certificate, which is used to verify the authenticity of your app. You can generate this fingerprint using the
keytool
command in your Java Development Kit (JDK). Make sure you use the correct keystore file when generating the fingerprint. Now you’re all set with the Google Cloud stuff!
Adding Dependencies to Your Flutter Project
Time to add the necessary dependencies to your Flutter project. Open your
pubspec.yaml
file and add the following packages:
dependencies:
supabase_flutter: ^latest
google_sign_in: ^latest
Run
flutter pub get
to fetch these packages. The
supabase_flutter
package provides the tools you need to interact with your Supabase backend. The
google_sign_in
package handles the Google Sign-In authentication flow. These packages simplify the process of integrating Supabase and Google Sign-In into your Flutter app. Make sure you use the latest versions of these packages to take advantage of the latest features and bug fixes. After adding these dependencies, you may need to restart your IDE or run
flutter clean
to ensure that the changes are properly applied. Once the dependencies are added, you can start implementing the Google Sign-In functionality in your Flutter app.
Initializing Supabase in Flutter
Before you can use Supabase in your Flutter app, you need to initialize it. This involves providing the API URL and anon key that you obtained earlier. In your
main.dart
file, add the following code:
import 'package:flutter/material.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Supabase.initialize(
url: 'YOUR_SUPABASE_URL',
anonKey: 'YOUR_SUPABASE_ANON_KEY',
);
runApp(MyApp());
}
Replace
YOUR_SUPABASE_URL
and
YOUR_SUPABASE_ANON_KEY
with your actual Supabase credentials. The
WidgetsFlutterBinding.ensureInitialized()
call ensures that the Flutter framework is properly initialized before you initialize Supabase. The
Supabase.initialize()
method sets up the connection to your Supabase backend. This initialization step is crucial for your Flutter app to communicate with your Supabase project. Make sure you perform this initialization before any other Supabase-related operations in your app. By initializing Supabase, you’re essentially telling your Flutter app where to find your backend and how to authenticate with it. This is the foundation for all the data and authentication features you’ll be building on top of Supabase. Remember to keep your Supabase credentials secure and never expose them in your client-side code. With Supabase initialized, you’re ready to start implementing the Google Sign-In functionality.
Implementing Google Sign-In
Now comes the fun part: implementing the Google Sign-In functionality. This involves creating a button in your Flutter app that triggers the Google Sign-In flow. Here’s the code:
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
Future<void> _signInWithGoogle() async {
final GoogleSignIn _googleSignIn = GoogleSignIn();
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
if (googleUser == null) {
// User cancelled the sign-in flow.
return;
}
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final accessToken = googleAuth.accessToken;
final idToken = googleAuth.idToken;
if (accessToken == null || idToken == null) {
// Missing required Google authentication tokens.
return;
}
final res = await Supabase.instance.client.auth.signInWithIdToken(
provider: Provider.google,
idToken: idToken,
accessToken: accessToken,
);
final error = res.error;
if (error != null) {
print('Error signing in with Google: ${error.message}');
} else {
// User signed in successfully.
print('User signed in successfully: ${res.user}');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Login')),
body: Center(
child: ElevatedButton(
onPressed: _signInWithGoogle,
child: Text('Sign in with Google'),
),
),
);
}
}
This code creates a
LoginPage
widget with a button that, when pressed, triggers the
_signInWithGoogle
function. This function uses the
google_sign_in
package to initiate the Google Sign-In flow. Once the user successfully signs in, the function retrieves the
access token
and
ID token
from the Google authentication result. These tokens are then passed to the
Supabase.instance.client.auth.signInWithIdToken
method, which authenticates the user with Supabase using the Google credentials. If the authentication is successful, the user is signed in to your Supabase project. If there is an error, an error message is printed to the console. This code provides a basic implementation of Google Sign-In with Supabase in Flutter. You can customize this code to fit your specific needs. For example, you can add error handling, loading indicators, and navigation to the next screen after successful sign-in. The
GoogleSignIn
class provides methods for initiating the sign-in flow, retrieving user information, and signing out. The
GoogleSignInAccount
class represents a Google user account. The
GoogleSignInAuthentication
class contains the authentication tokens obtained from Google. The
Supabase.instance.client.auth.signInWithIdToken
method is used to authenticate the user with Supabase using the Google credentials. The
Provider.google
constant specifies that the authentication provider is Google. This method returns a
AuthResponse
object, which contains the result of the authentication operation.
Handling Sign-Out
Don’t forget about sign-out! Here’s how to implement it:
Future<void> _signOut() async {
await Supabase.instance.client.auth.signOut();
print('User signed out successfully');
}
This code calls the
Supabase.instance.client.auth.signOut
method, which signs the user out of your Supabase project. After signing out, you can update the UI to reflect the user’s sign-out status. For example, you can navigate the user back to the login screen. The
signOut
method clears the user’s session and revokes any access tokens. This ensures that the user is properly signed out and cannot access protected resources. You can add a sign-out button to your app and call this function when the user presses the button. It’s important to provide a clear and easy way for users to sign out of your app. This enhances the user experience and ensures that users have control over their accounts. By implementing sign-out functionality, you’re providing a complete authentication experience for your users. This includes signing in, signing up, and signing out. With all these features in place, your app will be well-equipped to handle user authentication securely and efficiently.
Conclusion
And there you have it! Implementing Google Sign-In with Supabase in Flutter might seem daunting at first, but with these steps, you’ll be rocking it in no time. Remember to handle those API keys with care and customize the code to fit your app’s specific needs. Now go build something awesome! Good luck, and happy coding!