9.5 KiB
System Architecture
Project Structure
Core Directory (lib/core/)
Central infrastructure and shared components:
- Dependency Injection: GetIt-based service locator in
locator_service.dart - Routing: GoRouter implementation in
app_router.dartwith deep linking - Theme: Material theme with Mulish font family in
theme/theme_helper.dart - Networking: Dio HTTP client with token interceptor
- WebSockets: Pusher Channels for real-time communication
- State Management: Flutter BLoC/Cubit pattern
Features Directory (lib/features/)
Feature-based modular architecture with 35+ feature modules:
Core Features:
auth/- Authentication (email/password, OAuth)feed/- Content discovery feeddiary/- Food diary trackingchat/- Real-time messagingconsultations/- Consultation managementprofile/- User profiles and settings
Content Creation:
create_recipe/- Recipe creationcreate_diet/- Diet plan creationcreate_plan/- Nutrition plan creationblog_post_create/- Blog post creation
User Management:
settings/- User preferencesuser_details/- User information managementmenu/- App navigation menubottom_navigation_bar/- Main navigation
Consultant Features:
consultant/- Consultant verificationconsultant_rating/- Rating systemfinances_and_consultations_archive/- Financial tracking
Supporting Features:
notifications/- Push notificationsglossary/- Nutrition glossarycalendar/- Calendar integrationsupport/- Customer supportwelcome/- Onboardingupdate_screen/- App update management
Architectural Patterns
Clean Architecture Layers
Each feature follows a layered structure:
feature/
├── models/ # Data models (freezed + json_serializable)
├── services/ # API services (Retrofit)
├── repositories/ # Data repositories
├── presentation/ # UI layer
│ ├── pages/ # Screen widgets
│ ├── widgets/ # Feature-specific widgets
│ └── bloc/ # State management (Cubit)
└── entities/ # Domain entities
Dependency Injection
Registration Structure (lib/core/di/):
app_config_registration.dart- App configurationexternal_registrations.dart- External dependencies (Dio, etc.)service_registrations.dart- API servicesrepository_registrations.dart- Data repositoriescubit_registrations.dart- State management
Service Lifecycle:
- Singleton: Services, Repositories (most common)
- Factory: Cubits that need fresh instances
- Lazy Singleton: WebSocket manager, core services
State Management Pattern
BLoC/Cubit Implementation:
- Global state: Registered in
AppConfig.globalBlocProviders - Feature state: Created per screen/feature
- State classes: Freezed unions for type-safe states
Global Cubits:
NewMessagesCubit- Message notificationsNotificationsCubit- Push notificationsFeedCubit- Feed contentProfileAvatarCubit- User profileChatsCubit- Chat roomsViewsCubit- Content view trackingInternetConnectionCubit- Network status
Data Flow
API Integration
Base Setup:
- Base URL: Configurable via environment (prod/dev)
- HTTP Client: Dio with interceptors
- API Services: Retrofit for type-safe endpoints
- Authentication: Bearer token in headers
Interceptors:
TokenInterceptor- Adds auth token, handles 401 errorsPhoneVerifyErrorInterceptor- Handles phone verification errors
Real-time Communication
WebSocket Architecture:
- Library:
dart_pusher_channels - Manager:
WsManager(singleton) - Connection: Authenticated via backend endpoint
Channels:
- Private Notifications:
App\Events\BroadcastNotificationCreated - Private Messages:
App\Events\ChatMessageUpdated - Direct Chat: Room-specific message updates
- Client Typing: Real-time typing indicators
Socket ID Storage:
- Persisted via SharedPreferences
- Used for authentication and channel subscription
Authentication Flow
Methods:
- Email/Password - Traditional credentials
- OAuth Providers:
- VK ID (Russian social network)
- Yandex ID
- OK (Odnoklassniki)
- Mail.ru
Token Management:
- Storage: SharedPreferences via
TokenStorage - Refresh: Automatic on 401 response
- Logout: Token removal + WebSocket cleanup
Post-Authentication:
- WebSocket initialization
- Profile loading
- Chat room loading
- Notification loading
- Firebase push token registration
Navigation Architecture
GoRouter Setup
Route Structure:
- Shell routes for persistent bottom navigation
- Named routes for easy navigation
- Deep linking support for content (recipe/blog_post/plan/diet)
Route Groups:
AuthRoutes- Login, registration, password resetMainNavigationRoutes- Shell route with bottom navContentRoutes- Content viewing screensSettingsRoutes- User settingsOtherRoutes- Miscellaneous screens
Deep Linking Pattern:
/content/{type}/{identifier}
- /content/recipe/{slug}
- /content/blog_post/{id}
- /content/plan/{slug}
- /content/diet/{slug}
Bottom Navigation
Main Sections:
- My Profile - User profile and content
- Feed - Content discovery
- Diary - Food tracking
- Consultations - Consultation management
- Chat - Messaging
- Notifications - Notification center
- Menu - Settings and more
Implementation:
BottomNavigationBarWidgetwraps content- No transition animations for tab switches
- WebSocket initialization on feed screen
Data Persistence
Storage Solutions
SharedPreferences:
- Authentication token
- Socket ID
- User preferences
Cached Network Images:
- Library:
cached_network_image - Automatic caching of user avatars, content images
Firebase:
- Push notification tokens
- Remote configuration
- Analytics events
Critical Implementation Details
Content View Tracking
Pattern:
ViewsCubithandles visibility detectionVisibilityDetectorwidget tracks on-screen time- Views sent to backend when 50%+ visible for 2+ seconds
- Debounced to prevent excessive API calls
Tracked Content:
- Blog posts
- Recipes
- Diets
- Nutrition plans
Image Handling
Upload Flow:
ImagePickerfor selectionFlutterImageCompressfor compression- MultiPart form data upload via Dio
- Preview via
CachedNetworkImage
Supported Formats:
- User photos (profile, diary)
- Content images (recipes, diets, plans)
- Chat attachments
Search Implementation
Debounced Search:
- Library:
easy_debounce - Delay: 500ms
- Min query length: 3 characters
- Applied to: Feed, Recipes, Diets, Plans, Consultants
Tag-based Filtering:
- Recipe tags for filtering
- Modal bottom sheet UI
- Persistent selection across sessions
Pagination Pattern
Implementation:
- Page-based pagination
- Scroll detection for next page load
- Loading state during fetch
- Meta data tracking (current page, last page)
Example (FeedCubit):
currentPage = 1
lastPage = meta.lastPage
loadNextPage() when currentPage < lastPage
Error Handling
Network Errors
401 Unauthorized:
- Auto logout
- Token removal
- Navigate to auth screen
Connection Errors:
InternetConnectionCubitmonitors status- Retry mechanisms in repositories
- User-friendly error messages
State Error Handling
Pattern:
sealed class State {
const State.loading();
const State.loaded({required data});
const State.error({required String errorMessage});
}
UI Response:
- Loading: Show loaders/skeletons
- Error: Show
DataErrorWidgetwith retry - Empty: Show empty state messages
Performance Optimizations
Lazy Loading
- Lazy singleton services
- On-demand cubit creation
- Deferred widget loading
Image Optimization
- Compression before upload
- Cached network images
- Thumbnail generation
WebSocket Management
- Connection reuse
- Automatic reconnection
- Proper cleanup on logout
List Rendering
- Pagination for large lists
- ListView.builder for efficiency
- Visibility detection for tracking
Platform-Specific Features
Android
- Huawei HMS support for Huawei devices
- Google FCM for push notifications
- ProGuard rules for release builds
- QR code scanning via camera
iOS
- APNs for push notifications
- Deep linking configuration
- App Store compliance
Firebase Integration
- Separate configs for Android/iOS
- Environment-based configuration
- Push notification handling
- Analytics tracking
Security Considerations
Authentication
- Bearer token authentication
- Secure token storage
- Automatic session management
- OAuth 2.0 for social login
Data Protection
- HTTPS only communication
- Token encryption in storage
- Secure WebSocket connections
- Privacy policy compliance
Key Files Reference
Entry Point:
lib/main.dart- App initialization
Core Infrastructure:
lib/core/app_initializer.dart- Startup sequencelib/core/locator_service.dart- DI containerlib/core/app_config.dart- App configurationlib/core/app_router.dart- Routing setup
WebSocket:
lib/core/websockets/ws_manager.dart- Connection managementlib/core/websockets/ws_service.dart- API service
Authentication:
lib/features/auth/sdk/social_auth_facade.dart- Social authlib/core/token_storage.dart- Token persistencelib/core/interceptors/token_interceptor.dart- Auth interceptor
Environment:
lib/core/env_config.dart- Environment variables.env- Environment file (not in repo)