flutter_prakash_core πŸš€βœ¨

Flutter Dart License: MIT Clean Architecture

flutter_prakash_core is an ultimate, enterprise-grade multi-app core engine and hybrid Flutter package framework. Built on Clean Architecture, SOLID principles, and zero-boilerplate reactive workflows, it serves as a plug-and-play architectural foundation across all production Flutter applications. πŸ—οΈβš‘


πŸ“‘ Table of Contents


🌟 Key Architectural Highlights

  • 🎯 Clean Architecture & SOLID Enforced: Strictly concrete Data Sources and Repositories with zero unnecessary abstractions or domain pollution.
  • ⚑ Complete BLoC State Management: BaseCubit, BaseBloc, BaseUiCubit, BasePagingCubit, and EnterpriseBlocObserver.
  • πŸͺ„ One-Shot UI Side-Effects Stream: Dispatches Toasts, Navigations, and Dialogs cleanly without polluting state trees via FpEffectListener.
  • πŸ“ Declarative Reactive Forms: Type-safe validation chains (Field<T>, Validators, ReactiveTextField, ReactivePinCodeField, ReactiveDropdown, ReactiveCheckbox, ReactiveSwitch, ReactiveFormButton).
  • πŸ›‘οΈ Type-Safe Sealed Result<T>: Full failure/exception encapsulation for seamless asynchronous network and storage handling.
  • πŸŽ›οΈ Built-in DevTools Floating Dock: Live inspection of HTTP traffic, GraphQL calls, SharedPreferences, logs, app storage, and custom overrides.
  • πŸ’° Comprehensive AdMob & Offline Ad Fallbacks: Google AdMob Banner, Adaptive Banner, Native templates, App Open, Interstitial, and Rewarded Ads with offline cross-promotions.
  • 🎭 Universal Theme & Design Tokens: Material 3 Theme Builder (AppThemeBuilder), AppColors, AppSpacing, AppRadii, and dynamic color generators.

πŸ“¦ Installation & Setup

Add flutter_prakash_core to your pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  flutter_prakash_core:
    path: ../flutter_prakash_core # Or pub version

Run pub get:

flutter pub get

Import into your application:

import 'package:flutter_prakash_core/fp_core.dart';

πŸ›οΈ Architecture & Project Structure

flutter_prakash_core provides clean, modular components under lib/src/:

lib/
 └── src/
      β”œβ”€β”€ base/        πŸ›οΈ Base Repository, Base DataSource, Model, Storage
      β”œβ”€β”€ blocs/       ⚑ Base BLoC/Cubit, Paging, Theme, Locale, AppEvent
      β”œβ”€β”€ devtools/    πŸ› οΈ DevTools Dialog, Floating Dock, Network/Storage Inspectors
      β”œβ”€β”€ di/          πŸ’‰ GetIt & Injectable DI Helpers
      β”œβ”€β”€ extensions/  πŸͺ„ Context, String, Int, DateTime, Collection extensions
      β”œβ”€β”€ fake_data/   πŸ§ͺ Comprehensive Mock & Placeholder Generator (`Fake`)
      β”œβ”€β”€ firebase/    πŸ”₯ Crashlytics, Analytics, Cloud Messaging, Distribution
      β”œβ”€β”€ form/        πŸ“ Reactive Form Engine, Fields Suite, Validators, Widgets
      β”œβ”€β”€ loggers/     πŸͺ΅ Ansi Color Loggers (REST, GraphQL, Supabase, Flutter)
      β”œβ”€β”€ network/     🌐 Result<T>, Failure, NetworkException
      β”œβ”€β”€ plugins/     πŸ”Œ Native Method Channels & Platform Interface
      β”œβ”€β”€ routing/     πŸ—ΊοΈ FpRouter & Route Guards
      β”œβ”€β”€ theme/       🎨 AppThemeBuilder, AppColors, AppSpacing, AppRadii
      β”œβ”€β”€ typedefs/    🏷️ Common Functional & Callback Type Aliases
      β”œβ”€β”€ utilities/   🧰 Debouncer, In-App Review, In-App Update, ColorUtils
      └── widgets/     πŸͺŸ Toast, LoadingOverlay, Shimmer, InAppWebView, FilePreview

🧩 Core Modules & Capabilities

⚑ 1. BLoC State Management Engine

flutter_prakash_core eliminates state boilerplate with lifecycle-safe methods and side-effect streams.

πŸ”„ BaseUiCubit & UiState

Encapsulates async operations (initial, loading, success, failure) into a unified UI builder:

// 1. Define Cubit
@injectable
class UserProfileCubit extends BaseUiCubit<UserProfile> {
  UserProfileCubit(this._repo) : super(const UiState.initial());
  final UserRepository _repo;

  Future<void> fetchProfile(String id) {
    return executeResult(
      call: () => _repo.getUser(id),
      onSuccess: (profile) => emitEffect(ShowToastEffect('Loaded ${profile.name}')),
    );
  }
}

