flutter_authentication (1.0.2)

Published 2026-02-13 10:12:46 +00:00 by mansi.kansara

Installation

dart pub add flutter_authentication:1.0.2 --hosted-url=

About this package

A provider-agnostic authentication package for Flutter. Includes ready-to-use Firebase implementation, or use Stripe, Supabase, or any custom backend. Clean architecture with reusable business logic.

🔐 Flutter Authentication Package

A provider-agnostic authentication package for Flutter apps. Includes ready-to-use Firebase implementation, or use Stripe, Supabase, or any custom backend - the package adapts to your choice!

Flutter
Dart
GetX
Provider Agnostic


Key Features

  • 100% Provider Agnostic - Works with Firebase, Stripe, Supabase, custom APIs, etc.
  • Firebase Included - Ready-to-use FirebaseAuthService - just import and use!
  • Optional Dependencies - Use Firebase or implement your own provider
  • Reusable Business Logic - BaseAuthController handles all common auth flows
  • Simple Structure - Clean, flat organization
  • Multiple Providers - Email/Password, Google, Apple, Facebook, Anonymous, Custom
  • Account Linking - Link multiple auth methods to one account
  • Mock Implementation - Included for testing (no external dependencies)
  • Built-in Validators - Email and password validation without external dependencies
  • ⚠️ GetX State Management - Currently uses GetX (see limitations below)

⚠️ Important Note on State Management

This package currently uses GetX for state management in BaseAuthController. While the AuthService interface is framework-agnostic, the controller layer has a dependency on GetX.

If you use a different state management solution:

  • Option 1: Still use BaseAuthController and add GetX to your dependencies
  • Option 2: Use the AuthService interface directly and create your own controller with Riverpod, Bloc, Provider, etc.
  • Option 3: Wait for v2.0 which may offer framework-agnostic controllers

We acknowledge this limitation and are considering alternatives for future versions.


🎯 Why This Package?

Other Packages This Package
Forces Firebase Use ANY auth provider
Tight coupling Clean interfaces
Bloated dependencies Zero forced dependencies
Hard to test Mock service included
UI mixed with logic Separated concerns

📦 Installation

Add to your pubspec.yaml:

dependencies:
  flutter_authentication:
    git:
      url: https://gitea.bosctechlab.com/mansi.kansara/bosc_flutter_authentication.git

That's it! Firebase is included, or use your own provider implementation.


🚀 Quick Start

Step 1: Choose Your Auth Service

import 'package:flutter_authentication/flutter_authentication.dart';

// FirebaseAuthService is ready to use - no implementation needed!
// Just make sure Firebase is initialized in your app:
// await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

Option B: Custom Implementation

If you want to use a different provider, implement the AuthService interface:

Custom REST API:

import 'package:flutter_authentication/flutter_authentication.dart';
import 'package:http/http.dart' as http;

class CustomApiAuthService implements AuthService {
  final String baseUrl;
  
  CustomApiAuthService(this.baseUrl);
  
  @override
  Future<void> signInWithEmailPassword(String email, String password) async {
    final response = await http.post(
      Uri.parse('$baseUrl/auth/login'),
      body: {'email': email, 'password': password},
    );
    
    if (response.statusCode != 200) {
      throw 'Login failed';
    }
    // Store token, etc.
  }
  
  // ... implement other methods for your API
}

Supabase:

import 'package:flutter_authentication/flutter_authentication.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

class SupabaseAuthService implements AuthService {
  final SupabaseClient _supabase = Supabase.instance.client;
  
  @override
  Future<void> signInWithEmailPassword(String email, String password) async {
    await _supabase.auth.signInWithPassword(
      email: email,
      password: password,
    );
  }
  
  // ... implement other methods
}

Stripe Identity:

import 'package:flutter_authentication/flutter_authentication.dart';

class StripeAuthService implements AuthService {
  // Implement Stripe Identity integration
  @override
  Future<void> signInWithEmailPassword(String email, String password) async {
    // Your Stripe implementation
  }
  
  // ... implement other methods
}

Step 2: Create Your Controller

import 'package:flutter_authentication/flutter_authentication.dart';
import 'package:get/get.dart';

