🧩 BLoC Architecture Guide
Guide lengkap untuk implementasi BLoC (Business Logic Component) pattern di MStore Mobile dengan proper scope dan lifecycle management.📌 Prinsip Dasar
Siapa yang Memiliki State?
BLoC bukan sekadar “controller” — dia pemilik state dan event lifecycle.Pertanyaannya bukan “di mana paling mudah”, tapi siapa yang bertanggung jawab mengelola durasi hidup state itu.
⚙️ Hierarki UI dan Scope yang Tepat
Tabel Scope BLoC
🧩 Best Practice BLoC Scope per Domain
Global / Persistent
Scope: Root (di MaterialApp)Contoh:
- AuthBloc
- SettingsBloc
- ThemeBloc
Feature-based
Scope: RouteContoh:
- SalesBloc
- InventoryBloc
- HRBloc
Ephemeral UI
Scope: Page / Widget StateContoh:
- FilterCubit
- TabIndexCubit
- DialogCubit
🧠 Struktur Ideal (Modular + Feature Scoped)
🔧 Implementation Pattern
✅ CORRECT: Route-Level BlocProvider
- ✅ AuthBloc hanya hidup selama route aktif
- ✅ Semua widget di bawah LoginPage bisa
context.watch<AuthBloc>() - ✅ Tidak membanjiri global scope
- ✅ Auto-disposed saat keluar route
❌ ANTIPATTERN: Page-Level BlocProvider
- ❌ Setiap kali route direpush, SalesBloc direcreate
- ❌ Request API ulang
- ❌ State hilang saat navigasi antar tab
- ❌ Tidak bisa share state ke sub-page (
/sales/detail/:id)
🧮 MultiBloc Pattern
Jika satu feature butuh beberapa state domain:- ✅ Semua anak widget bisa akses multi-state
- ✅ Masih terisolasi dalam feature route
- ✅ Lifecycle otomatis dihapus saat keluar route
🧱 Decision Matrix
- Kapan taruh di Route
- Kapan taruh di Page
- Kapan taruh di Component
- State domain / API calls
- Perlu diakses antar sub-page
- Misal: Sales, Inventory, HR
- Lifecycle: Lives as long as route lives
✅ Implementation Checklist
1
Define BLoC Scope
Tentukan apakah state ini:
- Global (auth, theme)
- Feature-level (sales, inventory)
- UI-only (filter, sort)
2
Create BLoC/Cubit
3
Register in DI
4
Provide at Route Level
5
Access in Widgets
📊 Architecture Summary
💡 Key Takeaways
BLoC Domain
Di route-level (feature provider)Contoh:
/sales, /inventoryCubit Ringan
Di page/component levelContoh: Filter, Sort, Tab Index
Root BLoC
Hanya untuk global shared stateContoh: Auth, Theme, Locale
Never in Component
Jangan taruh BLoC di widget kecilAkan recreate setiap build
🔗 Related Documentation
Mobile Architecture
Complete mobile architecture guide
State Management
State management patterns
Dependency Injection
DI setup dengan Injectable
Testing BLoC
Unit testing untuk BLoC
Best Practice: Selalu provide BLoC di route-level untuk proper lifecycle management dan avoid memory leaks.