flutter_firebase_auth_repository 1.0.0
flutter_firebase_auth_repository: ^1.0.0 copied to clipboard
A comprehensive Flutter/Dart package that provides a simple, clean repository for handling Firebase Authentication with multiple providers.
π Firebase Auth Repository #
A simple, clean, and comprehensive repository for handling Firebase Authentication in Flutter. It supports multiple providers out-of-the-box and integrates seamlessly with Firestore.
β¨ Features #
- β
Multiple Auth Providers:
- Email & Password (Sign Up / Sign In / Password Reset)
- Google Sign-In
- Facebook Sign-In
- GitHub Sign-In
- Microsoft Sign-In
- β
Real-time Auth State: Exposes a
Stream<User?>
to listen for authentication state changes across your app. - β Firestore Integration: Automatically creates a user document in Firestore on the first sign-up.
- β Platform-Independent Core: Pure Dart logic makes it perfect for any Flutter application.
- β Clean Architecture Ready: Built with a repository pattern that is easy to integrate into state management solutions like BLoC/Cubit, Riverpod, etc.
π Table of Contents #
- π Getting Started
- π» Usage Example
- π API Reference
- π Firestore Security Rules
- π οΈ For Maintainers & Contributors
- π License
- π Maintained By
π Getting Started #
Follow these steps to integrate the Firebase Auth Repository into your Flutter project.
1. Add Dependency #
Add the package to your pubspec.yaml
file:
dependencies:
firebase_auth_repository: ^1.0.0 # Check for the latest version on pub.flutter-io.cn
Then, run flutter pub get
in your terminal.
2. Configure Firebase #
Make sure your Flutter app is connected to a Firebase project.
- Android: Place your
google-services.json
file in theandroid/app/
directory. - Add Gradle Plugins (Android):
- In
android/build.gradle
, add thegoogle-services
classpath:// android/build.gradle buildscript { dependencies { // ... other dependencies classpath 'com.google.gms:google-services:4.4.1' // Use the latest version } }
- In
android/app/build.gradle
, apply the plugin at the bottom of the file:// android/app/build.gradle apply plugin: 'com.google.gms.google-services'
- In
3. Configure Social Providers #
Google Sign-In (Android)
For standard Google Sign-In, the initial Firebase setup is often sufficient. However, you will need to provide your serverClientId
.
π How to get the
serverClientId
- Open your
google-services.json
file.- Find the
client_id
where"client_type": 3
. This is typically the Web client ID.- Copy this value and pass it as the
serverClientId
parameter to thesignInWithGoogle()
method.You can also find this ID in the Google Cloud Console under APIs & Services β Credentials β OAuth 2.0 Client IDs.
Facebook Sign-In (Android)
β οΈ Important: Facebook SDK v15.0.0 and newer require a minimum Android SDK version of 21.
// android/app/build.gradle defaultConfig { // ... minSdkVersion 21 // ... }
-
Add Facebook App Credentials In
android/app/src/main/res/values/strings.xml
, add your Facebook App ID and Client Token:<?xml version="1.0" encoding="utf-8"?> <resources> <string name="facebook_app_id">YOUR_FACEBOOK_APP_ID</string> <string name="facebook_client_token">YOUR_FACEBOOK_CLIENT_TOKEN</string> </resources>
-
Retrieve Your Credentials
- Go to the Facebook for Developers portal.
- Navigate to your app's dashboard.
- App Settings β Basic: Copy the
App ID
. - App Settings β Advanced: Copy the
Client Token
.
4. Enable Providers in Firebase #
In your Firebase Console:
- Navigate to the Authentication section.
- Select the Sign-in method tab.
- Enable all the providers you intend to use (Google, Facebook, etc.).
- For Facebook, you must also add the App ID and App Secret from the Facebook Developer portal.
π» Usage Example #
Here is a basic example of how to initialize the repository and trigger a sign-in flow.
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth_repository/firebase_auth_repository.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(); // Initialize Firebase
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final _authRepository = FirebaseAuthRepository();
MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Auth Example')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Listen to auth state changes
StreamBuilder<User?>(
stream: _authRepository.authStateChanges,
builder: (context, snapshot) {
final user = snapshot.data;
if (user != null) {
return Text('Welcome ${user.email ?? user.displayName}!');
}
return const Text('You are not signed in.');
},
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
try {
// Pass your serverClientId here
const serverClientId = 'YOUR_GOOGLE_SERVER_CLIENT_ID';
await _authRepository.signInWithGoogle(serverClientId: serverClientId);
print('Google sign-in successful!');
} catch (e) {
print('Error signing in with Google: $e');
}
},
child: const Text('Sign in with Google'),
),
ElevatedButton(
onPressed: () async {
try {
await _authRepository.signOut();
print('Signed out successfully!');
} catch (e) {
print('Error signing out: $e');
}
},
child: const Text('Sign Out'),
),
],
),
),
),
);
}
}
π API Reference #
Method | Description |
---|---|
signUp(...) |
Creates a new user with email and password. |
signIn(...) |
Signs in an existing user with email and password. |
signInWithGoogle(...) |
Initiates the Google Sign-In flow. |
signInWithFacebook() |
Initiates the Facebook Sign-In flow. |
signInWithGitHub() |
Initiates the GitHub Sign-In flow. |
signInWithMicrosoft() |
Initiates the Microsoft Sign-In flow. |
signOut() |
Signs out the currently authenticated user. |
resetPassword(...) |
Sends a password reset link to the specified email. |
authStateChanges |
A Stream<User?> that emits the current user or null . |
π Firestore Security Rules #
If you are using the Firestore integration, it is critical to secure your database. Use these rules as a starting point to ensure users can only access their own data.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Only authenticated users can read or write their own user document
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}
π οΈ For Maintainers & Contributors #
This plugin was created with the flutter create --template=plugin
command.
Plugin Structure #
The core Dart logic is located in lib/
, while native Android configurations are managed in the android/
directory.
firebase_auth_repository/
βββ android/
β βββ src/main/AndroidManifest.xml <-- Native Android manifest
βββ lib/
β βββ firebase_auth_repository.dart <-- Core Dart logic
βββ pubspec.yaml
Internal Android Configuration #
The plugin includes its own android/src/main/AndroidManifest.xml
to handle native dependencies like Facebook Login. The Android build tools automatically merge this with your app's main manifest.
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<application>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<meta-data android:name="com.facebook.sdk.ClientToken" android:value="@string/facebook_client_token"/>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="@string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
</application>
</manifest>
This setup relies on the end-user to define @string/facebook_app_id
and @string/facebook_client_token
in their app's strings.xml
file, as explained in the setup guide.
π License #
This project is licensed under the MIT License - see the LICENSE file for details.
π Maintained By #
Made with β€οΈ by Dattaram Kolte