class AuthController extends BaseAuthController {
  @override
  void onInit() {
    // Use built-in FirebaseAuthService (or your own implementation)
    authService = FirebaseAuthService(); // Ready to use!
    super.onInit();
  }

  // Override navigation methods
  @override
  Future<void> onSignInSuccess() async {
    Get.offAllNamed('/home');
  }

  @override
  Future<void> onSignUpSuccess() async {
    Get.offAllNamed('/welcome');
  }
}

Step 3: Use in Your UI

import 'package:flutter_authentication/flutter_authentication.dart';
import 'package:get/get.dart';

class LoginView extends GetView<AuthController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          TextField(
            onChanged: (value) => controller.email.value = value,
            decoration: InputDecoration(labelText: 'Email'),
          ),
          TextField(
            onChanged: (value) => controller.password.value = value,
            decoration: InputDecoration(labelText: 'Password'),
            obscureText: true,
          ),
          Obx(() => controller.isLoading.value
            ? CircularProgressIndicator()
            : ElevatedButton(
                onPressed: () => controller.signIn(),
                child: Text('Sign In'),
              )),
        ],
      ),
    );
  }
}

📚 Core API

AuthService Interface

Implement this interface for your auth provider:

abstract class AuthService {
  // Email/Password
  Future<void> signInWithEmailPassword(String email, String password);
  Future<void> signUpWithEmailPassword(String email, String password);
  
  // Social (optional - throw UnimplementedError if not supported)
  Future<AuthUserInfo> signInWithGoogle();
  Future<AuthUserInfo> signInWithApple();
  Future<void> signInAnonymously();
  
  // Management
  Future<void> signOut();
  Future<void> resetPassword(String email);
  Future<void> sendEmailVerification();
  Future<bool> isEmailVerified();
  
  // Account Linking (optional)
  Future<void> linkWithGoogle();
  Future<void> linkWithApple();
  Future<void> linkWithEmailPassword(String email, String password);
  Future<void> unlinkProvider(AuthProviderType provider);
  
  // Status
  Stream<bool> get isAuthenticated;
  String? get currentUserEmail;
  String? get currentUserId;
  AuthUserInfo? get currentUser;
  
  void dispose();
}

BaseAuthController Methods

// Authentication
await controller.signIn()
await controller.signUp()
await controller.signOut()
await controller.resetPassword()

// Social Auth
await controller.signInWithGoogle()
await controller.signInWithApple()

// Account Linking
await controller.linkWithGoogle()
await controller.linkWithApple()
await controller.linkWithEmailPassword(email, password)
await controller.unlinkProvider(provider)

// State (Observable)
controller.isLoading.value
controller.errorMessage.value
controller.isAuthenticated.value
controller.email.value
controller.password.value

// User Info
controller.getCurrentUser()
controller.getCurrentUserEmail()
controller.getLinkedProviders()

🏗️ Architecture

┌─────────────────────────────────────────┐
│         Your App (UI Layer)             │
│      (Views + Custom Controller)        │
└──────────────┬──────────────────────────┘
               │
               ▼
┌─────────────────────────────────────────┐
│   BaseAuthController (from package)     │
│   • All business logic                  │
│   • Validation                          │
│   • State management                     │
│   • Error handling                      │
└──────────────┬──────────────────────────┘
               │
               ▼
┌─────────────────────────────────────────┐
│   AuthService Interface (from package)  │
│   • Defines contract                    │
└──────────────┬──────────────────────────┘
               │
               ▼
┌─────────────────────────────────────────┐
│   YOUR Implementation (in your app)     │
│   • FirebaseAuthService                 │
│   • CustomApiAuthService                │
│   • StripeAuthService                   │
│   • SupabaseAuthService                 │
└─────────────────────────────────────────┘

You control the implementation. Package provides the structure.


🎯 Supported Auth Providers

Built-in Examples

The package includes:

  • firebase_auth_service.dart - Ready-to-use Firebase implementation (exported)
  • mock_auth_service.dart - Mock implementation for testing

Community / Your Implementations

You can create implementations for:

  • 🔥 Firebase
  • 💳 Stripe Identity
  • 🗄️ Supabase
  • 🌐 Custom REST APIs
  • 🔐 Auth0
  • 🔑 AWS Cognito
  • 📱 OAuth providers
  • ... anything!

🧪 Testing

Use the included MockAuthService:

import 'package:flutter_authentication/flutter_authentication.dart';

class TestAuthController extends BaseAuthController {
  @override
  void onInit() {
    authService = MockAuthService();
    super.onInit();
  }
}

// In tests
final mockAuth = MockAuthService();
mockAuth.addTestUser('test@example.com', 'password123');

No Firebase SDK, no network calls, instant tests!


📖 Example App

See example/ for a complete working implementation with:

  • Firebase integration
  • Login/Signup/Reset password screens
  • Account linking UI
  • Home screen with user info

Run the example:

cd example
flutter pub get
flutter run

💡 Implementation Guide

Minimal Implementation

Only implement methods you need:

class MinimalAuthService implements AuthService {
  @override
  Future<void> signInWithEmailPassword(String email, String password) async {
    // Your implementation
  }
  
  @override
  Future<void> signOut() async {
    // Your implementation
  }
  
  @override
  Stream<bool> get isAuthenticated => Stream.value(false);
  
  @override
  String? get currentUserEmail => null;
  
  @override
  String? get currentUserId => null;
  
  @override
  AuthUserInfo? get currentUser => null;
  
  // Throw for unsupported features
  @override
  Future<AuthUserInfo> signInWithGoogle() async {
    throw UnimplementedError('Google Sign-In not supported');
  }
  
  // ... implement or throw for other methods
  
  @override
  void dispose() {}
}

Full Implementation

For a complete Firebase implementation, see:

  • lib/firebase_auth_service_reference.dart - Complete reference implementation (commented out, copy to your project)
  • Example app - Working demo with MockAuthService

To use the Firebase reference:

  1. Copy lib/firebase_auth_service_reference.dart to your project
  2. Uncomment the code and Firebase imports
  3. Add Firebase dependencies to your pubspec.yaml
  4. Use it in your AuthController

🎨 Customization

Override Methods

Customize behavior by overriding:

class AuthController extends BaseAuthController {
  @override
  Future<void> onSignInSuccess() async {
    // Custom navigation
  }
  
  @override
  void onSignInError(String error) {
    // Custom error handling
  }
  
  @override
  Future<void> onAccountExistsWithDifferentCredential(
    String email,
    String attemptedProvider,
    String existingProviders,
  ) async {
    // Custom account linking flow
  }
}

📦 Package Structure

lib/
├── auth_service.dart                    # Interface (implement this)
├── auth_validators.dart                 # Validation utilities
├── mock_auth_service.dart               # Mock for testing
├── auth_analytics.dart                  # Analytics interface
├── auth_config.dart                     # Configuration class
├── base_auth_controller.dart            # Reusable GetX controller
├── firebase_auth_service_reference.dart # Firebase reference (not exported)
└── flutter_authentication.dart         # Main export

Simple, flat structure. Easy to navigate.

Note: firebase_auth_service_reference.dart is a reference implementation. It's not exported by the package - copy it to your project if you want to use Firebase.


FAQ

Q: Do I need Firebase?
A: No! Use any auth provider you want.

Q: Can I use Stripe Identity?
A: Yes! Implement AuthService for Stripe.

Q: Can I use my own REST API?
A: Yes! Implement AuthService for your API.

Q: What if I don't need social auth?
A: Just throw UnimplementedError for those methods.

Q: Does this work offline?
A: Depends on your implementation. The package is provider-agnostic.

Q: Can I use multiple providers?
A: Yes! You can even switch providers at runtime.


🤝 Contributing

Contributions welcome! Ideas for contributions:

  • Create reference implementations for other providers (Supabase, Auth0, etc.)
  • Add more examples
  • Improve documentation
  • Report bugs

📄 License

Free to use. No restrictions.


🌟 Support

If this package helped you:

  • Star the repo
  • 📣 Share with others
  • 🐛 Report issues
  • 💡 Suggest improvements

Made with ❤️ for Flutter developers who want flexibility

No forced dependencies. No vendor lock-in. Just clean architecture.

Details
Pub
2026-02-13 10:12:46 +00:00
7
27 KiB
Assets (1)
1.0.2.tar.gz 27 KiB
Versions (4) View all
1.0.3 2026-02-27
1.0.2 2026-02-13
1.0.1 2026-02-12
1.0.0 2026-01-29