// 2. Consume in UI with Pattern Matching
BlocBuilder<UserProfileCubit, UiState<UserProfile>>(
  builder: (context, state) => switch (state) {
    UiInitial() || UiLoading() => const Center(child: CircularProgressIndicator()),
    UiFailure(:final message) => ErrorRetryWidget(message: message),
    UiSuccess(:final data) => ProfileCard(user: data),
  },
);

πŸš€ Single-Shot UI Effects (FpEffectListener)

Dispatches one-time events (toasts, navigation routes, alerts) without polluting the state stream:

FpEffectListener.fromCubit(
  cubit: context.read<LoginCubit>(),
  onEffect: (context, effect) {
    if (effect is NavigateEffect) {
      context.router.pushNamed(effect.route);
    }
  },
  child: const LoginFormView(),
);

πŸ“œ BasePagingCubit & PagingListView

Built-in infinite pagination with automated pull-to-refresh and error handling:

@injectable
class UserPagingCubit extends BasePagingCubit<User> {
  UserPagingCubit(this._repo);
  final UserRepository _repo;

  @override
  Future<Result<List<User>>> fetchPage(int page, int pageSize) {
    return _repo.getUsers(page: page, limit: pageSize);
  }
}

πŸ“ 2. Reactive Forms Framework (BaseFormCubit & Field<T>)

Declarative, type-safe reactive forms with auto-inferred labels, hints, validation, and submission states.

// 1. Define State
class LoginFormState extends FormCubitState {
  final Field<String> email;
  final Field<String> password;

  LoginFormState({
    Field<String>? email,
    Field<String>? password,
    super.status = FormStatus.initial,
  })  : email = email ?? Fields.email(),
        password = password ?? Fields.password(minLength: 6);

  @override
  List<Field<dynamic>> get fields => [email, password];

  LoginFormState copyWith({
    Field<String>? email,
    Field<String>? password,
    FormStatus? status,
  }) {
    return LoginFormState(
      email: email ?? this.email,
      password: password ?? this.password,
      status: status ?? this.status,
    );
  }
}

// 2. Define Cubit
@injectable
class LoginCubit extends BaseFormCubit<LoginFormState, UserProfile> {
  LoginCubit(this._authRepo) : super(LoginFormState());
  final AuthRepository _authRepo;

  void emailChanged(String val) => emit(state.copyWith(email: state.email(val)));
  void passwordChanged(String val) => emit(state.copyWith(password: state.password(val)));

  Future<void> login() async {
    await submitForm(
      call: () => _authRepo.login(state.email.value, state.password.value),
      onSuccess: (user) => emitEffect(ShowToastEffect('Welcome back, ${user.name}!')),
    );
  }
}

Available Reactive Form Components:

  • πŸ”€ ReactiveTextField
  • πŸ”’ ReactivePinCodeField (OTP codes)
  • πŸ”˜ ReactiveCheckbox
  • 🎚️ ReactiveSwitch
  • πŸ“‹ ReactiveDropdown<T>
  • πŸ“‘ ReactiveSegmentedButton<T>
  • 🎚️ ReactiveSlider
  • πŸ“… ReactiveDatePicker & ⏰ ReactiveTimePicker
  • πŸ”˜ ReactiveRadioGroup<T>
  • πŸ”˜ ReactiveFormButton

🌐 3. Networking & Error Handling (Result<T>)

Encapsulate async computations into clean, type-safe sealed Result<T> values:

@lazySingleton
class AuthRepository {
  final AuthRemoteDataSource _remoteSource;
  final AuthLocalDataSource _localSource;

  AuthRepository(this._remoteSource, this._localSource);

  FutureResult<AuthUserModel> login(LoginRequestModel request) {
    return Result.fromAsync(
      call: () async {
        final result = await _remoteSource.login(request);
        await _localSource.saveSession(token: result.token, user: result.user);
        return result.user;
      },
    );
  }
}

// Handling in Cubit / Service:
final result = await authRepo.login(request);
result.when(
  success: (user) => print('Logged in as ${user.name}'),
  error: (failure) => print('Error: ${failure.errorMessage}'),
);

πŸ› οΈ 4. DevTools Suite & Runtime Inspectors

Embed a draggable floating inspection dock into your debug builds with a single widget:

MaterialApp.router(
  builder: (context, child) {
    return DevtoolsFloatingDock(
      enabled: appEnv.isDev,
      // The dock lives above the Navigator, so hand it a key to reach it.
      navigatorKey: _appRouter.navigatorKey,
      child: child ?? const SizedBox.shrink(),
    );
  },
  routerConfig: _appRouter.config(),
);

Included Inspectors:

  • 🌐 Network Inspector: Real-time logging of HTTP headers, queries, payloads, and response times.
  • β™Š GraphQL Inspector: Query/Mutation debugger with execution timing and variables inspector.
  • πŸ’Ύ Preferences Inspector: Live viewer & editor for all SharedPreferences keys.
  • πŸ“¦ Storage Inspector: Visual directory browser for app sandboxes, cache, and documents.
  • πŸͺ΅ Log Inspector: Filterable ANSI terminal logs with search and tag filters.
  • βš™οΈ Custom Options: Dynamic toggles for environment URLs, mock overrides, and feature flags.

