Skip to content

realmeylisdev/flutter_scalable_arch

Repository files navigation

Flutter Scalable Architecture

A production-ready reference architecture demonstrating enterprise-scale patterns for Flutter applications supporting 10M+ users.

Key Features

  • Offline-First: Transactional outbox pattern with automatic sync
  • Real-Time: WebSocket client with reconnection and channel management
  • Modular: Multi-team ready with feature-based architecture
  • Performance-Optimized: Deferred initialization, shader warmup, memory-efficient image loading

Architecture Overview

flutter_scalable_arch/
├── apps/
│   └── main_app/           # Primary application
│
├── packages/
│   ├── core/               # Core infrastructure
│   │   ├── core_foundation/  # Either, Failure, extensions
│   │   ├── core_di/          # GetIt service locator
│   │   ├── core_storage/     # Drift database, secure storage
│   │   ├── core_network/     # Dio client, interceptors
│   │   └── core_realtime/    # WebSocket, push notifications
│   │
│   ├── data/               # Data layer
│   │   ├── data_sync/        # Offline sync engine
│   │   └── data_repository/  # Base repository classes
│   │
│   ├── domain/             # Domain layer
│   │   └── domain_core/      # Entities, use cases
│   │
│   ├── presentation/       # Presentation layer
│   │   └── ui_kit/           # Design system
│   │
│   └── features/           # Feature modules
│       └── feature_auth/     # Authentication

Quick Start

# Clone the repository
git clone <repository-url>
cd flutter_scalable_arch

# Install Melos globally
dart pub global activate melos

# Bootstrap the project
melos bootstrap

# Run code generation
melos run generate

# Run the app
cd apps/main_app
flutter run -t lib/main_dev.dart

Core Patterns

Functional Error Handling

// Using Either for type-safe error handling
FutureResult<User> getUser(String id) async {
  try {
    final user = await api.getUser(id);
    return Right(user);
  } catch (e) {
    return Left(NetworkFailure.fromException(e));
  }
}

// Pattern matching with Dart 3
final result = await getUser('123');
switch (result) {
  case Right(:final value):
    print('User: ${value.name}');
  case Left(:final value):
    print('Error: ${value.message}');
}

Transactional Outbox Pattern

// Offline-first operations with automatic sync
class UserRepositoryImpl extends OfflineFirstRepository<User, String> {
  @override
  FutureResult<User> update(User user) async {
    // 1. Update locally (optimistic)
    await saveToLocal(user);

    // 2. Enqueue for sync
    await syncEngine.enqueue(
      entityType: 'users',
      entityId: user.id,
      operation: SyncOperation.update,
      payload: user.toJson(),
    );

    return Right(user);
  }
}

WebSocket with Reconnection

// Automatic reconnection with exponential backoff
final wsClient = WebSocketClient(
  baseUrl: 'wss://api.example.com',
  reconnectStrategy: ReconnectStrategy.exponentialBackoff,
  maxReconnectAttempts: 10,
);

// Subscribe to channels
wsClient.subscribe('chat:room-123', (message) {
  print('New message: $message');
});

Package Details

core_foundation

Provides foundational types for functional programming:

  • Either<L, R> - Type-safe error handling
  • Failure sealed class hierarchy - Domain errors
  • Result<T> and FutureResult<T> type aliases
  • Common extensions for DateTime, String, Iterable

core_storage

Local storage solutions:

  • Drift Database - SQLite with sync tables (SyncOutbox, ChangeLog)
  • SecureStorageService - Encrypted key-value storage
  • KeyValueStore - SharedPreferences wrapper
  • CacheManager - In-memory caching with policies

core_network

HTTP client with enterprise features:

  • DioApiClient - Returns Result<T> types
  • AuthInterceptor - Token management with refresh
  • RetryInterceptor - Automatic retry with backoff
  • ConnectivityService - Network state monitoring

data_sync

Offline-first synchronization:

  • SyncEngine - Orchestrates push/pull operations
  • ConflictResolver - Multiple resolution strategies
  • EntitySyncHandler - Per-entity sync logic

ui_kit

Design system with atomic design:

  • Theme - Colors, typography, spacing
  • Atoms - Buttons, text fields, avatars
  • Molecules - Cards, dialogs
  • Organisms - Empty states, bottom sheets
  • Feedback - Loading, shimmer, snackbars

feature_auth

Reference feature implementation:

  • Domain - User entity, AuthRepository interface, use cases
  • Data - Models, data sources, repository implementation
  • Presentation - Providers, pages, widgets

Environment Configuration

// Development
flutter run -t lib/main_dev.dart

// Staging
flutter run -t lib/main_staging.dart

// Production
flutter run --release

Melos Commands

melos run get       # Get dependencies for all packages
melos run analyze   # Run static analysis
melos run format    # Format all code
melos run test      # Run all tests
melos run generate  # Run build_runner

Architecture Decisions

Decision Choice Rationale
State Management Riverpod 3.x Type-safe, testable, code generation
Database Drift Type-safe SQL, reactive streams
HTTP Client Dio Interceptors, retry, certificate pinning
Navigation GoRouter Declarative, deep linking, type-safe
DI GetIt + Injectable Proven, tree-shakable
Error Handling Custom Either Dart 3 pattern matching
Sync Pattern Transactional Outbox Reliable offline-first

Dependencies

Core

  • flutter_riverpod: ^3.0.3
  • drift: ^2.23.0
  • dio: ^5.8.0
  • go_router: ^14.8.1
  • get_it: ^8.0.3

Dev

  • melos: ^7.3.0
  • very_good_analysis: ^7.0.0
  • freezed: ^3.0.6
  • riverpod_generator: ^3.0.0

License

MIT License - see LICENSE file for details.

flutter_scalable_arch

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages