flutter_prakash_core πβ¨
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
- π¦ Installation & Setup
- ποΈ Architecture & Project Structure
- π§© Core Modules & Capabilities
- β‘ 1. BLoC State Management Engine
- π 2. Reactive Forms Framework (
BaseFormCubit&Field<T>) - π 3. Networking & Error Handling (
Result<T>) - π οΈ 4. DevTools Suite & Runtime Inspectors
- π¨ 5. Design System, Tokens & Theme Builder
- π° 6. AdMob Monetization & Cross-Promotion Engine
- π₯ 7. Firebase & Observability Suite
- πͺ 8. UI Components & Overlays (
Toast,LoadingOverlay,FilePreview) - π§ͺ 9. Mock Data Generator (
Fake) - πͺ 10. Extensions & Helpers
- π± Example Application
- π License & Authors
π 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, andEnterpriseBlocObserver. - πͺ 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
SharedPreferenceskeys. - π¦ 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.