🎨 5. Design System, Tokens & Theme Builder

Material 3 Theme generation with out-of-the-box light and dark themes:

MaterialApp.router(
  theme: AppThemeBuilder.buildLightTheme(primaryColor: AppColors.primary),
  darkTheme: AppThemeBuilder.buildDarkTheme(primaryColor: AppColors.primary),
  themeMode: themeMode,
  routerConfig: _appRouter.config(),
);

Design Tokens:

// Colors
AppColors.primary;
AppColors.secondary;
AppColors.success;
AppColors.error;

// Spacing & Radii
AppSpacing.sm; // 8.0
AppSpacing.md; // 16.0
AppSpacing.lg; // 24.0
AppRadii.borderLg; // BorderRadius.circular(16)

πŸ’° 6. AdMob Monetization & Cross-Promotion Engine

Unified monetization engine with Google AdMob & offline cross-promotion fallbacks:

// 1. Initialize AdMob with Custom Offline Ads
await AdMobService.initialize(
  config: AdMobConfig(
    bannerAndroidId: 'ca-app-pub-xxx',
    interstitialAndroidId: 'ca-app-pub-xxx',
    rewardedAndroidId: 'ca-app-pub-xxx',
    isTesting: kDebugMode,
  ),
  autoShowAppOpen: true,
);

// 2. Drop-in Banners
const AdMobBannerWidget();
const AdMobAdaptiveBannerWidget();

// 3. Drop-in Native Ads
const AdMobNativeWidget(templateType: TemplateType.medium);

// 4. Interstitials & Rewarded Video
AdMobService.showInterstitial(onCompleted: () => navigateNext());
AdMobService.showRewarded(onUserEarnedReward: (reward) => giveReward());

πŸ”₯ 7. Firebase & Observability Suite

Unified manager singletons for Firebase services:

// Firebase Analytics
FirebaseAnalyticsManager.logEvent(name: 'purchase_success', parameters: {'amount': 99});

// Firebase Crashlytics
FirebaseCrashlyticsManager.recordError(exception, stackTrace, reason: 'Network failure');

// Cloud Messaging & App Distribution
FirebaseCloudMessagingManager.initialize();
FirebaseAppDistributionManager.checkForUpdate();

πŸͺŸ 8. UI Components & Overlays

🍞 Global Toasts (Toast)

Display notifications anywhere without a direct BuildContext:

// Call anywhere:
Toast.success('Profile updated successfully!');
Toast.error('Failed to sync changes.');
Toast.warning('Check your network connection.');
Toast.info('New message received.');

⏳ Global Loading Overlay (LoadingOverlay)

Block UI during critical background operations:

LoadingOverlay.show(autoHideInSeconds: 10);
await performHeavySync();
LoadingOverlay.hide();

πŸ“„ Media & Web Containers

// In-App Browser
InAppWebViewContainer.show(context, initialUrl: 'https://flutter.cn', title: 'Flutter');

// Interactive Zoomable Image / PDF Viewer
FilePreviewContainer.show(
  context,
  filePath: 'https://example.com/sample.pdf',
  fileType: FileType.pdf,
  sourceType: FileSourceType.network,
  title: 'Contract PDF',
);

πŸ§ͺ 9. Mock Data Generator (Fake)

Generate realistic mock data for unit tests, previews, and UI placeholders:

final name = Fake.fullName;
final email = Fake.email;
final avatar = Fake.avatarUrl();
final image = Fake.imageUrl(width: 800, height: 600);
final price = Fake.price(min: 10, max: 200);
final paragraphs = Fake.paragraphs(3);
final fakeUsers = Fake.list((i) => User(id: Fake.id, name: Fake.fullName), count: 20);

πŸͺ„ 10. Extensions & Helpers

Ergonomic extensions built directly into Dart core classes:

// BuildContext Extensions
context.theme;
context.colorScheme;
context.textTheme;
context.isDarkMode;
context.isLightMode;
context.screenWidth;
context.screenHeight;

// String Extensions
'john doe'.capitalize(); // 'John doe'
'john_doe'.toTitleCase(); // 'John Doe'
'alex@company.com'.obscureEmail(); // 'a***x@company.com'
'John Doe'.toInitials(); // 'JD'
'12345'.toNepaliDigits(); // 'ΰ₯§ΰ₯¨ΰ₯©ΰ₯ͺΰ₯«'

// DateTime Extensions
DateTime.now().toIsoDateString(); // '2026-08-26'
DateTime.now().toReadableDate(); // 'Aug 26, 2026'
DateTime.now().subtract(const Duration(minutes: 5)).toTimeAgo(); // '5 minutes ago'
DateTime.now().isToday; // true

πŸ“± Example Application

A complete enterprise-grade sample application demonstrating all patterns can be found in the example/ directory:

cd example
flutter run -t lib/main_dev.dart

πŸ§ͺ Verification & QA

flutter analyze
flutter test
cd example && flutter analyze

πŸ“„ License & Authors

Crafted with ❀️ by Prakash Bahadur Chand. Licensed under the MIT License.