Compare commits

...

60 Commits

Author SHA1 Message Date
misha
12ca205515 Merge remote-tracking branch 'upstream/main' into issue-710 2025-10-16 18:23:04 +03:00
mso7nueh
d8e7464c37 Merge pull request 'build 80 (android), 81 ios' (#734) from mso7nueh/eatvio_app:main into main
Reviewed-on: eatvio/eatvio_app#734
2025-10-16 14:39:17 +00:00
mso7nueh
e0c90bcb21 fix: upd ver to 80 2025-10-16 17:38:23 +03:00
4a96390839 Merge pull request 'doc(readme): README.md update' (#731) from apoloz/eatvio_app:main into main
Reviewed-on: eatvio/eatvio_app#731
2025-10-16 14:36:34 +00:00
a3b25270ac Merge pull request 'fix: merge conflict' (#733) from misha/eatvio_app:main into main
Reviewed-on: eatvio/eatvio_app#733
2025-10-16 14:34:30 +00:00
misha
c72b3e77c6 fix: merge conflict 2025-10-16 17:33:52 +03:00
35f2c0f30a Merge pull request 'feat(social)' (#732) from misha/eatvio_app:main into main
Reviewed-on: eatvio/eatvio_app#732
2025-10-16 14:20:46 +00:00
misha
9e43be5b4e feat(social): added validation for social media registration 2025-10-16 17:18:45 +03:00
4db5dda3ce doc(readme): README.md update 2025-10-16 14:22:23 +03:00
87d5e0bc23 Merge pull request 'docs and rules added' (#730) from apoloz/eatvio_app:main into main
Reviewed-on: eatvio/eatvio_app#730
2025-10-16 08:22:11 +00:00
fa3cf297a3 doc(project): project brief docs added 2025-10-16 11:01:37 +03:00
7b08560257 merge upstream 2025-10-16 07:28:06 +00:00
efd6cca87d Merge pull request 'CI\CD fix' (#729) from misha/eatvio_app:main into main
Reviewed-on: eatvio/eatvio_app#729
2025-10-15 11:50:06 +00:00
misha
05bf90a3cf fixed pipline 2025-10-15 14:47:46 +03:00
misha
feee814bbb pod repod update for ci cd 2025-10-15 14:43:21 +03:00
mso7nueh
d871fdc084 Merge pull request 'build 80' (#726) from misha/eatvio_app:main into main
Reviewed-on: eatvio/eatvio_app#726
2025-10-15 11:26:30 +00:00
misha
e865a11d14 fix: fixed proj version 2025-10-15 14:25:27 +03:00
misha
b242eaa027 fix: fixed base url 2025-10-15 14:22:45 +03:00
misha
e073bd3f97 feat(socail): finished registration and ligin via social media 2025-10-15 14:21:43 +03:00
9281213ea1 Merge pull request 'feat(dairy): navigation to diet from diary' (#723) from misha/eatvio_app:issue-720 into main
Reviewed-on: eatvio/eatvio_app#723
2025-10-15 09:38:06 +00:00
misha
d0ac156307 Merge remote-tracking branch 'upstream/main' into issue-720 2025-10-15 12:35:47 +03:00
mso7nueh
4a9d45a18d Merge pull request 'Issue-691' (#725) from mso7nueh/eatvio_app:main into main
Reviewed-on: eatvio/eatvio_app#725
2025-10-15 09:35:33 +00:00
misha
65fabefdb9 Merge remote-tracking branch 'upstream/main' into issue-720 2025-10-15 12:35:05 +03:00
mso7nueh
f573bb28f8 feat(oauth): Issue-691 2025-10-14 19:25:26 +03:00
mso7nueh
20aca4b9a4 Merge branch 'main' of http://gitea.office.local:3000/mso7nueh/eatvio_app 2025-10-14 12:16:23 +03:00
mso7nueh
5354c3f517 feat(auth): Issue-691 2025-10-14 12:16:20 +03:00
17dbc1d5bf Merge pull request 'feat(social)' (#724) from misha/eatvio_app:main into main
Reviewed-on: eatvio/eatvio_app#724
2025-10-14 09:11:22 +00:00
misha
09a00a41ad added scopes for yandex id 2025-10-14 12:09:26 +03:00
misha
24675714e0 feat(social): added vk client id for ios 2025-10-10 17:02:08 +03:00
misha
21492a1ad9 fix: removed wrong code 2025-10-10 15:18:25 +03:00
misha
239ff675db fix: fixed author card image url handling 2025-10-10 14:58:24 +03:00
misha
fa6c2f9000 Merge remote-tracking branch 'upstream/main' into issue-720 2025-10-10 14:51:41 +03:00
misha
ae0c3a53be Merge remote-tracking branch 'upstream/main' into issue-720 2025-10-10 14:50:37 +03:00
21555bfb10 Merge pull request 'feat(social)' (#721) from misha/eatvio_app:main into main
Reviewed-on: eatvio/eatvio_app#721
2025-10-10 11:46:01 +00:00
misha
f90f1d3284 feat(social): fixed baseUrl for RegisterViaSocialScreen 2025-10-10 14:45:15 +03:00
f9fed539c2 Merge pull request 'feat(tests)' (#718) from misha/eatvio_app:tests into main
Reviewed-on: eatvio/eatvio_app#718
2025-10-10 11:38:03 +00:00
misha
654edc5457 fix: analyzer issues 2025-10-10 14:37:27 +03:00
928a55ae93 Merge pull request 'Issue-691' (#719) from mso7nueh/eatvio_app:main into main
Reviewed-on: eatvio/eatvio_app#719
2025-10-10 11:25:00 +00:00
misha
b2433b87b6 feat(diary): added navigation to detailed diet screen form diary 2025-10-10 14:08:21 +03:00
mso7nueh
183fa012d2 feat(auth): Issue-691 2025-10-09 17:24:36 +03:00
misha
9ac576221a feat(tests): changed base url handling logic, added build type checking for push permission 2025-10-08 17:23:51 +03:00
misha
5013ffe06b Merge remote-tracking branch 'upstream/main' into tests 2025-10-08 14:33:47 +03:00
2993c05dd1 Merge pull request 'feat(internetConnection)' (#714) from misha/eatvio_app:issue-712 into main
Reviewed-on: eatvio/eatvio_app#714
2025-10-08 11:18:29 +00:00
mso7nueh
79de6ee6fa feat(registration): Issue-691 register_via_social_screen.dart 2025-10-07 22:01:44 +03:00
misha
b0d2d86a18 feat(tests): added 2 e2e tests 2025-10-07 18:03:36 +03:00
mso7nueh
03448ebd2d feat(oauth): Issue-691 2025-10-06 17:27:11 +03:00
misha
8816b67ff5 Merge remote-tracking branch 'upstream/main' into issue-710 2025-10-02 10:27:45 +03:00
misha
c88b010cc5 feat(glossary): added pass key for glossary 2025-09-29 09:13:45 +03:00
84cdf34859 merge upstream 2025-09-16 08:55:48 +00:00
a31f721d81 merge upstream 2025-08-21 12:05:04 +00:00
1b93f5c287 Update README.md 2025-08-20 12:55:06 +00:00
7b8a5d14d7 Update README.md 2025-08-20 11:44:28 +00:00
f94fd6f358 Update README.md 2025-08-20 11:41:55 +00:00
a9ad6aedd0 Update README.md 2025-08-20 11:41:21 +00:00
83dd53351b merge upstream 2025-08-20 11:39:16 +00:00
f269ab59cc merge upstream 2025-08-20 09:50:17 +00:00
0d4ec9390d merge upstream 2025-06-30 19:50:42 +00:00
a16e78f804 Merge pull request 'sync main' (#2) from eatvio/eatvio_app:main into main
Reviewed-on: apoloz/eatvio_app#2
2025-06-30 07:23:34 +00:00
c021cdf2c1 Update .gitea/workflows/docker-run-tests.yml 2025-03-13 14:13:19 +00:00
851c300622 Merge pull request 'sync main' (#1) from eatvio/eatvio_app:main into main
Reviewed-on: apoloz/eatvio_app#1
2025-03-13 14:12:52 +00:00
91 changed files with 2839 additions and 610 deletions

View File

@@ -41,7 +41,7 @@ jobs:
# - name: Build apk
# run: flutter build apk
# some test
# some test 2
# - name: Rename and move apk
# run: |

View File

@@ -1,4 +1,4 @@
name: "Build Test Flight"
name: 'Build Test Flight'
on:
pull_request:
branches:
@@ -10,7 +10,7 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Checkout env repository
uses: actions/checkout@v2
with:
@@ -39,8 +39,8 @@ jobs:
run: |
security unlock-keychain -p "$KEYCHAIN_PASSWORD" /Users/gitea_runner_ci/Library/Keychains/login.keychain-db
env:
KEYCHAIN_PASSWORD: ${{ vars.IOS_RUNNER_CI_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ vars.IOS_RUNNER_CI_PASSWORD }}
- name: Setup API key
run: |
echo "${API_APPSTORE_KEY}" | tr -d '\n' | base64 --decode > ios/AuthKey.p8
@@ -66,9 +66,9 @@ jobs:
env:
LANG: en_US.UTF-8
LC_ALL: en_US.UTF-8
MATCH_PASSWORD: ${{ vars.IOS_RUNNER_CI_PASSWORD }}
FASTLANE_PASSWORD: ${{ vars.FASTLANE_PASSWORD }}
MATCH_PASSWORD: ${{ vars.IOS_RUNNER_CI_PASSWORD }}
FASTLANE_PASSWORD: ${{ vars.FASTLANE_PASSWORD }}
MATCH_GIT_URL: http://gitea.office.local:3000/mso7nueh/fastlane
FASTLANE_USER: eatvio2023@icloud.com
FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD: ${{ vars.FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD }}
FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD: ${{ vars.FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD }}
API_APPSTORE_KEY: ${{ vars.API_APPSTORE_KEY }}

View File

@@ -0,0 +1,167 @@
# Memory Bank
I am an expert software engineer with a unique characteristic: my memory resets completely between sessions. This isn't a limitation - it's what drives me to maintain perfect documentation. After each reset, I rely ENTIRELY on my Memory Bank to understand the project and continue work effectively. I MUST read ALL memory bank files at the start of EVERY task - this is not optional. The memory bank files are located in `.kilocode/rules/memory-bank` folder.
When I start a task, I will include `[Memory Bank: Active]` at the beginning of my response if I successfully read the memory bank files, or `[Memory Bank: Missing]` if the folder doesn't exist or is empty. If memory bank is missing, I will warn the user about potential issues and suggest initialization.
## Memory Bank Structure
The Memory Bank consists of core files and optional context files, all in Markdown format.
### Core Files (Required)
1. `brief.md`
This file is created and maintained manually by the developer. Don't edit this file directly but suggest to user to update it if it can be improved.
- Foundation document that shapes all other files
- Created at project start if it doesn't exist
- Defines core requirements and goals
- Source of truth for project scope
2. `product.md`
- Why this project exists
- Problems it solves
- How it should work
- User experience goals
3. `context.md`
This file should be short and factual, not creative or speculative.
- Current work focus
- Recent changes
- Next steps
4. `architecture.md`
- System architecture
- Source Code paths
- Key technical decisions
- Design patterns in use
- Component relationships
- Critical implementation paths
5. `tech.md`
- Technologies used
- Development setup
- Technical constraints
- Dependencies
- Tool usage patterns
### Additional Files
Create additional files/folders within memory-bank/ when they help organize:
- `tasks.md` - Documentation of repetitive tasks and their workflows
- Complex feature documentation
- Integration specifications
- API documentation
- Testing strategies
- Deployment procedures
## Core workflows
### Memory Bank Initialization
The initialization step is CRITICALLY IMPORTANT and must be done with extreme thoroughness as it defines all future effectiveness of the Memory Bank. This is the foundation upon which all future interactions will be built.
When user requests initialization of the memory bank (command `initialize memory bank`), I'll perform an exhaustive analysis of the project, including:
- All source code files and their relationships
- Configuration files and build system setup
- Project structure and organization patterns
- Documentation and comments
- Dependencies and external integrations
- Testing frameworks and patterns
I must be extremely thorough during initialization, spending extra time and effort to build a comprehensive understanding of the project. A high-quality initialization will dramatically improve all future interactions, while a rushed or incomplete initialization will permanently limit my effectiveness.
After initialization, I will ask the user to read through the memory bank files and verify product description, used technologies and other information. I should provide a summary of what I've understood about the project to help the user verify the accuracy of the memory bank files. I should encourage the user to correct any misunderstandings or add missing information, as this will significantly improve future interactions.
### Memory Bank Update
Memory Bank updates occur when:
1. Discovering new project patterns
2. After implementing significant changes
3. When user explicitly requests with the phrase **update memory bank** (MUST review ALL files)
4. When context needs clarification
If I notice significant changes that should be preserved but the user hasn't explicitly requested an update, I should suggest: "Would you like me to update the memory bank to reflect these changes?"
To execute Memory Bank update, I will:
1. Review ALL project files
2. Document current state
3. Document Insights & Patterns
4. If requested with additional context (e.g., "update memory bank using information from @/Makefile"), focus special attention on that source
Note: When triggered by **update memory bank**, I MUST review every memory bank file, even if some don't require updates. Focus particularly on context.md as it tracks current state.
### Add Task
When user completes a repetitive task (like adding support for a new model version) and wants to document it for future reference, they can request: **add task** or **store this as a task**.
This workflow is designed for repetitive tasks that follow similar patterns and require editing the same files. Examples include:
- Adding support for new AI model versions
- Implementing new API endpoints following established patterns
- Adding new features that follow existing architecture
Tasks are stored in the file `tasks.md` in the memory bank folder. The file is optional and can be empty. The file can store many tasks.
To execute Add Task workflow:
1. Create or update `tasks.md` in the memory bank folder
2. Document the task with:
- Task name and description
- Files that need to be modified
- Step-by-step workflow followed
- Important considerations or gotchas
- Example of the completed implementation
3. Include any context that was discovered during task execution but wasn't previously documented
Example task entry:
```markdown
## Add New Model Support
**Last performed:** [date]
**Files to modify:**
- `/providers/gemini.md` - Add model to documentation
- `/src/providers/gemini-config.ts` - Add model configuration
- `/src/constants/models.ts` - Add to model list
- `/tests/providers/gemini.test.ts` - Add test cases
**Steps:**
1. Add model configuration with proper token limits
2. Update documentation with model capabilities
3. Add to constants file for UI display
4. Write tests for new model configuration
**Important notes:**
- Check Google's documentation for exact token limits
- Ensure backward compatibility with existing configurations
- Test with actual API calls before committing
```
### Regular Task Execution
In the beginning of EVERY task I MUST read ALL memory bank files - this is not optional.
The memory bank files are located in `.kilocode/rules/memory-bank` folder. If the folder doesn't exist or is empty, I will warn user about potential issues with the memory bank. I will include `[Memory Bank: Active]` at the beginning of my response if I successfully read the memory bank files, or `[Memory Bank: Missing]` if the folder doesn't exist or is empty. If memory bank is missing, I will warn the user about potential issues and suggest initialization. I should briefly summarize my understanding of the project to confirm alignment with the user's expectations, like:
"[Memory Bank: Active] I understand we're building a React inventory system with barcode scanning. Currently implementing the scanner component that needs to work with the backend API."
When starting a task that matches a documented task in `tasks.md`, I should mention this and follow the documented workflow to ensure no steps are missed.
If the task was repetitive and might be needed again, I should suggest: "Would you like me to add this task to the memory bank for future reference?"
In the end of the task, when it seems to be completed, I will update `context.md` accordingly. If the change seems significant, I will suggest to the user: "Would you like me to update memory bank to reflect these changes?" I will not suggest updates for minor changes.
## Context Window Management
When the context window fills up during an extended session:
1. I should suggest updating the memory bank to preserve the current state
2. Recommend starting a fresh conversation/task
3. In the new conversation, I will automatically load the memory bank files to maintain continuity
## Technical Implementation
Memory Bank is built on Kilo Code's Custom Rules feature, with files stored as standard markdown documents that both the user and I can access.
## Important Notes
REMEMBER: After every memory reset, I begin completely fresh. The Memory Bank is my only link to previous work. It must be maintained with precision and clarity, as my effectiveness depends entirely on its accuracy.
If I detect inconsistencies between memory bank files, I should prioritize brief.md and note any discrepancies to the user.
IMPORTANT: I MUST read ALL memory bank files at the start of EVERY task - this is not optional. The memory bank files are located in `.kilocode/rules/memory-bank` folder.

View File

@@ -0,0 +1,374 @@
# 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.dart` with 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 feed
- `diary/` - Food diary tracking
- `chat/` - Real-time messaging
- `consultations/` - Consultation management
- `profile/` - User profiles and settings
**Content Creation:**
- `create_recipe/` - Recipe creation
- `create_diet/` - Diet plan creation
- `create_plan/` - Nutrition plan creation
- `blog_post_create/` - Blog post creation
**User Management:**
- `settings/` - User preferences
- `user_details/` - User information management
- `menu/` - App navigation menu
- `bottom_navigation_bar/` - Main navigation
**Consultant Features:**
- `consultant/` - Consultant verification
- `consultant_rating/` - Rating system
- `finances_and_consultations_archive/` - Financial tracking
**Supporting Features:**
- `notifications/` - Push notifications
- `glossary/` - Nutrition glossary
- `calendar/` - Calendar integration
- `support/` - Customer support
- `welcome/` - Onboarding
- `update_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 configuration
- `external_registrations.dart` - External dependencies (Dio, etc.)
- `service_registrations.dart` - API services
- `repository_registrations.dart` - Data repositories
- `cubit_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 notifications
- `NotificationsCubit` - Push notifications
- `FeedCubit` - Feed content
- `ProfileAvatarCubit` - User profile
- `ChatsCubit` - Chat rooms
- `ViewsCubit` - Content view tracking
- `InternetConnectionCubit` - 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:**
1. `TokenInterceptor` - Adds auth token, handles 401 errors
2. `PhoneVerifyErrorInterceptor` - Handles phone verification errors
### Real-time Communication
**WebSocket Architecture:**
- Library: `dart_pusher_channels`
- Manager: `WsManager` (singleton)
- Connection: Authenticated via backend endpoint
**Channels:**
1. Private Notifications: `App\Events\BroadcastNotificationCreated`
2. Private Messages: `App\Events\ChatMessageUpdated`
3. Direct Chat: Room-specific message updates
4. Client Typing: Real-time typing indicators
**Socket ID Storage:**
- Persisted via SharedPreferences
- Used for authentication and channel subscription
### Authentication Flow
**Methods:**
1. Email/Password - Traditional credentials
2. 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:**
1. WebSocket initialization
2. Profile loading
3. Chat room loading
4. Notification loading
5. 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 reset
- `MainNavigationRoutes` - Shell route with bottom nav
- `ContentRoutes` - Content viewing screens
- `SettingsRoutes` - User settings
- `OtherRoutes` - 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:**
1. My Profile - User profile and content
2. Feed - Content discovery
3. Diary - Food tracking
4. Consultations - Consultation management
5. Chat - Messaging
6. Notifications - Notification center
7. Menu - Settings and more
**Implementation:**
- `BottomNavigationBarWidget` wraps 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:**
- `ViewsCubit` handles visibility detection
- `VisibilityDetector` widget 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:**
1. `ImagePicker` for selection
2. `FlutterImageCompress` for compression
3. MultiPart form data upload via Dio
4. 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):**
```dart
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:**
- `InternetConnectionCubit` monitors status
- Retry mechanisms in repositories
- User-friendly error messages
### State Error Handling
**Pattern:**
```dart
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 `DataErrorWidget` with 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 sequence
- `lib/core/locator_service.dart` - DI container
- `lib/core/app_config.dart` - App configuration
- `lib/core/app_router.dart` - Routing setup
**WebSocket:**
- `lib/core/websockets/ws_manager.dart` - Connection management
- `lib/core/websockets/ws_service.dart` - API service
**Authentication:**
- `lib/features/auth/sdk/social_auth_facade.dart` - Social auth
- `lib/core/token_storage.dart` - Token persistence
- `lib/core/interceptors/token_interceptor.dart` - Auth interceptor
**Environment:**
- `lib/core/env_config.dart` - Environment variables
- `.env` - Environment file (not in repo)

View File

@@ -0,0 +1,35 @@
# Project Brief
## Project Name
Eatvio - Nutrition & Diet Management Application
## Project Description
A comprehensive mobile application connecting users with nutrition consultants, providing diet planning tools, recipes, food diary tracking, and professional consultation services.
## Core Features
- **Blog Posts**: Educational nutrition content and articles
- **Nutrition Consultation**: Professional consultation services with certified nutritionists
- **Recipes**: User-generated and professional recipes with nutritional information
- **Diets**: Structured diet plans with daily schedules
- **Nutrition Plans**: Long-term nutrition planning and tracking
## Target Audience
- Primary: Russian-speaking users interested in nutrition and healthy eating
- Secondary: Certified nutrition consultants offering professional services
- Market: Russian Federation and Russian-speaking countries
## Platform
- Mobile: iOS and Android (including Huawei devices)
- Language: Russian (ru)
- Current Version: 1.3.0+79
## Business Model
- Paid consultations with nutritionists
- Content marketplace for premium diets and plans
- Subscription-based features for consultants
## Key Success Metrics
- User engagement with food diary
- Consultation bookings and completion rates
- Content creation by consultants
- User retention and progress tracking

View File

@@ -0,0 +1,29 @@
# Current Context
## Project Status
Memory Bank initialized on 2025-10-16. This is a mature Flutter application (v1.3.0+79) currently in production.
## Recent Activity
- Memory Bank initialization completed
- All core files documented
- Architecture and technology stack catalogued
## Current Focus
Ready for development tasks. No active work in progress.
## Known Issues
None documented at initialization.
## Next Steps
Awaiting user direction for:
- Feature development
- Bug fixes
- Architecture improvements
- Performance optimizations
## Important Notes
- Primary language: Russian (ru)
- Target market: Russian users
- Multi-platform: Android (including Huawei) and iOS
- Environment: Uses `.env` file for configuration (not in repository)
- Build system: Requires code generation for models/services

View File

@@ -0,0 +1,73 @@
# Product Overview
## Purpose
Eatvio is a comprehensive nutrition and diet management mobile application that connects users with nutrition consultants, provides diet planning tools, recipes, and personal food diary tracking.
## Core Problems It Solves
### For Regular Users:
1. **Diet Management**: Track daily food intake with detailed nutritional information
2. **Meal Planning**: Access to recipes and structured diet plans
3. **Professional Guidance**: Connect with certified nutrition consultants
4. **Progress Tracking**: Monitor weight, body measurements, and dietary habits
5. **Knowledge Access**: Learn about nutrition through blog posts and glossary
### For Nutrition Consultants:
1. **Client Management**: Communicate with clients via integrated chat
2. **Content Creation**: Create and publish diets, meal plans, recipes, and blog posts
3. **Consultation Services**: Offer paid nutrition consultation services
4. **Income Tracking**: Monitor earnings and client purchases
5. **Professional Presence**: Build profile and gain subscribers
## How It Works
### User Journey:
1. **Authentication**: Sign up via email/password or social networks (VK, Yandex, OK, Mail.ru)
2. **Feed Exploration**: Browse recipes, diets, nutrition plans, blog posts, and consultants
3. **Content Interaction**: Like, bookmark, comment on content
4. **Diary Tracking**: Log daily meals with photos and nutritional data
5. **Consultations**: Book and pay for nutrition consultant services
6. **Real-time Chat**: Communicate with consultants through integrated messaging
7. **Progress Monitoring**: Track weight and body measurements over time
### Consultant Journey:
1. **Become Consultant**: Apply and get verified as nutrition consultant
2. **Content Creation**: Publish professional diets, meal plans, recipes
3. **Client Interaction**: Respond to consultations and provide guidance
4. **Diary Review**: Review client food diaries and provide feedback
5. **Earnings Management**: Track income from consultations and content
## User Experience Goals
### Seamless Navigation:
- Bottom navigation bar for main sections (Profile, Feed, Diary, Consultations, Chat)
- Tab-based feed filtering (Blog posts, Recipes, Diets, Plans, Consultants)
- Deep linking support for direct content access
### Real-time Engagement:
- WebSocket-powered chat for instant messaging
- Push notifications for messages and updates
- Live content updates without app restart
### Professional Interface:
- Clean, modern UI with Mulish font family
- Intuitive search and filtering across all content types
- Visual progress tracking with charts and gauges
### Content Discovery:
- Tag-based recipe filtering
- Search functionality across all content types
- Personalized feed based on user interests
### Offline Capability:
- Token persistence for seamless re-authentication
- Cached content for better performance
- Queue system for offline actions
## Key Differentiators
1. **Integrated Platform**: Combines diet tracking, content, and professional consultations
2. **Social Features**: Follow consultants, like/bookmark content, engage with community
3. **Professional Tools**: Full toolkit for consultants to manage practice
4. **Russian Market Focus**: Optimized for Russian users with local payment and auth integrations
5. **Multi-platform Support**: Works on Android (including Huawei) and iOS

View File

@@ -0,0 +1,152 @@
# Technology Stack
## Core Framework
- **Flutter**: SDK 3.8.0+
- **Dart**: Language version >=3.8.0 <4.0.0
- **Version**: 1.3.0+79 (build 79)
## State Management
- **flutter_bloc**: ^9.1.1 - BLoC pattern implementation
- **equatable**: ^2.0.7 - Value equality for state objects
## Data Management
- **freezed**: ^3.2.0 - Immutable data classes
- **freezed_annotation**: ^3.1.0 - Code generation annotations
- **json_annotation**: ^4.9.0 - JSON serialization
- **json_serializable**: ^6.10.0 - JSON code generation
## Networking
- **dio**: ^5.9.0 - HTTP client
- **retrofit**: ^4.7.1 - Type-safe REST client
- **retrofit_generator**: ^10.0.2 - Retrofit code generation
- **http**: ^1.5.0 - Additional HTTP support
- **http_parser**: ^4.1.2 - HTTP parsing utilities
## Real-time Communication
- **dart_pusher_channels**: ^1.2.3 - WebSocket support via Pusher
- **connectivity_plus**: ^6.1.5 - Network connectivity monitoring
## Navigation & Routing
- **go_router**: ^16.1.0 - Declarative routing
- Deep linking support for content
## UI Components
- **cached_network_image**: ^3.4.1 - Image caching
- **flutter_svg**: ^2.2.0 - SVG rendering
- **google_fonts**: ^6.3.0 - Mulish font family
- **carousel_slider_plus**: ^7.1.1 - Carousel widgets
- **photo_view**: ^0.15.0 - Image viewer
- **dismissible_page**: ^1.0.2 - Swipe to dismiss
- **badges**: ^3.1.2 - Notification badges
- **lottie**: ^3.3.1 - Animation support
- **flutter_portal**: ^1.1.4 - Overlay widgets
- **dotted_border**: ^3.1.0 - Dotted borders
- **flutter_rating_bar**: ^4.0.1 - Rating widgets
## Forms & Input
- **flutter_form_builder**: ^10.2.0 - Form management
- **validators**: ^3.0.0 - Input validation
- **flutter_typeahead**: ^5.2.0 - Autocomplete
- **keyboard_dismisser**: ^3.0.0 - Keyboard management
- **flutter_keyboard_visibility**: ^6.0.0 - Keyboard state
- **mask_text_input_formatter**: ^2.9.0 - Input masking
## Media & Files
- **image_picker**: ^1.2.0 - Image selection
- **flutter_image_compress**: ^2.4.0 - Image compression
- **image**: ^4.5.4 - Image manipulation
- **file_picker**: ^10.3.1 - File selection
- **audioplayers**: ^6.5.0 - Audio playback
- **qr_code_scanner_plus**: ^2.0.10+1 - QR code scanning
## Data Visualization
- **syncfusion_flutter_charts**: ^30.2.5 - Chart widgets
- **syncfusion_flutter_gauges**: ^30.2.5 - Gauge widgets
- **table_calendar**: ^3.2.0 - Calendar widget
## Storage & Persistence
- **shared_preferences**: ^2.5.3 - Local key-value storage
- **path_provider**: ^2.1.5 - File system paths
- **path**: ^1.9.1 - Path manipulation
## Firebase
- **firebase_core**: ^4.0.0 - Firebase initialization
- **firebase_messaging**: ^16.0.0 - Push notifications
## Analytics & Monitoring
- **sentry_flutter**: ^9.6.0 - Error tracking
- **appmetrica_plugin**: ^3.3.0 - Analytics (Russian market)
## Authentication
- **vk_id**: ^1.0.3 - VK social login
- **flutter_login_yandex**: ^0.0.5 - Yandex ID login
- OAuth support for OK and Mail.ru
## Utilities
- **url_launcher**: ^6.3.2 - URL handling
- **easy_debounce**: ^2.0.3 - Debouncing
- **share_plus**: ^11.1.0 - Content sharing
- **flutter_html**: ^3.0.0 - HTML rendering
- **webview_flutter**: ^4.13.0 - WebView
- **intl**: ^0.20.2 - Internationalization
- **collection**: ^1.19.1 - Collection utilities
- **uuid**: ^4.5.1 - UUID generation
- **visibility_detector**: ^0.4.0+2 - Visibility tracking
- **fluttertoast**: ^8.2.12 - Toast messages
- **version**: ^3.0.2 - Version management
- **package_info_plus**: ^8.3.1 - Package info
- **device_info_plus**: ^11.5.0 - Device information
- **permission_handler**: ^12.0.1 - Permissions
## Platform-Specific
### Android
- Huawei HMS Push (6.12.0.300)
- Huawei Analytics (6.12.0.300)
- Google Play Services
- ProGuard for code obfuscation
- NDK version 27.0.12077973
- Compile SDK: Flutter default
- Min SDK: Flutter default
- Target SDK: Flutter default
### iOS
- APNs for push notifications
- Deep linking support
## Development Tools
- **build_runner**: ^2.7.0 - Code generation
- **flutter_native_splash**: ^2.4.6 - Splash screen
- **flutter_lints**: ^6.0.0 - Linting
- **mockito**: ^5.5.0 - Mocking for tests
- **flutter_test**: SDK - Testing framework
- **integration_test**: SDK - Integration testing
- **flutter_dotenv**: ^5.2.1 - Environment variables
## Localization
- **flutter_localizations**: SDK - Localization
- **flutter_intl**: Enabled - Internationalization
- Primary language: Russian (ru)
## Build Configuration
- **Environment**: Production/Development/Test modes
- **Build types**: Debug, Release, Profile
- **Code generation**: Freezed, JSON, Retrofit
- **Obfuscation**: ProGuard (Android release)
- **Resource optimization**: Shrink resources enabled
## API Integration Patterns
- RESTful API via Retrofit
- Bearer token authentication
- Interceptor-based auth injection
- Automatic 401 handling
- Environment-based base URLs
- Type-safe API clients
## Development Workflow
1. Code generation: `flutter pub run build_runner build`
2. Clean generation: `flutter pub run build_runner build --delete-conflicting-outputs`
3. Watch mode: `flutter pub run build_runner watch`
4. Environment setup: `.env` file configuration
5. Firebase setup: Separate configs per platform
6. Testing: Unit tests + Integration tests

450
README.md
View File

@@ -1 +1,449 @@
# eatvio_app
# Eatvio - Nutrition & Diet Management Application
## Project Overview
Eatvio is a comprehensive mobile application connecting users with nutrition consultants, providing diet planning tools, recipes, food diary tracking, and professional consultation services. The application is specifically designed for Russian-speaking users interested in nutrition and healthy eating.
### Core Features
- **Blog Posts**: Educational nutrition content and articles
- **Nutrition Consultation**: Professional consultation services with certified nutritionists
- **Recipes**: User-generated and professional recipes with nutritional information
- **Diets**: Structured diet plans with daily schedules
- **Nutrition Plans**: Long-term nutrition planning and tracking
### Target Audience
- **Primary**: Russian-speaking users interested in nutrition and healthy eating
- **Secondary**: Certified nutrition consultants offering professional services
- **Market**: Russian Federation and Russian-speaking countries
### Business Model
- Paid consultations with nutritionists
- Content marketplace for premium diets and plans
- Subscription-based features for consultants
### Platform Information
- **Mobile**: iOS and Android (including Huawei devices)
- **Language**: Russian (ru)
- **Current Version**: 1.3.0+79 (build 79)
## Prerequisites
### Flutter & Dart Versions
- **Flutter**: SDK 3.8.0+
- **Dart**: Language version >=3.8.0 <4.0.0
### Platform-Specific Requirements
#### Android
- **NDK Version**: 27.0.12077973
- **Huawei HMS Dependencies**:
- Huawei Push (6.12.0.300)
- Huawei Analytics (6.12.0.300)
- **Google Play Services**
- **ProGuard** for code obfuscation
- **Compile SDK**: Flutter default
- **Min SDK**: Flutter default
- **Target SDK**: Flutter default
#### iOS
- **APNs** for push notifications
- **Deep linking** configuration
- **Xcode** version compatible with Flutter requirements
#### General IDE Requirements
- **VS Code** with Flutter/Dart extensions
- **Android Studio** with Flutter plugin
- **Visual Studio Code** recommended for development
## Environment Configuration
### .env Setup Process
1. Copy the environment template:
```bash
cp env.example .env
```
2. Edit the `.env` file with your configuration values
### Required Environment Variables
#### API URLs
- `BASE_URL` - основной URL API (по умолчанию: https://eatvio.ru)
- `DEV_BASE_URL` - URL API для разработки (по умолчанию: https://dev2.eatvio.com)
#### Sentry Configuration
- `SENTRY_DSN` - DSN для Sentry мониторинга
#### Firebase Configuration
- `FIREBASE_PROJECT_ID` - ID проекта Firebase
- `FIREBASE_DATABASE_URL` - URL базы данных Firebase
- `FIREBASE_STORAGE_BUCKET` - bucket для хранения файлов
- `FIREBASE_MESSAGING_SENDER_ID` - ID отправителя сообщений
#### Firebase Android Configuration
- `FIREBASE_ANDROID_API_KEY` - API ключ для Android
- `FIREBASE_ANDROID_APP_ID` - ID приложения для Android
#### Firebase iOS Configuration
- `FIREBASE_IOS_API_KEY` - API ключ для iOS
- `FIREBASE_IOS_APP_ID` - ID приложения для iOS
- `FIREBASE_IOS_BUNDLE_ID` - Bundle ID для iOS
#### App Store URLs
- `APP_STORE_URL` - URL App Store
- `RUSTORE_URL` - URL RuStore
#### Support URLs
- `TELEGRAM_SUPPORT_URL` - URL поддержки в Telegram
- `SUPPORT_EMAIL` - email для поддержки
#### Test Credentials (только для разработки)
- `TEST_EMAIL` - тестовый email
- `TEST_PASSWORD` - тестовый пароль
#### Email Validation API
- `EMAIL_VALIDATION_API_URL` - URL API для валидации email
#### Connection Check URLs
- `GOOGLE_CHECK_URL` - URL для проверки соединения (Google)
- `YANDEX_CHECK_URL` - URL для проверки соединения (Yandex)
#### VK ID Configuration
- `VK_CLIENT_ID` - ID приложения VK (числовой)
- **Примечание**: VK_CLIENT_ID - это числовой "ID приложения" из консоли VK ID, НЕ "Защищённый ключ" или "Сервисный ключ доступа"
#### Yandex ID Configuration
- `YANDEX_CLIENT_ID` - ID приложения Yandex OAuth
- `YANDEX_CLIENT_SECRET` - секретный ключ приложения Yandex OAuth
- `YANDEX_REDIRECT_URI` - URI для перенаправления (должен совпадать с настройками в Yandex OAuth приложении)
## Technology Stack
### Core Framework
- **Flutter**: SDK 3.8.0+
- **Dart**: Language version >=3.8.0 <4.0.0
- **Version**: 1.3.0+79 (build 79)
### State Management
- **flutter_bloc**: ^9.1.1 - BLoC pattern implementation
- **equatable**: ^2.0.7 - Value equality for state objects
### Data Management
- **freezed**: ^3.2.0 - Immutable data classes
- **freezed_annotation**: ^3.1.0 - Code generation annotations
- **json_annotation**: ^4.9.0 - JSON serialization
- **json_serializable**: ^6.10.0 - JSON code generation
### Networking
- **dio**: ^5.9.0 - HTTP client
- **retrofit**: ^4.7.1 - Type-safe REST client
- **retrofit_generator**: ^10.0.2 - Retrofit code generation
- **http**: ^1.5.0 - Additional HTTP support
- **http_parser**: ^4.1.2 - HTTP parsing utilities
### Real-time Communication
- **dart_pusher_channels**: ^1.2.3 - WebSocket support via Pusher
- **connectivity_plus**: ^6.1.5 - Network connectivity monitoring
### Navigation & Routing
- **go_router**: ^16.1.0 - Declarative routing
- Deep linking support for content
### UI Components
- **cached_network_image**: ^3.4.1 - Image caching
- **flutter_svg**: ^2.2.0 - SVG rendering
- **google_fonts**: ^6.3.0 - Mulish font family
- **carousel_slider_plus**: ^7.1.1 - Carousel widgets
- **photo_view**: ^0.15.0 - Image viewer
- **dismissible_page**: ^1.0.2 - Swipe to dismiss
- **badges**: ^3.1.2 - Notification badges
- **lottie**: ^3.3.1 - Animation support
- **flutter_portal**: ^1.1.4 - Overlay widgets
- **dotted_border**: ^3.1.0 - Dotted borders
- **flutter_rating_bar**: ^4.0.1 - Rating widgets
### Forms & Input
- **flutter_form_builder**: ^10.2.0 - Form management
- **validators**: ^3.0.0 - Input validation
- **flutter_typeahead**: ^5.2.0 - Autocomplete
- **keyboard_dismisser**: ^3.0.0 - Keyboard management
- **flutter_keyboard_visibility**: ^6.0.0 - Keyboard state
- **mask_text_input_formatter**: ^2.9.0 - Input masking
### Media & Files
- **image_picker**: ^1.2.0 - Image selection
- **flutter_image_compress**: ^2.4.0 - Image compression
- **image**: ^4.5.4 - Image manipulation
- **file_picker**: ^10.3.1 - File selection
- **audioplayers**: ^6.5.0 - Audio playback
- **qr_code_scanner_plus**: ^2.0.10+1 - QR code scanning
### Data Visualization
- **syncfusion_flutter_charts**: ^30.2.5 - Chart widgets
- **syncfusion_flutter_gauges**: ^30.2.5 - Gauge widgets
- **table_calendar**: ^3.2.0 - Calendar widget
### Storage & Persistence
- **shared_preferences**: ^2.5.3 - Local key-value storage
- **path_provider**: ^2.1.5 - File system paths
- **path**: ^1.9.1 - Path manipulation
### Firebase
- **firebase_core**: ^4.0.0 - Firebase initialization
- **firebase_messaging**: ^16.0.0 - Push notifications
### Analytics & Monitoring
- **sentry_flutter**: ^9.6.0 - Error tracking
- **appmetrica_plugin**: ^3.3.0 - Analytics (Russian market)
### Authentication
- **vk_id**: ^1.0.3 - VK social login
- **flutter_login_yandex**: ^0.0.5 - Yandex ID login
- OAuth support for OK and Mail.ru
### Utilities
- **url_launcher**: ^6.3.2 - URL handling
- **easy_debounce**: ^2.0.3 - Debouncing
- **share_plus**: ^11.1.0 - Content sharing
- **flutter_html**: ^3.0.0 - HTML rendering
- **webview_flutter**: ^4.13.0 - WebView
- **intl**: ^0.20.2 - Internationalization
- **collection**: ^1.19.1 - Collection utilities
- **uuid**: ^4.5.1 - UUID generation
- **visibility_detector**: ^0.4.0+2 - Visibility tracking
- **fluttertoast**: ^8.2.12 - Toast messages
- **version**: ^3.0.2 - Version management
- **package_info_plus**: ^8.3.1 - Package info
- **device_info_plus**: ^11.5.0 - Device information
- **permission_handler**: ^12.0.1 - Permissions
## Development Workflow
### Code Generation
- Run `flutter pub run build_runner build` for code generation
- Run `flutter pub run build_runner build --delete-conflicting-outputs` for clean generation
- Use `flutter pub run build_runner watch` for watch mode
### Environment Setup
- Configure `.env` file with all required variables
- Set up Firebase for both Android and iOS platforms
- Configure social authentication providers (VK, Yandex, etc.)
### Testing
- Unit tests with `flutter_test`
- Integration tests with `integration_test`
- Mocking with `mockito`
## Build Commands
### Development Builds
```bash
# Run on connected device
flutter run
# Run on specific Android device
flutter run -d emulator-5554
# Run on specific iOS simulator
flutter run -d iPhone\ 15
```
### Production Builds
#### Android
```bash
# Build APK (split by ABI)
flutter build apk --release --split-per-abi
# Build App Bundle
flutter build appbundle --release
# Huawei-specific build (with HMS)
flutter build apk --release --flavor production --target-platform android-arm64
```
#### iOS
```bash
# Build IPA for TestFlight
flutter build ipa --export-options-plist=ExportOptions.plist
# Build for specific device architecture
flutter build ipa --export-options-plist=ExportOptions.plist --no-codesign
```
## Optimization Techniques
### Android Build Optimization
1. **ProGuard Rules**:
- Configure rules in [`android/app/proguard-rules.pro`](android/app/proguard-rules.pro:1)
- Essential rules for Flutter:
```
-keep class io.flutter.app.** { *; }
-keep class io.flutter.plugin.** { *; }
-keep class io.flutter.util.** { *; }
-keep class io.flutter.view.** { *; }
```
2. **Resource Shrinking**:
- Enabled in `android/app/build.gradle`:
```gradle
buildTypes {
release {
shrinkResources true
minifyEnabled true
}
}
```
3. **Code Obfuscation**:
- Use `--obfuscate` flag with build commands
- Verify with `flutter build apk --release --obfuscate --split-debug-info=debug-info/`
4. **Image Compression Workflow**:
- Automatic compression via [`flutter_image_compress`](lib/features/create_diet/models/create_diet_model.dart:1)
- Configuration in image upload flows:
```dart
final compressedFile = await FlutterImageCompress.compressWithFile(
file.path,
quality: 85,
minWidth: 1024,
minHeight: 1024,
);
```
## Troubleshooting
### Common Issues
#### Missing .env Variables
- **Symptom**: Application crashes on startup with "Missing environment variable" error
- **Solution**:
1. Verify `.env` file exists in project root
2. Check [`ENV_SETUP.md`](ENV_SETUP.md) for required variables
3. Regenerate configuration with `flutter clean && flutter pub get`
#### Firebase Configuration Errors
- **Android**:
- Missing `google-services.json` in `android/app/`
- Missing `agconnect-services.json` for Huawei devices
- Verify SHA-1 fingerprints match Firebase console
- **iOS**:
- Missing `GoogleService-Info.plist` in `ios/Runner`
- Check bundle identifier matches Firebase project
#### WebSocket Connection Failures
- **Symptoms**: Chat messages not delivering, real-time updates not working
- **Solutions**:
1. Verify Pusher configuration in [`lib/core/websockets/ws_manager.dart`](lib/core/websockets/ws_manager.dart:1)
2. Check network connectivity with `connectivity_plus` package
3. Ensure proper authentication token is sent with WebSocket connection
#### Platform-Specific Build Errors
- **Huawei vs Google Services**:
- For Huawei devices, ensure `agconnect-services.json` is present
- Use `--flavor` flag to specify build variant:
```bash
flutter build apk --release --flavor hms
```
- Check for conflicting dependencies between HMS and GMS
- **iOS Code Signing Issues**:
- Verify `ExportOptions.plist` contains correct provisioning profiles
- Update signing certificates in Xcode
- Clean build folder: `flutter clean && rm -rf ios/Pods ios/Podfile.lock`
## Key Implementation Details
### Content View Tracking
- `ViewsCubit` handles visibility detection
- `VisibilityDetector` widget tracks on-screen time
- Views sent to backend when 50%+ visible for 2+ seconds
- Debounced to prevent excessive API calls
### Image Handling
- `ImagePicker` for selection
- `FlutterImageCompress` for compression
- MultiPart form data upload via Dio
- Preview via `CachedNetworkImage`
### Search Implementation
- Debounced search with 500ms delay
- Min query length: 3 characters
- Applied to: Feed, Recipes, Diets, Plans, Consultants
- Tag-based filtering for recipes
### Pagination Pattern
- Page-based pagination
- Scroll detection for next page load
- Loading state during fetch
- Meta data tracking (current page, last page)
## 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 sequence
- `lib/core/locator_service.dart` - DI container
- `lib/core/app_config.dart` - App configuration
- `lib/core/app_router.dart` - Routing setup
### WebSocket
- `lib/core/websockets/ws_manager.dart` - Connection management
- `lib/core/websockets/ws_service.dart` - API service
### Authentication
- `lib/features/auth/sdk/social_auth_facade.dart` - Social auth
- `lib/core/token_storage.dart` - Token persistence
- `lib/core/interceptors/token_interceptor.dart` - Auth interceptor
### Environment
- `lib/core/env_config.dart` - Environment variables
- `.env` - Environment file (not in repo)
## Key Success Metrics
- User engagement with food diary
- Consultation bookings and completion rates
- Content creation by consultants
- User retention and progress tracking
## Documentation Standards
- **Last Updated**: 2025-10-16
- All paths are relative to `/home/apoloz/dev/eatvio_app`
- Russian market focus maintained throughout documentation
- Version compatibility matrix:
| Component | Version | Notes |
|-----------|---------|-------|
| Flutter | 3.8.0+ | Required |
| Dart | 3.8.0-3.9.9 | Required |
| Android SDK | 34 | Target SDK |
| iOS Deployment | 14.0 | Minimum |
## Ubuntu Development PC Optimization
```bash
-# apt install linux-oem-24.04
-# sudo apt-get install --install-recommends linux-lowlatency-hwe-24.04
```
----
- ubuntu switch to hwe [kernel](https://canonical-kernel-docs.readthedocs-hosted.com/latest/reference/hwe-kernels/#installing-a-hwe-kernel)
----
- ubuntu instal intel iRIS gpu [drivers](https://dgpu-docs.intel.com/driver/client/overview.html#ubuntu-latest)
```

View File

@@ -0,0 +1,37 @@
import 'package:eatvio_app/app_keys.dart';
import 'package:eatvio_app/core/app_initializer.dart';
import 'package:eatvio_app/main.dart' as app;
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import '../common_cases/skip_welcome_screen.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
await AppInitializer.initialize(buildType: AppBuildType.tests);
});
testWidgets('Signs in successfully with valid credentials', (WidgetTester tester) async {
await tester.pumpWidget(const app.MyApp());
await tester.pumpAndSettle(const Duration(seconds: 3));
await skipWelcomeScreen(tester);
final emailFieldFinder = find.byKey(AppKeys.emailTextFieldAuthScreen);
final passwordFieldFinder = find.byKey(AppKeys.passwordTextFieldAuthScreen);
final signInButtonFinder = find.byKey(AppKeys.signInButtonAuthScreen);
expect(emailFieldFinder, findsOneWidget, reason: 'Email text field should be found.');
expect(passwordFieldFinder, findsOneWidget, reason: 'Password text field should be found.');
expect(signInButtonFinder, findsOneWidget, reason: 'Sign In button should be found.');
await tester.enterText(emailFieldFinder, 'reshetnick.mike+user4@gmail.com');
await tester.enterText(passwordFieldFinder, '1234567890');
await tester.pumpAndSettle();
await tester.tap(signInButtonFinder);
await tester.pumpAndSettle(const Duration(seconds: 3));
expect(signInButtonFinder, findsNothing, reason: 'Sign-in button should not be visible after successful login and navigation.');
});
}

View File

@@ -0,0 +1,31 @@
import 'package:eatvio_app/app_keys.dart';
import 'package:eatvio_app/core/app_initializer.dart';
import 'package:eatvio_app/features/dev_tools/presentation/dev_tools_screen.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:eatvio_app/main.dart' as app;
import '../common_cases/skip_welcome_screen.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
await AppInitializer.initialize(buildType: AppBuildType.tests);
});
testWidgets('tapping logo 7 times opens dev tools', (WidgetTester tester) async {
await tester.pumpWidget(const app.MyApp());
await tester.pumpAndSettle(const Duration(seconds: 3));
await skipWelcomeScreen(tester);
final logoButtonFinder = find.byKey(AppKeys.hiddenLogoButtonAuthScreen);
expect(logoButtonFinder, findsOneWidget, reason: 'The logo GestureDetector should be found in auth screen');
for (int i = 0; i < 7; i++) {
await tester.tap(logoButtonFinder);
await tester.pump(const Duration(milliseconds: 50));
}
await tester.pumpAndSettle();
expect(find.byType(DevToolsScreen), findsOneWidget, reason: 'DevToolsScreen should be visible after tapping the logo 7 times.');
});
}

View File

@@ -0,0 +1,8 @@
import 'package:eatvio_app/app_keys.dart';
import 'package:flutter_test/flutter_test.dart';
Future<void> skipWelcomeScreen(WidgetTester tester) async {
final welcomeScreenButtonFinder = find.byKey(AppKeys.welcomeScreenButton);
await tester.tap(welcomeScreenButtonFinder);
await tester.pumpAndSettle();
}

View File

@@ -388,7 +388,7 @@
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Distribution: ITVIO, OOO (VL68C36HYS)";
CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = 74;
CURRENT_PROJECT_VERSION = 80;
DEVELOPMENT_TEAM = VL68C36HYS;
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
@@ -539,7 +539,7 @@
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Distribution: ITVIO, OOO (VL68C36HYS)";
CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = 74;
CURRENT_PROJECT_VERSION = 80;
DEVELOPMENT_TEAM = VL68C36HYS;
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
@@ -578,7 +578,7 @@
CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements;
CODE_SIGN_IDENTITY = "Apple Distribution: ITVIO, OOO (VL68C36HYS)";
CODE_SIGN_STYLE = Manual;
CURRENT_PROJECT_VERSION = 74;
CURRENT_PROJECT_VERSION = 80;
DEVELOPMENT_TEAM = VL68C36HYS;
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (

View File

@@ -21,7 +21,7 @@
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>74</string>
<string>80</string>
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
<key>LSRequiresIPhoneOS</key>

13
lib/app_keys.dart Normal file
View File

@@ -0,0 +1,13 @@
import 'package:flutter/material.dart';
class AppKeys {
// Auth Screen
static const hiddenLogoButtonAuthScreen = ValueKey('hiddenLogoButtonAuthScreen');
static const emailTextFieldAuthScreen = ValueKey('emailTextFieldAuthScreen');
static const passwordTextFieldAuthScreen = ValueKey('passwordTextFieldAuthScreen');
static const signInButtonAuthScreen = ValueKey('signInButtonAuthScreen');
// Welcome Screen
static const welcomeScreenButton = ValueKey('welcomeScreenButton');
}

View File

@@ -1,3 +1,5 @@
import 'package:eatvio_app/core/app_initializer.dart';
import 'package:eatvio_app/core/env_config.dart';
import 'package:eatvio_app/core/internet_connection_cubit/internet_connection_cubit.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/views/cubit/views_cubit.dart';
@@ -13,8 +15,24 @@ import 'package:flutter_localizations/flutter_localizations.dart';
/// Конфигурация приложения
class AppConfig {
AppConfig({required this.buildType}) {
_baseUrl = switch (buildType) {
AppBuildType.prod => EnvConfig.baseUrl,
AppBuildType.tests => EnvConfig.devBaseUrl,
AppBuildType.dev => EnvConfig.devBaseUrl,
};
}
final AppBuildType buildType;
late String _baseUrl;
String get baseUrl => _baseUrl;
void setBaseUrl(String baseUrls) {
_baseUrl = baseUrls;
}
/// Список глобальных BlocProvider'ов
static List<BlocProvider> get globalBlocProviders => [
List<BlocProvider> get globalBlocProviders => [
BlocProvider<NewMessagesCubit>(create: (context) => sl<NewMessagesCubit>()),
BlocProvider<NotificationsCubit>(create: (context) => sl<NotificationsCubit>()..getNotifications()),
BlocProvider<FeedCubit>(create: (context) => sl<FeedCubit>()..loadFeedBlogPostList()),
@@ -25,7 +43,7 @@ class AppConfig {
];
/// Делегаты локализации
static const List<LocalizationsDelegate> localizationDelegates = [
List<LocalizationsDelegate> get localizationDelegates => [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
@@ -33,5 +51,5 @@ class AppConfig {
];
/// Поддерживаемые локали
static const List<Locale> supportedLocales = [Locale.fromSubtags(languageCode: 'ru')];
List<Locale> get supportedLocales => [const Locale.fromSubtags(languageCode: 'ru')];
}

View File

@@ -1,6 +1,8 @@
import 'dart:io' as io;
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/env_config.dart';
import 'package:eatvio_app/core/locator_service.dart' as di;
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/firebase_options.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
@@ -13,11 +15,11 @@ import 'package:sentry_flutter/sentry_flutter.dart';
/// Класс для инициализации приложения
class AppInitializer {
/// Инициализация всех сервисов приложения
static Future<void> initialize() async {
await _initializeSentry();
static Future<void> initialize({required AppBuildType buildType}) async {
await _initializeEnvironment();
await _initializeDependencyInjection(buildType: buildType);
await _initializeSentry();
await _initializeFirebase();
await _initializeDependencyInjection();
await _initializeDebugMode();
await _initializeAnalytics();
}
@@ -36,12 +38,14 @@ class AppInitializer {
/// Инициализация Firebase
static Future<void> _initializeFirebase() async {
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
await FirebaseMessaging.instance.requestPermission();
if (sl<AppConfig>().buildType == AppBuildType.prod) {
await FirebaseMessaging.instance.requestPermission();
}
}
/// Инициализация системы внедрения зависимостей
static Future<void> _initializeDependencyInjection() async {
await di.init();
static Future<void> _initializeDependencyInjection({required AppBuildType buildType}) async {
await di.init(buildType: buildType);
}
/// Настройка режима отладки
@@ -66,3 +70,5 @@ class AppInitializer {
}, appRunner: appRunner);
}
}
enum AppBuildType { prod, tests, dev }

View File

@@ -4,6 +4,7 @@ import 'package:eatvio_app/core/routing/main_navigation_routes.dart';
import 'package:eatvio_app/core/routing/other_routes.dart';
import 'package:eatvio_app/core/routing/route_constants.dart';
import 'package:eatvio_app/core/routing/settings_routes.dart';
import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart';
import 'package:flutter/material.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:go_router/go_router.dart';
@@ -50,4 +51,8 @@ class AppRouter {
return null;
}
static void navigateToRegisterViaSocial({required AuthResultEntity authResult, required String provider}) {
appRouter.pushNamed('registerViaSocialScreen', extra: {'authResult': authResult, 'provider': provider});
}
}

View File

@@ -1,6 +1,3 @@
import 'package:eatvio_app/core/env_config.dart';
String baseUrl = EnvConfig.devBaseUrl;
bool hidePlans = const bool.fromEnvironment('HIDE_PLANS', defaultValue: false);
const buildDate = String.fromEnvironment('BUILD_DATE', defaultValue: '');

View File

@@ -0,0 +1,12 @@
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/app_initializer.dart';
import 'package:get_it/get_it.dart';
class AppConfigRegistration {
static final sl = GetIt.instance;
/// Регистрация AppConfig
static void registerAppConfig({required AppBuildType buildType}) {
sl.registerLazySingleton<AppConfig>(() => AppConfig(buildType: buildType));
}
}

View File

@@ -1,6 +1,7 @@
import 'package:eatvio_app/core/internet_connection_cubit/internet_connection_cubit.dart';
import 'package:eatvio_app/core/views/cubit/views_cubit.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_cubit.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/reset_password_cubit/reset_password_cubit.dart';
import 'package:eatvio_app/features/blog_post/presentation/cubit/blog_post_cubit.dart';
import 'package:eatvio_app/features/blog_post_create/bloc/blog_post_create_cubit/blog_post_create_cubit.dart';
@@ -29,6 +30,7 @@ import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes
import 'package:eatvio_app/features/finances_and_consultations_archive/cubit/archive/consultations_archive_cubit.dart';
import 'package:eatvio_app/features/finances_and_consultations_archive/cubit/consultant_finances/consultant_finances_cubit.dart';
import 'package:eatvio_app/features/finances_and_consultations_archive/cubit/user_purchases/user_purchases_cubit.dart';
import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_cubit.dart';
import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked_users_cubit.dart';
import 'package:eatvio_app/features/menu/presentation/bloc/notification_settings_cubit/notification_settings_cubit.dart';
import 'package:eatvio_app/features/my_diets/presentation/cubit/my_diets_cubit.dart';
@@ -75,7 +77,7 @@ class CubitRegistrations {
sl.registerFactory<RegistrationCubit>(() => RegistrationCubit(registrationRepository: sl()));
sl.registerFactory<ResetPasswordCubit>(() => ResetPasswordCubit(resetPasswordRepository: sl()));
sl.registerFactory<VerifyEmailCubit>(() => VerifyEmailCubit(profileRepository: sl()));
sl.registerFactory<OAuthCubit>(() => OAuthCubit(authRepository: sl()));
// Feed related cubits
sl.registerFactory<FeedCubit>(() => FeedCubit(feedRepository: sl()));
sl.registerFactory<RecipesCubit>(() => RecipesCubit(feedRepository: sl(), recipeRepository: sl(), aboutRecipeRepository: sl()));
@@ -140,5 +142,6 @@ class CubitRegistrations {
sl.registerFactory<ConsultantRatingCubit>(() => ConsultantRatingCubit(feedRepository: sl(), repository: sl(), profileRepository: sl()));
sl.registerFactory<ViewsCubit>(() => ViewsCubit(viewsRepository: sl()));
sl.registerFactory<UserDetailsCubit>(() => UserDetailsCubit(profileRepository: sl()));
sl.registerFactory<MenuCubit>(() => MenuCubit(sl()));
}
}

View File

@@ -1,6 +1,6 @@
import 'package:dio/dio.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/dio/phone_verify_error_interceptor.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/interceptors/phone_verify_error_interceptor.dart';
import 'package:eatvio_app/core/interceptors/token_interceptor.dart';
import 'package:get_it/get_it.dart';
@@ -18,7 +18,7 @@ class ExternalRegistrations {
sl.registerLazySingleton(
() => Dio(
BaseOptions(
baseUrl: baseUrl,
baseUrl: sl<AppConfig>().baseUrl,
headers: {
'accept': 'application/json',
'content-type': 'application/json',

View File

@@ -45,7 +45,8 @@ class EnvConfig {
static String get yandexCheckUrl => dotenv.env['YANDEX_CHECK_URL'] ?? '';
// VK ID Configuration
static String get vkClientId => dotenv.env['VK_CLIENT_ID'] ?? '';
static String get vkClientIdIos => dotenv.env['VK_CLIENT_ID_IOS'] ?? '';
static String get vkClientIdAndroid => dotenv.env['VK_CLIENT_ID_ANDROID'] ?? '';
// Yandex ID Configuration
static String get yandexClientId => dotenv.env['YANDEX_CLIENT_ID'] ?? '';

View File

@@ -1,5 +1,7 @@
import 'dart:developer';
import 'dart:io';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/app_initializer.dart';
import 'package:eatvio_app/core/utils/toasts.dart';
import 'package:flutter/services.dart';
@@ -19,7 +21,9 @@ class FirebaseApi {
if (await _isHuaweiDevice()) {
token = await _getHuaweiPushTokenNative();
} else {
await _firebaseMessaging.requestPermission();
if ((sl<AppConfig>().buildType == AppBuildType.prod)) {
await _firebaseMessaging.requestPermission();
}
token = await _firebaseMessaging.getToken();
}
return token;

View File

@@ -12,8 +12,8 @@ class PhoneVerifyErrorInterceptor extends Interceptor {
final data = err.response?.data;
if (data is Map<String, dynamic> && data['type'] == 'unverificated_phone') {
final String phone = await sl<ProfileRepository>().getMyPhone();
final String passKey = await sl<ProfileRepository>().getPassKey(phone);
final String phone = await sl<ProfileRepository>().getMyPhone();
final String passKey = await sl<ProfileRepository>().getPassKey(routeName: 'user_detailz.change-phone-verify', routeParams: {"phone": phone});
await showErrorDialog(AppRouter.navigatorKey.currentContext!,
title: 'Привяжите номер телефона', description: 'Для того, что бы выполнить это действие необходимо привязать номер телефона');
AppRouter.navigatorKey.currentContext?.pushNamed('verifyScreen', extra: passKey);

View File

@@ -1,3 +1,5 @@
import 'package:eatvio_app/core/app_initializer.dart';
import 'package:eatvio_app/core/di/app_config_registration.dart';
import 'package:eatvio_app/core/di/cubit_registrations.dart';
import 'package:eatvio_app/core/di/external_registrations.dart';
import 'package:eatvio_app/core/di/repository_registrations.dart';
@@ -9,19 +11,22 @@ import 'package:get_it/get_it.dart';
final sl = GetIt.instance;
/// Инициализация системы внедрения зависимостей
Future<void> init() async {
Future<void> init({required AppBuildType buildType}) async {
// Регистрация AppConfig
AppConfigRegistration.registerAppConfig(buildType: buildType);
// Регистрация внешних зависимостей (Dio, etc.)
ExternalRegistrations.registerAll();
// Регистрация сервисов
ServiceRegistrations.registerAll();
// Регистрация репозиториев
RepositoryRegistrations.registerAll();
// Регистрация Cubit'ов
CubitRegistrations.registerAll();
// Регистрация WebSocket менеджера
sl.registerLazySingleton<WsManager>(() => WsManager(wsService: sl()));
}
}

View File

@@ -1,6 +1,8 @@
import 'package:eatvio_app/core/routing/route_constants.dart';
import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart';
import 'package:eatvio_app/features/auth/presentation/pages/auth_screen.dart';
import 'package:eatvio_app/features/auth/presentation/pages/forget_password_screen.dart';
import 'package:eatvio_app/features/auth/presentation/pages/register_via_social_screen.dart';
import 'package:eatvio_app/features/auth/presentation/pages/scan_qr_code_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/registration_screen.dart';
import 'package:eatvio_app/features/registration/presentation/pages/verify_screen.dart';
@@ -32,6 +34,14 @@ class AuthRoutes {
builder: (context, state) => VerifyScreen(passKey: state.extra as String),
),
GoRoute(path: RouteConstants.verifyEmailScreen, name: 'verifyEmailScreen', builder: (context, state) => const VerifyEmailScreen()),
GoRoute(
path: RouteConstants.registerViaSocialScreen,
name: 'registerViaSocialScreen',
builder: (context, state) {
final extra = state.extra as Map<String, dynamic>?;
return RegisterViaSocialScreen(authResult: extra?['authResult'] as AuthResultEntity?, provider: extra?['provider'] as String?);
},
),
];
}
}

View File

@@ -44,10 +44,15 @@ class ContentRoutes {
builder: (context, state) {
final slug = state.uri.queryParameters['slug'];
if (slug != null) {
return AboutDietScreen(slug: slug, index: null, navigateToComments: false);
return AboutDietScreen(id: null, slug: slug, index: null, navigateToComments: false);
}
final data = state.extra as Map<String, dynamic>;
return AboutDietScreen(slug: data['slug'] as String, index: data['index'] as int?, navigateToComments: data['navigateToComments'] as bool);
return AboutDietScreen(
id: data['id'] as int?,
slug: data['slug'] as String?,
index: data['index'] as int?,
navigateToComments: data['navigateToComments'] as bool,
);
},
),
GoRoute(

View File

@@ -1,5 +1,5 @@
import 'package:dio/dio.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/firebase_api.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/routing/route_constants.dart';
@@ -76,7 +76,7 @@ class OtherRoutes {
builder: (context, state) => const UpdateScreen(),
redirect: (context, state) async {
try {
final versions = (await sl<Dio>().get('$baseUrl/api/app_versions')).data;
final versions = (await sl<Dio>().get('${sl<AppConfig>().baseUrl}/api/app_versions')).data;
PackageInfo packageInfo = await PackageInfo.fromPlatform();
String version = packageInfo.version;
Version currentVersion = Version.parse(version);
@@ -180,7 +180,7 @@ class OtherRoutes {
),
// Other routes
GoRoute(path: RouteConstants.glossaryScreen, name: 'glossaryScreen', builder: (context, state) => const GlossaryScreen()),
GoRoute(path: RouteConstants.glossaryScreen, name: 'glossaryScreen', builder: (context, state) => GlossaryScreen(passKey: state.extra as String)),
GoRoute(path: RouteConstants.blockedUsersScreen, name: 'blockedUsersScreen', builder: (context, state) => const BlockedUsersScreen()),
GoRoute(
path: RouteConstants.notificationsSettingsScreen,

View File

@@ -7,6 +7,7 @@ class RouteConstants {
static const String scanQRCodeScreen = 'scan-qr-code-screen';
static const String verifyScreen = '/verify-screen';
static const String verifyEmailScreen = '/verify-email-screen';
static const String registerViaSocialScreen = '/register-via-social-screen';
// Main navigation routes
static const String myProfileScreen = '/my-profile-screen';

View File

@@ -3,6 +3,7 @@ import 'dart:developer';
import 'package:dart_pusher_channels/dart_pusher_channels.dart';
import 'package:easy_debounce/easy_debounce.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/websockets/ws_service.dart';
@@ -111,7 +112,7 @@ class WsManager {
_privateNotificationChannel = client?.privateChannel(
'$newNotificationsChannelName.$userId',
authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel(
authorizationEndpoint: Uri.parse('$baseUrl/broadcasting/auth'),
authorizationEndpoint: Uri.parse('${sl<AppConfig>().baseUrl}/broadcasting/auth'),
headers: {
'Authorization': 'Bearer $token',
},
@@ -124,7 +125,7 @@ class WsManager {
_privateMessagesChannel = client?.privateChannel(
'$newMessagesChannelName.$userId',
authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel(
authorizationEndpoint: Uri.parse('$baseUrl/broadcasting/auth'),
authorizationEndpoint: Uri.parse('${sl<AppConfig>().baseUrl}/broadcasting/auth'),
headers: {
'Authorization': 'Bearer $token',
},
@@ -137,7 +138,7 @@ class WsManager {
_privateDirectChatChannel = client?.privateChannel(
'$directChatChannelName.$chatId',
authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel(
authorizationEndpoint: Uri.parse('$baseUrl/broadcasting/auth'),
authorizationEndpoint: Uri.parse('${sl<AppConfig>().baseUrl}/broadcasting/auth'),
headers: {
'Authorization': 'Bearer $token',
},

View File

@@ -1,4 +1,4 @@
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/enums/complained_content.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
@@ -86,7 +86,7 @@ class CustomPopup extends StatelessWidget {
if (isAuthor) {
addItem('assets/icons/copy2.svg', 'Скопировать ссылку', () {
Clipboard.setData(ClipboardData(text: '$baseUrl/ru/$path'));
Clipboard.setData(ClipboardData(text: '${sl<AppConfig>().baseUrl}/ru/$path'));
showInfoToast(s.link_was_copied);
});
addItem('assets/icons/share2.svg', 'Поделиться', () {
@@ -94,7 +94,7 @@ class CustomPopup extends StatelessWidget {
SharePlus.instance.share(
ShareParams(
uri: Uri.parse(
'$baseUrl/ru/$path',
'${sl<AppConfig>().baseUrl}/ru/$path',
),
sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
),
@@ -140,7 +140,7 @@ class CustomPopup extends StatelessWidget {
});
} else {
addItem('assets/icons/copy2.svg', 'Скопировать ссылку', () {
Clipboard.setData(ClipboardData(text: '$baseUrl/ru/$path'));
Clipboard.setData(ClipboardData(text: '${sl<AppConfig>().baseUrl}/ru/$path'));
showInfoToast(s.link_was_copied);
});
addItem('assets/icons/share2.svg', 'Поделиться', () {
@@ -148,7 +148,7 @@ class CustomPopup extends StatelessWidget {
SharePlus.instance.share(
ShareParams(
uri: Uri.parse(
'$baseUrl/ru/$path',
'${sl<AppConfig>().baseUrl}/ru/$path',
),
sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
),

View File

@@ -8,6 +8,7 @@ abstract class AuthResultEntity with _$AuthResultEntity {
const factory AuthResultEntity({
required String accessToken,
required String userId,
required String clientId,
String? refreshToken,
String? firstName,
String? lastName,

View File

@@ -0,0 +1,16 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'oauth_login_request.freezed.dart';
part 'oauth_login_request.g.dart';
@freezed
abstract class OAuthLoginRequest with _$OAuthLoginRequest {
const factory OAuthLoginRequest({
@JsonKey(name: 'client_id') required String clientId,
@JsonKey(name: 'access_token') required String accessToken,
@JsonKey(name: 'refresh_token') required String refreshToken,
required String provider,
}) = _OAuthLoginRequest;
factory OAuthLoginRequest.fromJson(Map<String, dynamic> json) => _$OAuthLoginRequestFromJson(json);
}

View File

@@ -0,0 +1,25 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'oauth_model.freezed.dart';
part 'oauth_model.g.dart';
@freezed
abstract class OAuthModel with _$OAuthModel {
const factory OAuthModel({
@JsonKey(name: 'access_token') required String accessToken,
@JsonKey(name: 'refresh_token') required String refreshToken,
@JsonKey(name: 'first_name') required String firstName,
@JsonKey(name: 'last_name') required String lastName,
@JsonKey(name: 'date_of_birth') required String dateOfBirth,
@JsonKey(name: 'client_id') required String clientId,
required String provider,
required String id,
required String email,
required String phone,
required String gender,
required int weight,
required int height,
}) = _OAuthModel;
factory OAuthModel.fromJson(Map<String, dynamic> json) => _$OAuthModelFromJson(json);
}

View File

@@ -25,19 +25,4 @@ class AuthCubit extends Cubit<AuthState> {
return false;
}
}
Future<bool> getTokenBySocial({required String provider, required String accessToken}) async {
emit(const AuthState.loading());
try {
final token = (await authRepository.getTokenBySocial(provider: provider, accessToken: accessToken)).token;
emit(AuthState.loaded(token: token));
await TokenStorage.saveTokenInStorage(token);
return true;
} catch (e) {
log(e.toString());
showErrorToast('Не удалось войти через $provider');
emit(AuthState.error(errorMessage: '$e'));
return false;
}
}
}

View File

@@ -0,0 +1,101 @@
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:eatvio_app/core/token_storage.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_state.dart';
import 'package:eatvio_app/features/auth/repositories/auth_repository.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class OAuthCubit extends Cubit<OAuthState> {
final AuthRepository authRepository;
OAuthCubit({required this.authRepository}) : super(const OAuthState());
Future<void> signInViaSocialMedia({required String provider, required String accessToken, required String refreshToken, required String clientId}) async {
try {
emit(const OAuthState.loading());
final tokenModel = await authRepository.signInViaSocialMedia(
provider: provider,
accessToken: accessToken,
refreshToken: refreshToken,
clientId: clientId,
);
log('OAuthCubit: Got token model: ${tokenModel.token}');
TokenStorage.saveTokenInStorage(tokenModel.token);
emit(OAuthState.loaded(token: tokenModel.token));
} catch (e) {
log('OAuthCubit: Error occurred: $e');
emit(OAuthState.error(errorMessage: e.toString()));
}
}
Future<List<RegistrationValidationErrors>?> signUpViaSocialMedia({
required String provider,
required String accessToken,
required String id,
required String refreshToken,
required String firstName,
required String lastName,
required String email,
required String phone,
required String dateOfBirth,
required String gender,
required int weight,
required int height,
required String clientId,
}) async {
try {
emit(const OAuthState.loading());
final token = await authRepository.signUpViaSocialMedia(
provider: provider,
accessToken: accessToken,
id: id,
refreshToken: refreshToken,
firstName: firstName,
lastName: lastName,
email: email,
phone: phone,
dateOfBirth: dateOfBirth,
gender: gender,
weight: weight,
height: height,
clientId: clientId,
);
TokenStorage.saveTokenInStorage(token);
emit(OAuthState.loaded(token: token));
} on DioException catch (e) {
emit(OAuthState.error(errorMessage: e.toString()));
final errors = e.response?.data['errors'] as Map<String, dynamic>?;
final emailErrors = errors?['email'] as List<dynamic>?;
final phoneErrors = errors?['phone'] as List<dynamic>?;
final dateOfBirth = errors?['date_of_birth'] as List<dynamic>?;
final errorsList = <RegistrationValidationErrors>[];
if (emailErrors != null && emailErrors.isNotEmpty) {
if (emailErrors.contains('Некорректный формат email')) {
errorsList.add(RegistrationValidationErrors.incorrectEmailFormat);
}
if (emailErrors.contains('Такой Эл. почта уже существует.')) {
errorsList.add(RegistrationValidationErrors.emailExist);
}
}
if (phoneErrors != null && phoneErrors.isNotEmpty) {
if (phoneErrors.contains('Такой phone уже существует.')) {
errorsList.add(RegistrationValidationErrors.phoneExist);
}
}
if (dateOfBirth != null && dateOfBirth.isNotEmpty) {
if (dateOfBirth.contains('Некорректный формат даты рождения')) {
errorsList.add(RegistrationValidationErrors.incorrectDateOfBirthFormat);
}
}
if (errorsList.isNotEmpty) {
return errorsList;
}
}
return null;
}
}
enum RegistrationValidationErrors { incorrectEmailFormat, emailExist, phoneExist, incorrectDateOfBirthFormat }

View File

@@ -0,0 +1,14 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'oauth_state.freezed.dart';
@freezed
abstract class OAuthState with _$OAuthState {
const factory OAuthState() = _OAuthState;
const factory OAuthState.loading() = OAuthStateLoading;
const factory OAuthState.loaded({required String token}) = OAuthStateLoaded;
const factory OAuthState.error({required String errorMessage}) = OAuthStateError;
}

View File

@@ -1,7 +1,7 @@
// ignore_for_file: unused_element, duplicate_ignore
import 'dart:async';
import 'dart:developer';
import 'package:eatvio_app/app_keys.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/app_router.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/firebase_api.dart';
@@ -14,6 +14,10 @@ import 'package:eatvio_app/core/widgets/custom_divider.dart';
import 'package:eatvio_app/core/widgets/custom_text_form_field.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_state.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_cubit.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_state.dart';
import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart';
import 'package:eatvio_app/core/di/cubit_registrations.dart';
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
import 'package:eatvio_app/features/dev_tools/presentation/dev_tools_screen.dart';
@@ -46,7 +50,7 @@ class _AuthScreenState extends State<AuthScreen> {
late StreamSubscription<bool> keyboardSubscription;
bool isFocused = false;
int tapsCount = 0;
bool _isLoading = false;
@override
void initState() {
super.initState();
@@ -89,9 +93,142 @@ class _AuthScreenState extends State<AuthScreen> {
AppRouter.navigatorKey.currentContext?.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
}
void _onVkPressed() async {
try {
log('VK button pressed');
final context = AppRouter.navigatorKey.currentContext;
if (context == null) {
log('Context is null');
return;
}
log('Getting VK auth result');
final authResult = await SocialAuthFacade.signInWithVkAndFetchProfile(context: context);
if (authResult == null) {
log('VK auth result is null');
return;
}
log('VK auth result received, trying OAuth login');
if (context.mounted) {
await _tryOAuthLogin(context, authResult, 'vk');
} else {
log('Context is not mounted');
}
} catch (e) {
log('VK button error: $e');
}
}
void _onOkPressed() async {
try {
final context = AppRouter.navigatorKey.currentContext;
if (context == null) return;
final authResult = await SocialAuthFacade.signInWithOkAndFetchProfile();
if (authResult == null) {
return;
}
if (context.mounted) {
await _tryOAuthLogin(context, authResult, 'vk');
}
} catch (e) {
log(e.toString());
}
}
void _onMailRuPressed() async {
try {
final context = AppRouter.navigatorKey.currentContext;
if (context == null) return;
final authResult = await SocialAuthFacade.signInWithMailRuAndFetchProfile();
if (authResult == null) {
return;
}
if (context.mounted) {
await _tryOAuthLogin(context, authResult, 'vk');
}
} catch (e) {
log(e.toString());
}
}
void _onYandexPressed() async {
try {
final context = AppRouter.navigatorKey.currentContext;
if (context == null) return;
final authResult = await SocialAuthFacade.signInWithYandex();
if (authResult == null) return;
if (context.mounted) {
await _tryOAuthLogin(context, authResult, 'yandex');
}
} catch (e) {
log(e.toString());
}
}
Future<void> _tryOAuthLogin(BuildContext context, AuthResultEntity authResult, String provider) async {
log('Starting OAuth login for provider: $provider');
try {
final oauthCubit = CubitRegistrations.sl<OAuthCubit>();
StreamSubscription? subscription;
subscription = oauthCubit.stream.listen((state) {
log('OAuth state changed: ${state.runtimeType}');
if (state is OAuthStateLoaded) {
log('OAuth login successful, navigating to main screen');
subscription?.cancel();
_reconnectAfterAuth();
} else if (state is OAuthStateError) {
log('OAuth login failed: ${state.errorMessage}');
subscription?.cancel();
AppRouter.navigateToRegisterViaSocial(authResult: authResult, provider: provider);
}
});
log('Calling getOAuthLogin with provider: $provider');
await oauthCubit.signInViaSocialMedia(
provider: provider,
accessToken: authResult.accessToken,
refreshToken: authResult.refreshToken ?? '',
clientId: authResult.clientId,
);
} catch (e) {
log('OAuth login error in catch block: $e');
AppRouter.navigateToRegisterViaSocial(authResult: authResult, provider: provider);
}
}
Future<void> _reconnectAfterAuth() async {
final context = AppRouter.navigatorKey.currentContext;
if (context == null) return;
try {
await sl<WsManager>().clear();
await sl<WsManager>().initialize();
await sl<ProfileAvatarCubit>().getMyProfile();
await sl<ChatsCubit>().getChatRoomsWithLoading();
await sl<ChatsCubit>().connectToWebSocket();
await sl<NotificationsCubit>().getNotifications();
await sl<NotificationsCubit>().connectToWebSocket();
await sl<FirebaseApi>().registerPushToken();
showSuccessToast('Успешный вход');
} catch (e) {
log(e.toString());
}
AppRouter.navigatorKey.currentContext?.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
}
@override
Widget build(BuildContext context) {
var shortestSide = MediaQuery.sizeOf(context).shortestSide;
final screenSize = MediaQuery.of(context).size;
final bool useMobileLayout = shortestSide < 600;
if (!useMobileLayout) isFocused = true;
final s = S.of(context);
@@ -102,9 +239,10 @@ class _AuthScreenState extends State<AuthScreen> {
builder: (BuildContext context, AuthState state) {
return Scaffold(
appBar: AppBar(
toolbarHeight: screenSize.height * 0.15,
centerTitle: true,
toolbarHeight: isFocused ? 64 : MediaQuery.of(context).size.width - 64,
title: GestureDetector(
key: AppKeys.hiddenLogoButtonAuthScreen,
onTap: () {
tapsCount++;
if (tapsCount == 7) {
@@ -112,7 +250,7 @@ class _AuthScreenState extends State<AuthScreen> {
GoRouter.of(context).pushNamed(DevToolsScreen.name);
}
},
child: SvgPicture.asset(ImageConstant.imgLogoEatvio, height: isFocused ? 64 : MediaQuery.of(context).size.width - 64, fit: BoxFit.contain),
child: SvgPicture.asset(ImageConstant.imgLogoEatvio, height: screenSize.height * 0.20),
),
),
body: SafeArea(
@@ -121,9 +259,8 @@ class _AuthScreenState extends State<AuthScreen> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Social auth buttons at the top (outlined)
const Text('Авторизация через:', style: TextStyle(fontWeight: FontWeight.w600)),
const SizedBox(height: 8),
const Center(child: Text('Авторизация через')),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
@@ -164,6 +301,7 @@ class _AuthScreenState extends State<AuthScreen> {
textInputAction: TextInputAction.next,
keyboardType: TextInputType.emailAddress,
textInputType: TextInputType.emailAddress,
key: AppKeys.emailTextFieldAuthScreen,
hintText: 'Введите email',
),
const SizedBox(height: 16),
@@ -172,6 +310,7 @@ class _AuthScreenState extends State<AuthScreen> {
CustomTextFormField(
obscureText: hidePassword,
controller: passwordController,
key: AppKeys.passwordTextFieldAuthScreen,
hintText: 'Введите пароль',
suffix: IconButton(
onPressed: () {
@@ -224,7 +363,7 @@ class _AuthScreenState extends State<AuthScreen> {
decorationColor: appTheme.blueA400,
decoration: TextDecoration.underline,
),
recognizer: TapGestureRecognizer()..onTap = () async => await launchUrl(Uri.parse('$baseUrl/oferta_bs.pdf')),
recognizer: TapGestureRecognizer()..onTap = () async => await launchUrl(Uri.parse('${sl<AppConfig>().baseUrl}/oferta_bs.pdf')),
),
const TextSpan(text: ' и '),
],
@@ -236,7 +375,7 @@ class _AuthScreenState extends State<AuthScreen> {
decorationColor: appTheme.blueA400,
decoration: TextDecoration.underline,
),
recognizer: TapGestureRecognizer()..onTap = () async => await launchUrl(Uri.parse('$baseUrl/docs/privacy.pdf')),
recognizer: TapGestureRecognizer()..onTap = () async => await launchUrl(Uri.parse('${sl<AppConfig>().baseUrl}/docs/privacy.pdf')),
),
],
),
@@ -249,21 +388,28 @@ class _AuthScreenState extends State<AuthScreen> {
height: 48,
width: MediaQuery.of(context).size.width - 88,
child: FloatingActionButton.extended(
key: AppKeys.signInButtonAuthScreen,
heroTag: 'authButton',
highlightElevation: 0,
elevation: 0,
focusElevation: 0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
backgroundColor: state is AuthStateLoading ? Colors.black.withAlpha(50) : appTheme.blueA400,
onPressed: state is AuthStateLoading
backgroundColor: (state is AuthStateLoading || _isLoading) ? Colors.black.withAlpha(50) : appTheme.blueA400,
onPressed: (state is AuthStateLoading || _isLoading)
? null
: () async {
setState(() {
_isLoading = true;
});
final isAuthenticated = await authCubit.getTokenByCredentials(emailController.text, passwordController.text);
if (isAuthenticated) {
if (context.mounted) {
_reconnectWebSocket(context);
await _reconnectWebSocket(context);
}
}
setState(() {
_isLoading = false;
});
},
label: state is AuthStateLoading
? const CupertinoActivityIndicator()
@@ -296,7 +442,7 @@ class _AuthScreenState extends State<AuthScreen> {
children: [
const Text('Где взять QR-код?\n', style: TextStyle(fontSize: 18)),
Text(
'1. Войдите на сайте $baseUrl в свой аккаунт\n\n2. Перейдите в настройки профиля\n\n3. В разделе "Доп информация" перейдите на "QR Login"',
'1. Войдите на сайте ${sl<AppConfig>().baseUrl} в свой аккаунт\n\n2. Перейдите в настройки профиля\n\n3. В разделе "Доп информация" перейдите на "QR Login"',
),
const SizedBox(height: 12),
Row(
@@ -388,58 +534,3 @@ class _SocialButton extends StatelessWidget {
);
}
}
void _onVkPressed() async {
try {
final accessToken = await SocialAuthFacade.signInWithVk();
if (accessToken == null) {
return;
}
} catch (e) {
log(e.toString());
}
}
void _onOkPressed() async {
try {
final accessToken = await SocialAuthFacade.signInWithOk();
if (accessToken == null) {
return;
}
} catch (e) {
log(e.toString());
}
}
void _onMailRuPressed() async {
try {
final accessToken = await SocialAuthFacade.signInWithMailRu();
if (accessToken == null) {
return;
}
} catch (e) {
log(e.toString());
}
}
void _onYandexPressed() async {
final accessToken = await SocialAuthFacade.signInWithYandex();
if (accessToken == null) return;
}
Future<void> _reconnectAfterAuth() async {
final context = AppRouter.navigatorKey.currentContext;
if (context == null) return;
try {
await sl<WsManager>().clear();
await sl<WsManager>().initialize();
await sl<ProfileAvatarCubit>().getMyProfile();
await sl<ChatsCubit>().getChatRoomsWithLoading();
await sl<ChatsCubit>().connectToWebSocket();
await sl<NotificationsCubit>().getNotifications();
await sl<NotificationsCubit>().connectToWebSocket();
await sl<FirebaseApi>().registerPushToken();
showSuccessToast('Успешный вход');
} catch (_) {}
AppRouter.navigatorKey.currentContext?.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
}

View File

@@ -0,0 +1,532 @@
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/widgets/custom_text_form_field.dart';
import 'package:eatvio_app/core/di/cubit_registrations.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_cubit.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_state.dart';
import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart';
import 'package:eatvio_app/core/app_router.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/websockets/ws_manager.dart';
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart';
import 'package:eatvio_app/features/notifications/presentation/notifications_cubit/notifications_cubit.dart';
import 'package:eatvio_app/core/firebase_api.dart';
import 'package:eatvio_app/core/utils/toasts.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mask_text_input_formatter/mask_text_input_formatter.dart';
import 'package:url_launcher/url_launcher.dart';
class RegisterViaSocialScreen extends StatefulWidget {
final AuthResultEntity? authResult;
final String? provider;
const RegisterViaSocialScreen({super.key, this.authResult, this.provider});
@override
State<RegisterViaSocialScreen> createState() => _RegisterViaSocialScreenState();
}
class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
final maskFormatter = MaskTextInputFormatter(mask: '+7 (###) ### ## ##', filter: {"#": RegExp(r'[0-9]')}, type: MaskAutoCompletionType.lazy);
final maskFormatterForBirthday = MaskTextInputFormatter(mask: '##.##.####', filter: {"#": RegExp(r'[0-9]')}, type: MaskAutoCompletionType.lazy);
// Контроллеры для полей ввода
final firstNameController = TextEditingController();
final lastNameController = TextEditingController();
final emailController = TextEditingController();
final phoneController = TextEditingController();
final dateOfBirthController = TextEditingController();
final weightController = TextEditingController();
final heightController = TextEditingController();
bool emailExistError = false;
bool phoneExistError = false;
bool dateOfBirthError = false;
bool weightError = false;
bool heightError = false;
bool incorrectEmailFormatError = false;
// Состояние для выбора пола
bool isMaleSelected = true;
@override
void initState() {
super.initState();
_initializeFieldsFromAuthResult();
}
Future<void> _reconnectWebSocket(BuildContext context) async {
try {
await sl<WsManager>().clear();
await sl<WsManager>().initialize();
} catch (e) {
rethrow;
}
if (context.mounted) {
try {
await sl<ProfileAvatarCubit>().getMyProfile();
await sl<ChatsCubit>().getChatRoomsWithLoading();
await sl<ChatsCubit>().connectToWebSocket();
await sl<NotificationsCubit>().getNotifications();
await sl<NotificationsCubit>().connectToWebSocket();
await sl<FirebaseApi>().registerPushToken();
showSuccessToast('Успешная регистрация');
} catch (e) {
rethrow;
}
}
AppRouter.appRouter.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
}
void _initializeFieldsFromAuthResult() {
if (widget.authResult != null) {
final authResult = widget.authResult!;
if (authResult.firstName != null) {
firstNameController.text = authResult.firstName!;
}
if (authResult.lastName != null) {
lastNameController.text = authResult.lastName!;
}
if (authResult.email != null) {
emailController.text = authResult.email!;
}
if (authResult.phone != null) {
final cleanPhone = authResult.phone!.replaceAll(RegExp(r'[^\d]'), '');
final normalizedPhone = cleanPhone.startsWith('8') ? '7${cleanPhone.substring(1)}' : cleanPhone;
final phoneWithCountryCode = normalizedPhone.startsWith('7') ? normalizedPhone : '7$normalizedPhone';
final formattedPhone = maskFormatter.maskText('+$phoneWithCountryCode');
phoneController.text = formattedPhone;
}
if (authResult.birthDate != null) {
final formattedDate = _formatBirthDate(authResult.birthDate!);
final maskedDate = maskFormatterForBirthday.maskText(formattedDate);
dateOfBirthController.text = maskedDate;
}
if (authResult.gender != null) {
isMaleSelected = authResult.gender == GenderEnum.male;
}
}
}
String _formatBirthDate(String birthDate) {
try {
// Пытаемся распарсить различные форматы даты
DateTime? date;
// Если дата в формате ISO (YYYY-MM-DD)
if (birthDate.contains('-')) {
date = DateTime.tryParse(birthDate);
}
// Если дата в формате DD.MM.YYYY
else if (birthDate.contains('.')) {
final parts = birthDate.split('.');
if (parts.length == 3) {
final day = int.tryParse(parts[0]);
final month = int.tryParse(parts[1]);
final year = int.tryParse(parts[2]);
if (day != null && month != null && year != null) {
date = DateTime(year, month, day);
}
}
}
if (date != null) {
// Форматируем в DD.MM.YYYY
final day = date.day.toString().padLeft(2, '0');
final month = date.month.toString().padLeft(2, '0');
final year = date.year.toString();
return '$day.$month.$year';
}
} catch (e) {
// Если не удалось распарсить, возвращаем исходную строку
}
return birthDate;
}
@override
void dispose() {
firstNameController.dispose();
lastNameController.dispose();
emailController.dispose();
phoneController.dispose();
dateOfBirthController.dispose();
weightController.dispose();
heightController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocProvider<OAuthCubit>(
create: (context) => CubitRegistrations.sl<OAuthCubit>(),
child: Scaffold(
appBar: AppBar(),
body: BlocBuilder<OAuthCubit, OAuthState>(
builder: (context, state) {
return SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Center(
child: Text(
'Регистрация',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.w700, height: 1.1, color: Color(0xFF323F4B)),
),
),
const SizedBox(height: 24),
Row(
children: [
SizedBox(
width: MediaQuery.of(context).size.width / 2 - 22,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
const Text('Имя'),
const SizedBox(height: 4),
CustomTextFormField(controller: firstNameController, hintText: 'Введите имя', onChanged: (newValue) {}),
],
),
),
const SizedBox(width: 12),
SizedBox(
width: MediaQuery.of(context).size.width / 2 - 22,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Фамилия'),
const SizedBox(height: 4),
CustomTextFormField(controller: lastNameController, hintText: 'Введите фамилию', onChanged: (newValue) {}),
],
),
),
],
),
const SizedBox(height: 12),
const Text('Почта'),
const SizedBox(height: 4),
CustomTextFormField(
controller: emailController,
textInputType: TextInputType.emailAddress,
keyboardType: TextInputType.emailAddress,
hintText: 'Введите email',
textInputAction: TextInputAction.next,
hasError: emailExistError || incorrectEmailFormatError,
onChanged: (newValue) {},
),
if (emailExistError) ...[const SizedBox(height: 4), const ValidationErrorWidget(error: 'Такая почта уже существует.')],
if (incorrectEmailFormatError) ...[const SizedBox(height: 4), const ValidationErrorWidget(error: 'Некорректный формат email')],
const SizedBox(height: 12),
const Text('Номер телефона'),
const SizedBox(height: 4),
CustomTextFormField(
textInputAction: TextInputAction.done,
hintText: '+7 (999) 999 99 99',
controller: phoneController,
keyboardType: TextInputType.number,
inputFormatters: [maskFormatter],
hasError: phoneExistError,
onChanged: (newValue) {},
),
if (phoneExistError) ...[const SizedBox(height: 4), const ValidationErrorWidget(error: 'Такой номер телефона уже существует.')],
const SizedBox(height: 12),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: MediaQuery.of(context).size.width / 2 - 22,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
const Text('Дата рождения'),
const SizedBox(height: 4),
CustomTextFormField(
textInputAction: TextInputAction.done,
hintText: '01.01.2000',
controller: dateOfBirthController,
keyboardType: TextInputType.number,
hasError: dateOfBirthError,
inputFormatters: [maskFormatterForBirthday],
onChanged: (newValue) {},
),
if (dateOfBirthError) ...[const SizedBox(height: 4), const ValidationErrorWidget(error: 'Некорректный формат даты рождения')],
],
),
),
const SizedBox(width: 12),
SizedBox(
width: MediaQuery.of(context).size.width / 2 - 22,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Пол'),
const SizedBox(height: 4),
Row(
children: [
Expanded(child: _genderButton('М', isMaleSelected)),
const SizedBox(width: 4),
Expanded(child: _genderButton('Ж', !isMaleSelected)),
],
),
],
),
),
],
),
const SizedBox(height: 12),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: MediaQuery.of(context).size.width / 2 - 22,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
const Text('Вес'),
const SizedBox(height: 4),
CustomTextFormField(controller: weightController, hintText: 'Введите вес', onChanged: (newValue) {}, hasError: weightError),
if (weightError) ...[const SizedBox(height: 4), const ValidationErrorWidget(error: 'Вес должен быть от 30 до 300 кг')],
],
),
),
const SizedBox(width: 12),
SizedBox(
width: MediaQuery.of(context).size.width / 2 - 22,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Рост'),
const SizedBox(height: 4),
CustomTextFormField(controller: heightController, hintText: 'Введите рост', onChanged: (newValue) {}, hasError: heightError),
if (heightError) ...[const SizedBox(height: 4), const ValidationErrorWidget(error: 'Рост должен быть от 100 до 250 см')],
],
),
),
],
),
const SizedBox(height: 28),
const Center(
child: Text(
'Проверьте правильность заполненных\nданных. Пол, рост и вес требуются для\nрасчета вашей дневной нормы калорий',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xFF323F4B)),
textAlign: TextAlign.center,
),
),
const SizedBox(height: 28),
InkWell(
borderRadius: BorderRadius.circular(20),
onTap: () => _handleRegistration(context),
child: Ink(
width: MediaQuery.of(context).size.width - 32,
height: 52,
decoration: BoxDecoration(color: state is OAuthStateLoading ? Colors.grey : appTheme.blueA400, borderRadius: BorderRadius.circular(20)),
child: Center(
child: state is OAuthStateLoading
? const CircularProgressIndicator(color: Colors.white)
: const Text(
'Зарегистрироваться',
style: TextStyle(fontWeight: FontWeight.w600, fontSize: 18, color: Colors.white),
),
),
),
),
const SizedBox(height: 16),
Center(
child: RichText(
textAlign: TextAlign.center,
text: TextSpan(
text: 'Нажимая "Зарегистрироваться", Вы соглашаетесь\n',
style: const TextStyle(fontSize: 16, color: Colors.black),
children: [
const TextSpan(
text: 'c ',
style: TextStyle(fontSize: 16, color: Colors.black),
),
if (!hidePlans) ...[
TextSpan(
text: ' Публичной офертой',
style: TextStyle(
fontSize: 16,
color: appTheme.blueA400,
decorationColor: appTheme.blueA400,
decoration: TextDecoration.underline,
),
recognizer: TapGestureRecognizer()..onTap = () async => await launchUrl(Uri.parse('${sl<AppConfig>().baseUrl}oferta_bs.pdf')),
),
const TextSpan(
text: ' и ',
style: TextStyle(fontSize: 16, color: Colors.black),
),
],
TextSpan(
text: 'Политикой конфиденциальности и защитой персональных данных',
style: TextStyle(fontSize: 16, color: appTheme.blueA400, decorationColor: appTheme.blueA400, decoration: TextDecoration.underline),
recognizer: TapGestureRecognizer()..onTap = () async => await launchUrl(Uri.parse('${sl<AppConfig>().baseUrl}/docs/privacy.pdf')),
),
],
),
),
),
// Обработка успешной регистрации
if (state is OAuthStateLoaded) ...[
const SizedBox(height: 16),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.green.shade50,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.green.shade200),
),
child: const Text(
'Регистрация успешно завершена!',
style: TextStyle(color: Colors.green),
textAlign: TextAlign.center,
),
),
// Автоматический переход на главный экран после успешной регистрации
Builder(
builder: (context) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_reconnectWebSocket(context);
});
return const SizedBox.shrink();
},
),
],
],
),
);
},
),
),
);
}
Widget _genderButton(String gender, bool isActive) {
return InkWell(
onTap: () {
setState(() {
isMaleSelected = gender == 'М';
});
},
borderRadius: BorderRadius.circular(20),
child: Ink(
height: 52,
decoration: BoxDecoration(
color: const Color(0xFFF6F6F6),
borderRadius: BorderRadius.circular(20),
border: isActive ? Border.all(width: 2, color: appTheme.blueA400) : null,
),
child: Center(
child: Text(
gender,
style: TextStyle(color: isActive ? appTheme.blueA400 : const Color(0xFF323F4B), fontSize: 16, fontWeight: FontWeight.w500),
),
),
),
);
}
Future<void> _handleRegistration(BuildContext context) async {
final clientID = widget.authResult?.clientId;
// Валидация полей
if (firstNameController.text.isEmpty ||
lastNameController.text.isEmpty ||
emailController.text.isEmpty ||
phoneController.text.isEmpty ||
dateOfBirthController.text.isEmpty ||
weightController.text.isEmpty ||
heightController.text.isEmpty) {
showErrorToast('Пожалуйста, заполните все поля');
return;
}
// Парсим числовые значения
int? weight;
int? height;
weight = int.tryParse(weightController.text);
height = int.tryParse(heightController.text);
bool hasErrorWeightOrHeightError = false;
if (weight == null || height == null) {
setState(() {
weightError = true;
heightError = true;
});
hasErrorWeightOrHeightError = true;
}
if (weight! < 30 || weight > 300) {
setState(() {
weightError = true;
});
hasErrorWeightOrHeightError = true;
}
if (height! < 100 || height > 250) {
setState(() {
heightError = true;
});
hasErrorWeightOrHeightError = true;
}
if (hasErrorWeightOrHeightError) return;
// Очищаем номер телефона от маски для отправки
final cleanPhone = phoneController.text.replaceAll(RegExp(r'[^\d+]'), '');
if (clientID == null) return;
// Вызываем OAuth регистрацию
final errors = await context.read<OAuthCubit>().signUpViaSocialMedia(
provider: widget.provider ?? 'social',
accessToken: widget.authResult?.accessToken ?? 'dummy_token',
id: widget.authResult?.userId ?? 'dummy_id',
refreshToken: widget.authResult?.refreshToken ?? 'dummy_refresh_token',
firstName: firstNameController.text,
lastName: lastNameController.text,
email: emailController.text,
phone: cleanPhone,
dateOfBirth: dateOfBirthController.text,
gender: isMaleSelected ? 'М' : 'Ж',
weight: weight,
height: height,
clientId: clientID,
);
if (errors != null) {
for (final error in errors) {
switch (error) {
case RegistrationValidationErrors.incorrectEmailFormat:
setState(() {
incorrectEmailFormatError = true;
});
break;
case RegistrationValidationErrors.emailExist:
setState(() {
emailExistError = true;
});
break;
case RegistrationValidationErrors.phoneExist:
setState(() {
phoneExistError = true;
});
break;
case RegistrationValidationErrors.incorrectDateOfBirthFormat:
setState(() {
dateOfBirthError = true;
});
break;
}
}
return;
}
showSuccessToast('Регистрация успешна');
}
}

View File

@@ -1,8 +1,8 @@
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/app_router.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/firebase_api.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/token_storage.dart';
@@ -40,17 +40,11 @@ class _ScanQRCodeScreenState extends State<ScanQRCodeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Сканирование QR-кода'),
centerTitle: true,
),
appBar: AppBar(title: const Text('Сканирование QR-кода'), centerTitle: true),
body: Column(
children: <Widget>[
Expanded(
child: QRView(
key: qrKey,
onQRViewCreated: _onQRViewCreated,
),
child: QRView(key: qrKey, onQRViewCreated: _onQRViewCreated),
),
],
),
@@ -68,17 +62,9 @@ class _ScanQRCodeScreenState extends State<ScanQRCodeScreen> {
final scannedUrl = scanData.code;
final uri = Uri.parse(scannedUrl ?? '');
final scannedBaseUrl = (uri.hasAuthority) ? '${uri.scheme}://${uri.host}' : '';
baseUrl = scannedBaseUrl;
sl<Dio>().options.baseUrl = baseUrl;
final response = await Dio().getUri(
uri,
options: Options(
headers: {
'accept': 'application/json',
'content-type': 'application/json',
},
),
);
sl<AppConfig>().setBaseUrl(scannedBaseUrl);
sl<Dio>().options.baseUrl = scannedBaseUrl;
final response = await Dio().getUri(uri, options: Options(headers: {'accept': 'application/json', 'content-type': 'application/json'}));
final token = response.data['token'];
await TokenStorage.saveTokenInStorage(token);
try {
@@ -97,10 +83,7 @@ class _ScanQRCodeScreenState extends State<ScanQRCodeScreen> {
} catch (e) {
rethrow;
}
AppRouter.navigatorKey.currentContext?.go(
'/feed-screen',
extra: {'needToInitializeWebSocket': false},
);
AppRouter.navigatorKey.currentContext?.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
showSuccessToast('Добро пожаловать!');
} catch (e) {
await controller.resumeCamera();

View File

@@ -1,39 +1,76 @@
import 'package:eatvio_app/features/auth/models/credentials_model.dart';
import 'package:eatvio_app/features/auth/models/oauth_model.dart';
import 'package:eatvio_app/features/auth/models/oauth_login_request.dart';
import 'package:eatvio_app/features/auth/models/token_model.dart';
import 'package:eatvio_app/features/auth/services/auth_service.dart';
import 'package:eatvio_app/features/auth/models/social_exchange_request.dart';
class AuthRepository {
final AuthService authService;
AuthRepository({required this.authService});
Future<TokenModel> getTokenByCredentials(
String email,
String password,
) async {
Future<TokenModel> getTokenByCredentials(String email, String password) async {
try {
return await authService.getTokenByCredentials(
credentials: CredentialsModel(
email: email,
password: password,
),
credentials: CredentialsModel(email: email, password: password),
);
} catch (e) {
rethrow;
}
}
Future<TokenModel> getTokenBySocial({
Future<TokenModel> signInViaSocialMedia({
required String provider,
required String accessToken,
required String refreshToken,
required String clientId,
}) async {
try {
return await authService.getTokenBySocial(
body: SocialExchangeRequest(provider: provider, accessToken: accessToken),
return await authService.signInViaSocialMedia(
body: OAuthLoginRequest(provider: provider, accessToken: accessToken, refreshToken: refreshToken, clientId: clientId),
);
} catch (e) {
rethrow;
}
}
Future<String> signUpViaSocialMedia({
required String provider,
required String accessToken,
required String id,
required String refreshToken,
required String firstName,
required String lastName,
required String email,
required String phone,
required String dateOfBirth,
required String gender,
required int weight,
required int height,
required String clientId,
}) async {
try {
return (await authService.signUpViaSocialMedia(
body: OAuthModel(
provider: provider,
accessToken: accessToken,
id: id,
refreshToken: refreshToken,
firstName: firstName,
lastName: lastName,
email: email,
phone: phone,
dateOfBirth: dateOfBirth,
gender: gender == 'М' ? 'male' : 'female',
weight: weight,
height: height,
clientId: clientId,
),
))['token']!
as String;
} catch (e) {
rethrow;
}
}
}

View File

@@ -1,12 +1,14 @@
import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart';
import 'package:eatvio_app/features/auth/models/yandex_profile_model.dart';
import 'package:flutter/material.dart';
import 'package:eatvio_app/core/app_router.dart';
import 'package:eatvio_app/core/env_config.dart';
import 'package:go_router/go_router.dart';
import 'package:http/http.dart' as http;
import 'package:vk_id/vk_id.dart';
import 'package:webview_flutter/webview_flutter.dart';
@@ -20,14 +22,14 @@ class SocialAuthFacade {
}
static Future<AuthResultEntity?> signInWithVkAndFetchProfile({required BuildContext context}) async {
final clientIdStr = EnvConfig.vkClientId.trim();
final clientIdStr = Platform.isIOS ? EnvConfig.vkClientIdIos.trim() : EnvConfig.vkClientIdAndroid.trim();
if (clientIdStr.isEmpty) {
return null;
}
try {
final controller = VkIDController(clID: int.parse(clientIdStr));
final authUri = controller.generateAuthorizeLinkWithCodeVerifier();
final authUri = controller.generateAuthorizeLinkWithCodeVerifier(provider: VkProvider.vkID, scopes: [VkScope.email, VkScope.phone]);
final authUrl = authUri.value.toString();
final codeVerifier = authUri.key;
@@ -37,7 +39,7 @@ class SocialAuthFacade {
if (redirectParams == null) {
return null;
}
return await _parseVKAuthResult(redirectParams: redirectParams, controller: controller, codeVerifier: codeVerifier);
return await _parseVKAuthResult(redirectParams: redirectParams, controller: controller, codeVerifier: codeVerifier, clientId: clientIdStr);
} catch (e) {
return null;
}
@@ -47,6 +49,7 @@ class SocialAuthFacade {
required Map<String, String> redirectParams,
required VkIDController controller,
required String codeVerifier,
required String clientId,
}) async {
final code = redirectParams['code'];
final deviceId = redirectParams['device_id'];
@@ -87,36 +90,20 @@ class SocialAuthFacade {
phone: profile.phone,
gender: GenderEnum.fromVkGender(profile.parsedSex),
birthDate: profile.bDayDt?.toString(),
clientId: clientId,
);
}
Future<Map<String, dynamic>?> exchangeCodeForToken(String code, String clientId, String clientSecret) async {
final response = await http.post(
Uri.parse('https://oauth.yandex.ru/token'),
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: {'grant_type': 'authorization_code', 'code': code, 'client_id': clientId, 'client_secret': clientSecret},
);
if (response.statusCode == 200) {
return jsonDecode(response.body) as Map<String, dynamic>;
} else {
log('Error exchanging code: ${response.body}');
}
return null;
}
static Future<String?> signInWithOk() async {
static Future<AuthResultEntity?> signInWithOkAndFetchProfile() async {
final context = AppRouter.navigatorKey.currentContext;
if (context == null) return null;
final vkAuthRes = await _signInWithVkIdProvider(context: context, provider: VkProvider.okRu);
return vkAuthRes?.accessToken;
return await _signInWithVkIdProvider(context: context, provider: VkProvider.okRu);
}
static Future<String?> signInWithMailRu() async {
static Future<AuthResultEntity?> signInWithMailRuAndFetchProfile() async {
final context = AppRouter.navigatorKey.currentContext;
if (context == null) return null;
final vkAuthRes = await _signInWithVkIdProvider(context: context, provider: VkProvider.mailRu);
return vkAuthRes?.accessToken;
return await _signInWithVkIdProvider(context: context, provider: VkProvider.mailRu);
}
static Future<AuthResultEntity?> signInWithYandex() async {
@@ -135,7 +122,7 @@ class SocialAuthFacade {
'response_type': 'code',
'client_id': clientId,
'redirect_uri': redirectUri,
'force_confirm': 'yes',
'force_confirm': 'true',
}).toString();
final redirectSchemePrefix = redirectUri;
@@ -167,6 +154,7 @@ class SocialAuthFacade {
phone: yandexProfileData.defaultPhone.number,
gender: GenderEnum.fromString(yandexProfileData.sex),
birthDate: yandexProfileData.birthday,
clientId: clientId,
);
} catch (e) {
log(e.toString());
@@ -197,14 +185,14 @@ class SocialAuthFacade {
}
static Future<AuthResultEntity?> _signInWithVkIdProvider({required BuildContext context, required VkProvider provider}) async {
final clientIdStr = EnvConfig.vkClientId.trim();
final clientIdStr = Platform.isIOS ? EnvConfig.vkClientIdIos.trim() : EnvConfig.vkClientIdAndroid.trim();
if (clientIdStr.isEmpty) {
return null;
}
try {
final controller = VkIDController(clID: int.parse(clientIdStr));
final authUri = controller.generateAuthorizeLinkWithCodeVerifier(provider: provider);
final authUri = controller.generateAuthorizeLinkWithCodeVerifier(provider: provider, scopes: [VkScope.phone, VkScope.email]);
final codeVerifier = authUri.key;
final authUrl = authUri.value.toString();
final redirectScheme = 'vk$clientIdStr://';
@@ -215,7 +203,7 @@ class SocialAuthFacade {
final deviceId = redirectParams['device_id'];
if (code == null || deviceId == null) return null;
return await _parseVKAuthResult(redirectParams: redirectParams, controller: controller, codeVerifier: codeVerifier);
return await _parseVKAuthResult(redirectParams: redirectParams, controller: controller, codeVerifier: codeVerifier, clientId: clientIdStr);
} catch (e) {
return null;
}
@@ -246,7 +234,9 @@ class SocialAuthFacade {
}
}
}
Navigator.of(context, rootNavigator: true).pop(params);
if (GoRouter.of(context).canPop()) {
GoRouter.of(context).pop(params);
}
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;

View File

@@ -1,7 +1,8 @@
import 'package:dio/dio.dart';
import 'package:eatvio_app/features/auth/models/credentials_model.dart';
import 'package:eatvio_app/features/auth/models/oauth_model.dart';
import 'package:eatvio_app/features/auth/models/oauth_login_request.dart';
import 'package:eatvio_app/features/auth/models/token_model.dart';
import 'package:eatvio_app/features/auth/models/social_exchange_request.dart';
import 'package:retrofit/retrofit.dart';
part 'auth_service.g.dart';
@@ -11,12 +12,11 @@ abstract class AuthService {
factory AuthService(Dio dio, {String? baseUrl}) = _AuthService;
@POST('/api/login')
Future<TokenModel> getTokenByCredentials({
@Body() required CredentialsModel credentials,
});
Future<TokenModel> getTokenByCredentials({@Body() required CredentialsModel credentials});
@POST('/api/social/login')
Future<TokenModel> getTokenBySocial({
@Body() required SocialExchangeRequest body,
});
@POST('/api/oauth/callback')
Future<Map<String, Object?>> signUpViaSocialMedia({@Body() required OAuthModel body});
@POST('/api/oauth/login')
Future<TokenModel> signInViaSocialMedia({@Body() required OAuthLoginRequest body});
}

View File

@@ -1,6 +1,6 @@
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/enums/complained_content.dart';
import 'package:eatvio_app/core/utils/date_time_utils.dart';
import 'package:eatvio_app/core/widgets/custom_popup.dart';
@@ -207,7 +207,7 @@ class _BlogPostScreenState extends State<BlogPostScreen> {
children: [
CircleAvatar(
radius: 16,
foregroundImage: NetworkImage(baseUrl + (blogPostState.blogPostModel?.author.authorProfileIcon ?? '')),
foregroundImage: NetworkImage(sl<AppConfig>().baseUrl + (blogPostState.blogPostModel?.author.authorProfileIcon ?? '')),
backgroundImage: const AssetImage('assets/images/no_avatar.png'),
),
const SizedBox(width: 8),
@@ -239,7 +239,7 @@ class _BlogPostScreenState extends State<BlogPostScreen> {
),
const SizedBox(height: 8),
if (blogPostState.blogPostModel?.image.isNotEmpty ?? false)
CachedNetworkImage(imageUrl: '$baseUrl/storage/${blogPostState.blogPostModel?.image ?? ''}'),
CachedNetworkImage(imageUrl: '${sl<AppConfig>().baseUrl}/storage/${blogPostState.blogPostModel?.image ?? ''}'),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
@@ -267,7 +267,7 @@ class _BlogPostScreenState extends State<BlogPostScreen> {
final box = context.findRenderObject() as RenderBox?;
SharePlus.instance.share(
ShareParams(
uri: Uri.parse('$baseUrl/ru/blog_post/${widget.id}'),
uri: Uri.parse('${sl<AppConfig>().baseUrl}/ru/blog_post/${widget.id}'),
sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
),
);

View File

@@ -1,7 +1,7 @@
import 'dart:async';
import 'dart:io';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/app_router.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/permission_handler/permission_handler.dart';
import 'package:eatvio_app/core/theme/app_decoration.dart';
import 'package:eatvio_app/core/widgets/show_error_dialog.dart';
@@ -304,7 +304,7 @@ class _BlogPostCreateScreenState extends State<BlogPostCreateScreen> {
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Image(
image: NetworkImage('$baseUrl/storage/${widget.feedBlogPostModel!.image}'),
image: NetworkImage('${sl<AppConfig>().baseUrl}/storage/${widget.feedBlogPostModel!.image}'),
),
),
),

View File

@@ -1,7 +1,8 @@
import 'dart:developer';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:http/http.dart' as http;
import 'package:eatvio_app/core/image_compressing/image_compress_utility.dart';
import 'package:eatvio_app/features/blog_post_create/services/blog_post_service.dart';
@@ -36,7 +37,7 @@ class BlogPostRepository {
Future<XFile?> downloadImage(String imageUrl) async {
try {
// Загрузка изображения
final response = await http.get(Uri.parse('$baseUrl/storage/$imageUrl'));
final response = await http.get(Uri.parse('${sl<AppConfig>().baseUrl}/storage/$imageUrl'));
if (response.statusCode == 200) {
// Получение временной директории

View File

@@ -1,5 +1,6 @@
import 'package:badges/badges.dart' as badges;
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/utils/image_constant.dart';
import 'package:eatvio_app/features/dev_tools/presentation/dev_tools_screen.dart';
import 'package:eatvio_app/features/notifications/presentation/notifications_cubit/notifications_cubit.dart';
@@ -102,7 +103,7 @@ class _BottomNavigationBarWidgetState extends State<BottomNavigationBarWidget> {
label: '',
icon: CircleAvatar(
foregroundImage: NetworkImage(
widget.profileModel.profilePhotoUrl.contains('https') ? widget.profileModel.profilePhotoUrl : baseUrl + widget.profileModel.profilePhotoUrl,
widget.profileModel.profilePhotoUrl.contains('https') ? widget.profileModel.profilePhotoUrl : sl<AppConfig>().baseUrl + widget.profileModel.profilePhotoUrl,
),
backgroundImage: const AssetImage('assets/images/no_avatar.png'),
radius: 16,

View File

@@ -1,6 +1,7 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dismissible_page/dismissible_page.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/app_decoration.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
@@ -88,7 +89,7 @@ class _PhotoViewScreenState extends State<PhotoViewScreen> {
color: Colors.white,
),
title: Text(
widget.imageUrls[index].replaceAll('$baseUrl/storage/chat_files/', ''),
widget.imageUrls[index].replaceAll('${sl<AppConfig>().baseUrl}/storage/chat_files/', ''),
style: const TextStyle(
color: Colors.white,
fontSize: 12,

View File

@@ -1,4 +1,5 @@
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/utils/localization_utils.dart';
@@ -47,7 +48,7 @@ class _OrderCardState extends State<OrderCard> {
ClipRRect(
borderRadius: BorderRadius.circular(12),
child: Image.network(
'$baseUrl/storage/${widget.plan.image}',
'${sl<AppConfig>().baseUrl}/storage/${widget.plan.image}',
width: double.infinity,
fit: BoxFit.cover,
),

View File

@@ -1,4 +1,6 @@
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/features/consultant/become_consultant/presentation/bloc/register_consultant_cubit/register_consultant_cubit.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:flutter/material.dart';
@@ -49,7 +51,7 @@ class _LastStepScreenState extends State<LastStepScreen> {
Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: TextButton(
onPressed: () async => await launchUrl(Uri.parse(hidePlans ? '$baseUrl/docs/privacy.pdf' : '$baseUrl/oferta_bs.pdf')),
onPressed: () async => await launchUrl(Uri.parse(hidePlans ? '${sl<AppConfig>().baseUrl}/docs/privacy.pdf' : '${sl<AppConfig>().baseUrl}/oferta_bs.pdf')),
child: Text(
hidePlans ? 'Политика конфиденциальности и пользовательское соглашение' : 'Договор офёрты',
style: const TextStyle(height: 1, fontSize: 16, color: Color(0xFF323F4B), decoration: TextDecoration.underline),

View File

@@ -2,8 +2,10 @@ import 'dart:convert';
import 'dart:io';
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/image_compressing/image_compress_utility.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/features/create_diet/presentation/cubit/create_diet_state.dart';
import 'package:eatvio_app/features/create_diet/repositories/create_diet_repository.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
@@ -53,7 +55,7 @@ class CreateDietCubit extends Cubit<CreateDietState> {
name: diet.name,
duration: diet.duration,
type: type,
imageUrl: '$baseUrl/storage/${diet.image}',
imageUrl: '${sl<AppConfig>().baseUrl}/storage/${diet.image}',
),
);
emit(state.copyWith(dietState: diet.state, durationIndex: durationValues.indexOf(diet.duration)));

View File

@@ -1,7 +1,8 @@
import 'dart:developer';
import 'dart:io';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/features/create_recipe/entities/recipe_create_entity.dart';
import 'package:eatvio_app/features/create_recipe/models/ingredient.dart' as i;
import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_state.dart';
@@ -187,13 +188,13 @@ class CreateRecipeCubit extends Cubit<CreateRecipeState> {
}
Future<void> recipeToEntity(Recipe recipe) async {
final file = await downloadImageAsFile('$baseUrl/storage/${recipe.image}');
final file = await downloadImageAsFile('${sl<AppConfig>().baseUrl}/storage/${recipe.image}');
final List<StepEntity> steps = await Future.wait(
recipe.steps!.map(
(e) async => StepEntity(
description: e.description,
image: e.image.isEmpty ? null : await downloadImageAsFile('$baseUrl/storage/${e.image}'),
image: e.image.isEmpty ? null : await downloadImageAsFile('${sl<AppConfig>().baseUrl}/storage/${e.image}'),
),
),
);

View File

@@ -1,8 +1,8 @@
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/app_router.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/firebase_api.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/utils/toasts.dart';
@@ -84,7 +84,7 @@ class _DevToolsScreenContentState extends State<DevToolsScreenContent> {
void initState() {
super.initState();
setState(() {
baseUrlForTest = baseUrl;
baseUrlForTest = sl<AppConfig>().baseUrl;
});
testsStates = List.generate(testCases.length, (index) => TestState.notRun);
}
@@ -111,8 +111,8 @@ class _DevToolsScreenContentState extends State<DevToolsScreenContent> {
onPressed: () {
setState(() {
baseUrlForTest = controller.text;
baseUrl = baseUrlForTest.toLowerCase();
sl<Dio>().options.baseUrl = baseUrl;
sl<AppConfig>().setBaseUrl(baseUrlForTest.toLowerCase());
sl<Dio>().options.baseUrl = baseUrlForTest.toLowerCase();
controller.clear();
});
},
@@ -122,23 +122,23 @@ class _DevToolsScreenContentState extends State<DevToolsScreenContent> {
),
const SizedBox(height: 10),
CustomOutlinedButton(
text: baseUrl == EnvConfig.devBaseUrl ? 'Set production base url' : 'Set dev2 base url',
text: sl<AppConfig>().baseUrl == EnvConfig.devBaseUrl ? 'Set production base url' : 'Set dev2 base url',
onPressed: () {
setState(() {
if (baseUrl == EnvConfig.baseUrl) {
if (sl<AppConfig>().baseUrl == EnvConfig.baseUrl) {
baseUrlForTest = EnvConfig.devBaseUrl;
} else {
baseUrlForTest = EnvConfig.baseUrl;
}
baseUrl = baseUrlForTest.toLowerCase();
sl<Dio>().options.baseUrl = baseUrl;
sl<AppConfig>().setBaseUrl(baseUrlForTest.toLowerCase());
sl<Dio>().options.baseUrl = baseUrlForTest.toLowerCase();
controller.clear();
});
},
buttonStyle: const ButtonStyle(),
),
SizedBox(height: baseUrlForTest != baseUrl ? 40 : 10),
if (baseUrl.toLowerCase() != EnvConfig.baseUrl.toLowerCase())
SizedBox(height: baseUrlForTest != sl<AppConfig>().baseUrl ? 40 : 10),
if (sl<AppConfig>().baseUrl.toLowerCase() != EnvConfig.baseUrl.toLowerCase())
ListView.builder(
shrinkWrap: true,
itemCount: testCases.length,

View File

@@ -1,3 +1,4 @@
import 'package:eatvio_app/core/routing/route_constants.dart';
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/widgets/custom_divider.dart';
@@ -6,77 +7,84 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
class ChosenDietWidget extends StatelessWidget {
const ChosenDietWidget({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<DiaryCubit, DiaryState>(builder: (context, state) {
if (state is DiaryStateLoaded) {
if (state.diary.typeOfDiary.hasChosenDiet) {
return ChosenDietWidgetContent(
currentDietDay: state.diary.dayOfChosenDiet ?? 0,
dietName: state.diary.diet?.name ?? '',
dietDuration: state.diary.diet?.duration ?? 0,
);
return BlocBuilder<DiaryCubit, DiaryState>(
builder: (context, state) {
if (state is DiaryStateLoaded) {
if (state.diary.typeOfDiary.hasChosenDiet) {
return ChosenDietWidgetContent(
currentDietDay: state.diary.dayOfChosenDiet ?? 0,
dietName: state.diary.diet?.name ?? '',
dietDuration: state.diary.diet?.duration ?? 0,
dietId: state.diary.diet?.id ?? 0,
);
}
}
}
if (state is DiaryStateLoadedTomorrowWithDiet) {
if (state.diary.typeOfDiary.hasChosenDiet) {
return Column(
children: [
const CustomDivider(),
const SizedBox(height: 16),
ChosenDietWidgetContent(
currentDietDay: state.diary.dayOfChosenDiet ?? 0,
dietName: state.diary.diet?.name ?? '',
dietDuration: state.diary.diet?.duration ?? 0,
),
],
);
if (state is DiaryStateLoadedTomorrowWithDiet) {
if (state.diary.typeOfDiary.hasChosenDiet) {
return Column(
children: [
const CustomDivider(),
const SizedBox(height: 16),
ChosenDietWidgetContent(
currentDietDay: state.diary.dayOfChosenDiet ?? 0,
dietName: state.diary.diet?.name ?? '',
dietDuration: state.diary.diet?.duration ?? 0,
dietId: state.diary.diet?.id ?? 0,
),
],
);
}
}
}
return const SizedBox.shrink();
});
return const SizedBox.shrink();
},
);
}
}
class ChosenDietWidgetContent extends StatelessWidget {
const ChosenDietWidgetContent({
super.key,
required this.currentDietDay,
required this.dietName,
required this.dietDuration,
});
const ChosenDietWidgetContent({super.key, required this.currentDietDay, required this.dietName, required this.dietDuration, required this.dietId});
final int currentDietDay;
final String dietName;
final int dietDuration;
final int dietId;
@override
Widget build(BuildContext context) {
final size = MediaQuery.sizeOf(context);
final s = S.of(context);
return Column(
children: [
Row(
children: [
SizedBox(
width: size.width * 0.4,
child: Text(dietName, style: TextStyles.textLMedium.copyWith(color: appTheme.black)),
),
const Spacer(),
Container(
decoration: BoxDecoration(color: appTheme.dividerColor, borderRadius: BorderRadius.circular(12)),
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 12),
child: Text('${s.day} $currentDietDay из $dietDuration', style: TextStyles.textMSemibold.copyWith(color: appTheme.gray)),
)
],
),
const SizedBox(
height: 16,
)
],
return GestureDetector(
onTap: () {
GoRouter.of(context).push(RouteConstants.aboutDietScreen, extra: {'id': dietId, 'navigateToComments': false});
},
child: Column(
children: [
Row(
children: [
SizedBox(
width: size.width * 0.4,
child: Text(
dietName,
style: TextStyles.textLMedium.copyWith(color: appTheme.black, decoration: TextDecoration.underline),
),
),
const Spacer(),
Container(
decoration: BoxDecoration(color: appTheme.dividerColor, borderRadius: BorderRadius.circular(12)),
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 12),
child: Text('${s.day} $currentDietDay из $dietDuration', style: TextStyles.textMSemibold.copyWith(color: appTheme.gray)),
),
],
),
const SizedBox(height: 16),
],
),
);
}
}

View File

@@ -1,8 +1,9 @@
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/app_router.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/permission_handler/permission_handler.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/features/diary/models/diary_day_model.dart';
@@ -139,7 +140,7 @@ class _PhotoGalleryWidgetState extends State<PhotoGalleryWidget> {
ClipRRect(
borderRadius: BorderRadius.circular(12),
child: CachedNetworkImage(
imageUrl: '$baseUrl/storage/${state.diary.meals[mealIndex].photos[currentSelectedPhotoIndex].path}',
imageUrl: '${sl<AppConfig>().baseUrl}/storage/${state.diary.meals[mealIndex].photos[currentSelectedPhotoIndex].path}',
),
),
if (!state.isConsultantView && !state.isDiaryFinished && !state.isDiaryCommented)
@@ -211,7 +212,7 @@ class _PhotoGalleryWidgetState extends State<PhotoGalleryWidget> {
height: 52,
width: 52,
child: CachedNetworkImage(
imageUrl: '$baseUrl/storage/${state.diary.meals[mealIndex].photos[i].path}',
imageUrl: '${sl<AppConfig>().baseUrl}/storage/${state.diary.meals[mealIndex].photos[i].path}',
fit: BoxFit.fitWidth,
),
),

View File

@@ -19,9 +19,14 @@ class AboutDietCubit extends Cubit<AboutDietState> {
String? userStartedDietName;
List<int> _selectedIndexes = [];
Future<void> getDiet(String slug, {int? index}) async {
Future<void> getDiet({String? slug, int? id, int? index}) async {
try {
final diet = await dietsRepository.getDietBySlug(slug);
final Diet diet;
if (slug != null) {
diet = await dietsRepository.getDietBySlug(slug);
} else {
diet = await dietsRepository.getDiet(id!);
}
if (index != null) {
dietsRepository.emitCommentsStateToFeed(CommentsState(index: index, totalComments: diet.totalComments));
}
@@ -32,10 +37,16 @@ class AboutDietCubit extends Cubit<AboutDietState> {
}
}
Future<void> initDietPage(String slug) async {
Future<void> initDietPage({String? slug, int? id}) async {
try {
emit(const AboutDietState.loading());
final diet = await dietsRepository.getDietBySlug(slug);
final Diet diet;
if (slug != null) {
diet = await dietsRepository.getDietBySlug(slug);
} else {
diet = await dietsRepository.getDiet(id!);
}
final chosenDiets = await profileRepository.getChosenDiets();
final lastChosenDiet = chosenDiets.firstOrNull;
if (lastChosenDiet != null && ['inited', 'started'].contains(lastChosenDiet.state)) {
@@ -50,12 +61,7 @@ class AboutDietCubit extends Cubit<AboutDietState> {
}
}
_selectedIndexes = List.generate(diet.dailySchedule.length, (index) => 0);
emit(AboutDietState.loaded(
diet: diet,
isStarted: isCurrentDietStarted,
hasStartedDiet: hasStartedDiet,
selectedIndexes: _selectedIndexes,
));
emit(AboutDietState.loaded(diet: diet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet, selectedIndexes: _selectedIndexes));
} catch (e) {
log(e.toString());
emit(AboutDietState.error(message: e.toString()));
@@ -68,41 +74,30 @@ class AboutDietCubit extends Cubit<AboutDietState> {
final currentDiet = (state as DietStateLoaded).diet;
if (currentDiet.wasLikedByMe) {
final updatedDiet = currentDiet.copyWith(
totalLikes: currentDiet.totalLikes - 1,
wasLikedByMe: false,
);
final updatedDiet = currentDiet.copyWith(totalLikes: currentDiet.totalLikes - 1, wasLikedByMe: false);
if (dietIndexInFeed != null) {
dietsRepository.emitLikesStateToFeed(LikesState(wasLikedByMe: updatedDiet.wasLikedByMe, totalLikes: updatedDiet.totalLikes, index: dietIndexInFeed));
}
emit(AboutDietState.loaded(diet: updatedDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet, selectedIndexes: _selectedIndexes));
} else {
final updatedDiet = currentDiet.copyWith(
totalLikes: currentDiet.totalLikes + 1,
wasLikedByMe: true,
);
final updatedDiet = currentDiet.copyWith(totalLikes: currentDiet.totalLikes + 1, wasLikedByMe: true);
if (dietIndexInFeed != null) {
dietsRepository.emitLikesStateToFeed(LikesState(wasLikedByMe: updatedDiet.wasLikedByMe, totalLikes: updatedDiet.totalLikes, index: dietIndexInFeed));
}
emit(AboutDietState.loaded(diet: updatedDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet, selectedIndexes: _selectedIndexes));
}
EasyDebounce.debounce(
'like_diet',
const Duration(seconds: 1),
() async {
try {
await dietsRepository.likeDiet(id);
} catch (e) {
log(e.toString());
if (dietIndexInFeed != null) {
dietsRepository
.emitLikesStateToFeed(LikesState(wasLikedByMe: currentDiet.wasLikedByMe, totalLikes: currentDiet.totalLikes, index: dietIndexInFeed));
}
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes,diet: currentDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet));
EasyDebounce.debounce('like_diet', const Duration(seconds: 1), () async {
try {
await dietsRepository.likeDiet(id);
} catch (e) {
log(e.toString());
if (dietIndexInFeed != null) {
dietsRepository.emitLikesStateToFeed(LikesState(wasLikedByMe: currentDiet.wasLikedByMe, totalLikes: currentDiet.totalLikes, index: dietIndexInFeed));
}
},
);
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes, diet: currentDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet));
}
});
}
Future<void> addToFavorite(int id, int? dietIndex) async {
@@ -110,30 +105,24 @@ class AboutDietCubit extends Cubit<AboutDietState> {
final currentDiet = (state as DietStateLoaded).diet;
final updatedDiet = currentDiet.copyWith(
isFavorite: true,
);
final updatedDiet = currentDiet.copyWith(isFavorite: true);
if (dietIndex != null) {
dietsRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: updatedDiet.isFavorite, index: dietIndex));
}
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes,diet: updatedDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet));
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes, diet: updatedDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet));
EasyDebounce.debounce(
'add_or_remove_diet_to_favorites',
const Duration(seconds: 1),
() async {
try {
await dietsRepository.addToFavorite(id);
} catch (e) {
log(e.toString());
showErrorToast('Произошла ошибка. Попробуйте ещё раз через некоторое время');
if (dietIndex != null) {
dietsRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: currentDiet.isFavorite, index: dietIndex));
}
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes,diet: currentDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet));
EasyDebounce.debounce('add_or_remove_diet_to_favorites', const Duration(seconds: 1), () async {
try {
await dietsRepository.addToFavorite(id);
} catch (e) {
log(e.toString());
showErrorToast('Произошла ошибка. Попробуйте ещё раз через некоторое время');
if (dietIndex != null) {
dietsRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: currentDiet.isFavorite, index: dietIndex));
}
},
);
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes, diet: currentDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet));
}
});
}
Future<void> removeFromFavorite(int id, int? dietIndex) async {
@@ -141,30 +130,24 @@ class AboutDietCubit extends Cubit<AboutDietState> {
final currentDiet = (state as DietStateLoaded).diet;
final updatedDiet = currentDiet.copyWith(
isFavorite: false,
);
final updatedDiet = currentDiet.copyWith(isFavorite: false);
if (dietIndex != null) {
dietsRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: updatedDiet.isFavorite, index: dietIndex));
}
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes,diet: updatedDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet));
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes, diet: updatedDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet));
EasyDebounce.debounce(
'add_or_remove_diet_to_favorites',
const Duration(seconds: 1),
() async {
try {
await dietsRepository.removeFromFavorite(id);
} catch (e) {
log(e.toString());
showErrorToast('Произошла ошибка. Попробуйте ещё раз через некоторое время');
if (dietIndex != null) {
dietsRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: currentDiet.isFavorite, index: dietIndex));
}
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes,diet: currentDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet));
EasyDebounce.debounce('add_or_remove_diet_to_favorites', const Duration(seconds: 1), () async {
try {
await dietsRepository.removeFromFavorite(id);
} catch (e) {
log(e.toString());
showErrorToast('Произошла ошибка. Попробуйте ещё раз через некоторое время');
if (dietIndex != null) {
dietsRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: currentDiet.isFavorite, index: dietIndex));
}
},
);
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes, diet: currentDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet));
}
});
}
Future<bool> startDiet(DateTime date) async {
@@ -199,13 +182,13 @@ class AboutDietCubit extends Cubit<AboutDietState> {
void clearStartedDietsState() {
if (state is! DietStateLoaded) return;
final diet = (state as DietStateLoaded).diet;
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes,diet: diet));
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes, diet: diet));
}
void emitCurrentStartedDietsState() {
if (state is! DietStateLoaded) return;
final diet = (state as DietStateLoaded).diet;
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes,diet: diet, isStarted: true));
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes, diet: diet, isStarted: true));
}
Future<Diet?> getDietBySlug(String slug) async {

View File

@@ -1,7 +1,7 @@
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/enums/complained_content.dart';
import 'package:eatvio_app/core/enums/product_type.dart';
import 'package:eatvio_app/core/utils/localization_utils.dart';
@@ -35,11 +35,12 @@ import 'package:flutter_svg/svg.dart';
import 'package:go_router/go_router.dart';
class AboutDietScreen extends StatefulWidget {
final String slug;
final String? slug;
final int? id;
final int? index;
final bool navigateToComments;
const AboutDietScreen({super.key, required this.index, required this.navigateToComments, required this.slug});
const AboutDietScreen({super.key, required this.index, required this.navigateToComments, required this.slug, required this.id});
@override
State<AboutDietScreen> createState() => _AboutDietScreenState();
@@ -79,7 +80,7 @@ class _AboutDietScreenState extends State<AboutDietScreen> {
final s = S.of(context);
return BlocProvider(
create: (context) => dietsCubit..initDietPage(widget.slug),
create: (context) => dietsCubit..initDietPage(slug: widget.slug, id: widget.id),
child: BlocProvider<CommentsCubit>(
create: (BuildContext context) => commentsCubit,
child: BlocConsumer<CommentsCubit, CommentsState>(
@@ -283,7 +284,7 @@ class _AboutDietScreenState extends State<AboutDietScreen> {
replyId = null;
});
Future.delayed(const Duration(milliseconds: 500), () {
dietsCubit.getDiet(dietState.diet.slug, index: widget.index);
dietsCubit.getDiet(slug: dietState.diet.slug, index: widget.index);
});
FocusManager.instance.primaryFocus?.unfocus();
}
@@ -353,7 +354,7 @@ class _AboutDietScreenState extends State<AboutDietScreen> {
Stack(
children: [
CachedNetworkImage(
imageUrl: '$baseUrl/storage/${dietState.diet.image}',
imageUrl: '${sl<AppConfig>().baseUrl}/storage/${dietState.diet.image}',
height: 300,
width: MediaQuery.sizeOf(context).width,
fit: BoxFit.fill,
@@ -526,7 +527,7 @@ class _AboutDietScreenState extends State<AboutDietScreen> {
),
),
body: DataErrorWidget(
onReload: () => context.read<AboutDietCubit>().getDiet(widget.slug, index: widget.index),
onReload: () => context.read<AboutDietCubit>().getDiet(slug: widget.slug, id: widget.id, index: widget.index),
),
);
}

View File

@@ -1,4 +1,5 @@
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/features/diets/presentation/widgets/info_bouble.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/core/theme/custom_text_style.dart';
@@ -37,45 +38,25 @@ class AuthorCard extends StatelessWidget {
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: NetworkImage(baseUrl + author.authorProfileIcon),
image: NetworkImage(
author.authorProfileIcon.contains('https') ? author.authorProfileIcon : sl<AppConfig>().baseUrl + author.authorProfileIcon,
),
fit: BoxFit.cover,
),
),
),
subtitle: Text(
author.authorName,
style: TextStyles.textLSemibold.copyWith(
color: appTheme.black,
),
),
title: Text(
title,
style: titleStyle ?? TextStyles.textSSemibold.copyWith(
color: appTheme.gray,
),
),
subtitle: Text(author.authorName, style: TextStyles.textLSemibold.copyWith(color: appTheme.black)),
title: Text(title, style: titleStyle ?? TextStyles.textSSemibold.copyWith(color: appTheme.gray)),
),
Row(
children: [
Text(
'Консультант',
style: TextStyles.textMMedium.copyWith(
color: appTheme.black,
),
),
Text('Консультант', style: TextStyles.textMMedium.copyWith(color: appTheme.black)),
const SizedBox(width: 10),
if (author.authorPlaceInRating != null)
InfoBouble(
radius: 12,
backgroundColor: appTheme.whiteA700,
children: [
Text(
'${author.authorPlaceInRating}-й в рейтинге',
style: TextStyles.textMMediumAuto.copyWith(
color: appTheme.blueA400,
),
),
],
children: [Text('${author.authorPlaceInRating}-й в рейтинге', style: TextStyles.textMMediumAuto.copyWith(color: appTheme.blueA400))],
),
],
),
@@ -88,18 +69,8 @@ class AuthorCard extends StatelessWidget {
child: Container(
width: 28,
height: 28,
decoration: BoxDecoration(
color: appTheme.whiteA700,
borderRadius: BorderRadius.circular(8),
),
child: Center(
child: SvgPicture.asset(
'assets/icons/arrow.svg',
width: 12,
height: 12,
fit: BoxFit.none,
),
),
decoration: BoxDecoration(color: appTheme.whiteA700, borderRadius: BorderRadius.circular(8)),
child: Center(child: SvgPicture.asset('assets/icons/arrow.svg', width: 12, height: 12, fit: BoxFit.none)),
),
),
],

View File

@@ -1,5 +1,6 @@
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/enums/complained_content.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/utils/toasts.dart';
import 'package:eatvio_app/features/complaining/presentation/complaining_bottom_sheet.dart';
import 'package:eatvio_app/core/widgets/custom_divider.dart';
@@ -35,7 +36,7 @@ class MoreOptions extends StatelessWidget {
onTap: disableActions == true
? null
: () {
Clipboard.setData(ClipboardData(text: '$baseUrl/ru/$path'));
Clipboard.setData(ClipboardData(text: '${sl<AppConfig>().baseUrl}/ru/$path'));
showInfoToast(s.link_was_copied);
},
child: Row(
@@ -62,7 +63,7 @@ class MoreOptions extends StatelessWidget {
final box = context.findRenderObject() as RenderBox?;
SharePlus.instance.share(
ShareParams(
uri: Uri.parse('$baseUrl/ru/$path',),
uri: Uri.parse('${sl<AppConfig>().baseUrl}/ru/$path',),
sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
),
);

View File

@@ -1,7 +1,8 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dismissible_page/dismissible_page.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/enums/complained_content.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/utils/date_time_utils.dart';
import 'package:eatvio_app/core/widgets/custom_popup.dart';
@@ -64,7 +65,7 @@ class _BlogPostWidgetState extends State<BlogPostWidget> {
authorName: state.feedBlogPostList[widget.index].author.authorName,
authorProfileIcon: state.feedBlogPostList[widget.index].author.authorProfileIcon.contains('https')
? state.feedBlogPostList[widget.index].author.authorProfileIcon
: baseUrl + state.feedBlogPostList[widget.index].author.authorProfileIcon,
: sl<AppConfig>().baseUrl + state.feedBlogPostList[widget.index].author.authorProfileIcon,
authorIsMe: state.feedBlogPostList[widget.index].author.authorIsMe,
),
);
@@ -75,7 +76,7 @@ class _BlogPostWidgetState extends State<BlogPostWidget> {
foregroundImage: NetworkImage(
state.feedBlogPostList[widget.index].author.authorProfileIcon.contains('https')
? state.feedBlogPostList[widget.index].author.authorProfileIcon
: baseUrl + state.feedBlogPostList[widget.index].author.authorProfileIcon,
: sl<AppConfig>().baseUrl + state.feedBlogPostList[widget.index].author.authorProfileIcon,
),
backgroundImage: const AssetImage('assets/images/no_avatar.png'),
),
@@ -157,15 +158,15 @@ class _BlogPostWidgetState extends State<BlogPostWidget> {
onTap: () {
context.pushTransparentRoute(
rootNavigator: true,
PhotoViewScreen(imageUrls: ['$baseUrl/storage/${state.feedBlogPostList[widget.index].image}'], index: 0),
PhotoViewScreen(imageUrls: ['${sl<AppConfig>().baseUrl}/storage/${state.feedBlogPostList[widget.index].image}'], index: 0),
);
},
child: Hero(
tag: '$baseUrl/storage/${state.feedBlogPostList[widget.index].image}',
tag: '${sl<AppConfig>().baseUrl}/storage/${state.feedBlogPostList[widget.index].image}',
child: CachedNetworkImage(
fit: BoxFit.fitWidth,
width: MediaQuery.of(context).size.width,
imageUrl: '$baseUrl/storage/${state.feedBlogPostList[widget.index].image}',
imageUrl: '${sl<AppConfig>().baseUrl}/storage/${state.feedBlogPostList[widget.index].image}',
errorWidget: (context, str, object) => const SizedBox.shrink(),
),
),
@@ -219,7 +220,7 @@ class _BlogPostWidgetState extends State<BlogPostWidget> {
final box = context.findRenderObject() as RenderBox?;
SharePlus.instance.share(
ShareParams(
uri: Uri.parse('$baseUrl/ru/blog_post/${state.feedBlogPostList[widget.index].id}'),
uri: Uri.parse('${sl<AppConfig>().baseUrl}/ru/blog_post/${state.feedBlogPostList[widget.index].id}'),
sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
),
);

View File

@@ -1,5 +1,5 @@
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/comments/presentation/comments_actions_bottom_sheet.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/enums/complained_content.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/utils/date_time_utils.dart';
@@ -99,13 +99,13 @@ class _CommentsWidgetState extends State<CommentsWidget> {
extra: Author(
authorSlug: comment.authorSlug,
authorName: comment.authorName,
authorProfileIcon: comment.authorProfileIcon.contains('https') ? comment.authorProfileIcon : baseUrl + comment.authorProfileIcon,
authorProfileIcon: comment.authorProfileIcon.contains('https') ? comment.authorProfileIcon : sl<AppConfig>().baseUrl + comment.authorProfileIcon,
authorIsMe: isMe,
),
);
},
child: CircleAvatar(
foregroundImage: NetworkImage(comment.authorProfileIcon.contains('https') ? comment.authorProfileIcon : baseUrl + comment.authorProfileIcon),
foregroundImage: NetworkImage(comment.authorProfileIcon.contains('https') ? comment.authorProfileIcon : sl<AppConfig>().baseUrl + comment.authorProfileIcon),
backgroundImage: const AssetImage('assets/images/no_avatar.png'),
radius: radius,
),

View File

@@ -1,5 +1,5 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
@@ -14,10 +14,7 @@ import 'package:go_router/go_router.dart';
class ConsultantWidget extends StatelessWidget {
final FeedConsultantModel consultant;
const ConsultantWidget({
super.key,
required this.consultant,
});
const ConsultantWidget({super.key, required this.consultant});
@override
Widget build(BuildContext context) {
@@ -36,10 +33,7 @@ class ConsultantWidget extends StatelessWidget {
borderRadius: BorderRadius.circular(20),
child: Ink(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color(0xFFF6F6F6),
),
decoration: BoxDecoration(borderRadius: BorderRadius.circular(20), color: const Color(0xFFF6F6F6)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@@ -51,46 +45,32 @@ class ConsultantWidget extends StatelessWidget {
children: [
Ink(
padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
),
decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(8)),
child: Text(
'${consultant.ratingPlace}',
style: TextStyle(
fontSize: 20,
color: appTheme.blueA400,
fontWeight: FontWeight.w600,
),
style: TextStyle(fontSize: 20, color: appTheme.blueA400, fontWeight: FontWeight.w600),
),
),
const SizedBox(width: 8),
CircleAvatar(
foregroundImage: NetworkImage(baseUrl + consultant.photo),
backgroundImage: const AssetImage('assets/images/no_avatar.png'),
),
if (consultant.photo.contains('https'))
CircleAvatar(foregroundImage: NetworkImage(consultant.photo), backgroundImage: const AssetImage('assets/images/no_avatar.png'))
else
CircleAvatar(
foregroundImage: NetworkImage(sl<AppConfig>().baseUrl + consultant.photo),
backgroundImage: const AssetImage('assets/images/no_avatar.png'),
),
const SizedBox(width: 8),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
consultant.name,
style: const TextStyle(
height: 1,
fontWeight: FontWeight.w500,
fontSize: 15,
color: Color(0xFF323F4B),
),
style: const TextStyle(height: 1, fontWeight: FontWeight.w500, fontSize: 15, color: Color(0xFF323F4B)),
),
const SizedBox(height: 4),
Text(
'Рейтинг: ${consultant.totalScores}',
style: TextStyle(
color: appTheme.blueA400,
height: 1,
fontWeight: FontWeight.w500,
fontSize: 12,
),
style: TextStyle(color: appTheme.blueA400, height: 1, fontWeight: FontWeight.w500, fontSize: 12),
),
],
),
@@ -98,21 +78,13 @@ class ConsultantWidget extends StatelessWidget {
),
Ink(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
color: Colors.white,
),
child: SvgPicture.asset(
'assets/icons/go_to_arrow.svg',
),
decoration: BoxDecoration(borderRadius: BorderRadius.circular(4), color: Colors.white),
child: SvgPicture.asset('assets/icons/go_to_arrow.svg'),
),
],
),
const SizedBox(height: 8),
Text(
consultant.description,
maxLines: 2,
),
Text(consultant.description, maxLines: 2),
if (consultant.badges.isNotEmpty) const SizedBox(height: 8),
_badges(consultant.badges, context),
],
@@ -128,16 +100,8 @@ class ConsultantWidget extends StatelessWidget {
children: [
for (int i = 0; i < badges.length; i++) ...[
badges[i].image.contains('svg')
? SvgPicture.network(
'$baseUrl/storage/${badges[i].image}',
width: 28,
height: 28,
)
: CachedNetworkImage(
imageUrl: '$baseUrl/storage/${badges[i].image}',
width: 28,
height: 28,
),
? SvgPicture.network('${sl<AppConfig>().baseUrl}/storage/${badges[i].image}', width: 28, height: 28)
: CachedNetworkImage(imageUrl: '${sl<AppConfig>().baseUrl}/storage/${badges[i].image}', width: 28, height: 28),
i < badges.length - 1 ? const SizedBox(width: 8) : const SizedBox.shrink(),
],
],

View File

@@ -1,7 +1,8 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/enums/complained_content.dart';
import 'package:eatvio_app/core/enums/product_type.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/widgets/bookmark_button.dart';
import 'package:eatvio_app/core/widgets/custom_popup.dart';
import 'package:eatvio_app/core/widgets/info_row.dart';
@@ -56,7 +57,7 @@ class _DietsWidgetState extends State<DietsWidget> {
ClipRRect(
borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
child: CachedNetworkImage(
imageUrl: '$baseUrl/storage/${widget.diet.image}',
imageUrl: '${sl<AppConfig>().baseUrl}/storage/${widget.diet.image}',
fit: BoxFit.fitWidth,
width: MediaQuery.of(context).size.width,
),
@@ -189,7 +190,7 @@ class _DietsWidgetState extends State<DietsWidget> {
final box = context.findRenderObject() as RenderBox?;
final result = await SharePlus.instance.share(
ShareParams(
uri: Uri.parse('$baseUrl/ru/diet/${widget.diet.id}'),
uri: Uri.parse('${sl<AppConfig>().baseUrl}/ru/diet/${widget.diet.id}'),
sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
),
);

View File

@@ -1,7 +1,8 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/enums/complained_content.dart';
import 'package:eatvio_app/core/enums/product_type.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/widgets/bookmark_button.dart';
import 'package:eatvio_app/core/widgets/custom_popup.dart';
import 'package:eatvio_app/core/widgets/info_row.dart';
@@ -61,7 +62,7 @@ class _PlanWidgetState extends State<PlanWidget> {
ClipRRect(
borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
child: CachedNetworkImage(
imageUrl: '$baseUrl/storage/${widget.plan.image}',
imageUrl: '${sl<AppConfig>().baseUrl}/storage/${widget.plan.image}',
fit: BoxFit.cover,
width: MediaQuery.of(context).size.width,
height: 426,
@@ -187,7 +188,7 @@ class _PlanWidgetState extends State<PlanWidget> {
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: NetworkImage(baseUrl + widget.plan.author.authorProfileIcon),
image: NetworkImage(sl<AppConfig>().baseUrl + widget.plan.author.authorProfileIcon),
fit: BoxFit.cover,
),
),
@@ -263,7 +264,7 @@ class _PlanWidgetState extends State<PlanWidget> {
final box = context.findRenderObject() as RenderBox?;
final result = await SharePlus.instance.share(
ShareParams(
uri: Uri.parse('$baseUrl/ru/diet/${widget.plan.id}'),
uri: Uri.parse('${sl<AppConfig>().baseUrl}/ru/diet/${widget.plan.id}'),
sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
),
);

View File

@@ -1,8 +1,9 @@
// ignore_for_file: dead_code
import 'package:cached_network_image/cached_network_image.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/enums/complained_content.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/utils/localization_utils.dart';
import 'package:eatvio_app/core/widgets/bookmark_button.dart';
@@ -75,7 +76,7 @@ class _RecipesWidgetState extends State<RecipesWidget> {
ClipRRect(
borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
child: CachedNetworkImage(
imageUrl: '$baseUrl/storage/${widget.recipe.image}',
imageUrl: '${sl<AppConfig>().baseUrl}/storage/${widget.recipe.image}',
fit: BoxFit.fitWidth,
width: MediaQuery.of(context).size.width,
),
@@ -231,7 +232,7 @@ class _RecipesWidgetState extends State<RecipesWidget> {
final box = context.findRenderObject() as RenderBox?;
SharePlus.instance.share(
ShareParams(
uri: Uri.parse('$baseUrl/ru/recipe/${widget.recipe.id}'),
uri: Uri.parse('${sl<AppConfig>().baseUrl}/ru/recipe/${widget.recipe.id}'),
sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
),
);

View File

@@ -1,10 +1,11 @@
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class GlossaryScreen extends StatefulWidget {
const GlossaryScreen({super.key});
const GlossaryScreen({super.key, required this.passKey});
final String passKey;
@override
State<GlossaryScreen> createState() => _GlossaryScreenState();
}
@@ -18,15 +19,13 @@ class _GlossaryScreenState extends State<GlossaryScreen> {
_controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..loadRequest(Uri.parse('$baseUrl/product_nutritional_value'));
..loadRequest(Uri.parse('${sl<AppConfig>().baseUrl}/login_with_pass_key?id=${widget.passKey}'));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Глоссарий'),
),
appBar: AppBar(title: const Text('Глоссарий')),
body: WebViewWidget(controller: _controller),
);
}

View File

@@ -0,0 +1,20 @@
import 'dart:developer';
import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_state.dart';
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class MenuCubit extends Cubit<MenuState> {
final ProfileRepository profileRepository;
MenuCubit(this.profileRepository) : super(MenuState());
Future<String?> makePassKey() async {
try {
final passKey = await profileRepository.getPassKey(routeName: 'product_nutritional_value.index', routeParams: {});
return passKey;
} catch (e) {
log(e.toString());
}
return null;
}
}

View File

@@ -0,0 +1 @@
class MenuState {}

View File

@@ -1,4 +1,5 @@
import 'package:dio/dio.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/token_storage.dart';
@@ -9,12 +10,14 @@ import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/features/consultant_rating/presentation/consultant_rating_screen.dart';
import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/consultant_finances_screen.dart';
import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/user_purchases_screen.dart';
import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_cubit.dart';
import 'package:eatvio_app/features/my_diets/presentation/my_diets_screen.dart';
import 'package:eatvio_app/features/my_plans/presentation/my_plans_screen.dart';
import 'package:eatvio_app/features/profile/models/profile_model.dart';
import 'package:eatvio_app/features/recipe/presentation/pages/my_recipes_screen.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:go_router/go_router.dart';
import 'package:package_info_plus/package_info_plus.dart';
@@ -26,66 +29,86 @@ class MenuScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(centerTitle: false, title: const Text('Меню')),
body: SingleChildScrollView(
child: Column(
children: [
_tile(title: 'Настройки профиля', leading: ImageConstant.icnProfileSettings, onTap: () => GoRouter.of(context).push('/settings-screen')),
if (profileModel.roles.contains('consultant')) _divider(context),
if (profileModel.roles.contains('consultant'))
_tile(leading: ImageConstant.icnRecipes, title: 'Мои рецепты', onTap: () => GoRouter.of(context).push(MyRecipesScreen.path)),
if (profileModel.roles.contains('consultant')) _divider(context),
if (profileModel.roles.contains('consultant'))
_tile(leading: 'assets/icons/diets.svg', title: 'Мои диеты', onTap: () => GoRouter.of(context).push(MyDietsScreen.path)),
if (profileModel.roles.contains('consultant')) _divider(context),
if (profileModel.roles.contains('consultant'))
_tile(leading: ImageConstant.icnPlans, title: 'Мои планы', onTap: () => GoRouter.of(context).push(MyPlansScreen.path)),
if (!hidePlans) ...[
_divider(context),
_tile(
leading: 'assets/icons/finance.svg',
title: 'Мои финансы',
onTap: () {
if (profileModel.roles.contains('consultant')) {
GoRouter.of(context).push(ConsultantFinancesScreen.path);
return;
}
GoRouter.of(context).push(UserPurchasesScreen.path);
},
return BlocProvider(
create: (context) => sl<MenuCubit>(),
child: Builder(
builder: (context) {
return Scaffold(
appBar: AppBar(centerTitle: false, title: const Text('Меню')),
body: SingleChildScrollView(
child: Column(
children: [
_tile(title: 'Настройки профиля', leading: ImageConstant.icnProfileSettings, onTap: () => GoRouter.of(context).push('/settings-screen')),
if (profileModel.roles.contains('consultant')) _divider(context),
if (profileModel.roles.contains('consultant'))
_tile(leading: ImageConstant.icnRecipes, title: 'Мои рецепты', onTap: () => GoRouter.of(context).push(MyRecipesScreen.path)),
if (profileModel.roles.contains('consultant')) _divider(context),
if (profileModel.roles.contains('consultant'))
_tile(leading: 'assets/icons/diets.svg', title: 'Мои диеты', onTap: () => GoRouter.of(context).push(MyDietsScreen.path)),
if (profileModel.roles.contains('consultant')) _divider(context),
if (profileModel.roles.contains('consultant'))
_tile(leading: ImageConstant.icnPlans, title: 'Мои планы', onTap: () => GoRouter.of(context).push(MyPlansScreen.path)),
if (!hidePlans) ...[
_divider(context),
_tile(
leading: 'assets/icons/finance.svg',
title: 'Мои финансы',
onTap: () {
if (profileModel.roles.contains('consultant')) {
GoRouter.of(context).push(ConsultantFinancesScreen.path);
return;
}
GoRouter.of(context).push(UserPurchasesScreen.path);
},
),
],
if (profileModel.roles.contains('consultant')) _divider(context),
if (profileModel.roles.contains('consultant'))
_tile(
leading: 'assets/icons/consultant_rating_icon.svg',
title: 'Мой рейтинг',
onTap: () {
GoRouter.of(context).push(ConsultantRatingScreen.path);
},
),
_divider(context),
_tile(
leading: ImageConstant.icnGlossary,
title: 'Глоссарий',
onTap: () async {
final passKey = await context.read<MenuCubit>().makePassKey();
if (passKey != null && context.mounted) {
GoRouter.of(context).push('/glossary-screen', extra: passKey);
}
},
),
_divider(context),
_tile(
leading: 'assets/icons/notifications.svg',
title: 'Уведомления',
onTap: () => GoRouter.of(context).pushNamed('notificationsSettingsScreen'),
),
_divider(context),
_tile(leading: ImageConstant.icnSupport, title: 'Поддержка', onTap: () => GoRouter.of(context).push('/support-screen')),
_divider(context),
_tile(leading: 'assets/icons/blocked_users.svg', title: 'Чёрный список', onTap: () => GoRouter.of(context).pushNamed('blockedUsersScreen')),
// _divider(context),
// _tile(
// leading: ImageConstant.icnDevTools,
// title: 'Для разработчиков',
// onTap: () {
// GoRouter.of(context).pushNamed(DevToolsScreen.name);
// },
// ),
_divider(context),
_tile(leading: ImageConstant.icnExit, title: 'Выход', onTap: _onTapLogout(context)),
const SizedBox(height: 10),
const AppInfo(),
],
),
],
if (profileModel.roles.contains('consultant')) _divider(context),
if (profileModel.roles.contains('consultant'))
_tile(
leading: 'assets/icons/consultant_rating_icon.svg',
title: 'Мой рейтинг',
onTap: () {
GoRouter.of(context).push(ConsultantRatingScreen.path);
},
),
_divider(context),
_tile(leading: ImageConstant.icnGlossary, title: 'Глоссарий', onTap: () => GoRouter.of(context).push('/glossary-screen')),
_divider(context),
_tile(leading: 'assets/icons/notifications.svg', title: 'Уведомления', onTap: () => GoRouter.of(context).pushNamed('notificationsSettingsScreen')),
_divider(context),
_tile(leading: ImageConstant.icnSupport, title: 'Поддержка', onTap: () => GoRouter.of(context).push('/support-screen')),
_divider(context),
_tile(leading: 'assets/icons/blocked_users.svg', title: 'Чёрный список', onTap: () => GoRouter.of(context).pushNamed('blockedUsersScreen')),
// _divider(context),
// _tile(
// leading: ImageConstant.icnDevTools,
// title: 'Для разработчиков',
// onTap: () {
// GoRouter.of(context).pushNamed(DevToolsScreen.name);
// },
// ),
_divider(context),
_tile(leading: ImageConstant.icnExit, title: 'Выход', onTap: _onTapLogout(context)),
const SizedBox(height: 10),
const AppInfo(),
],
),
),
);
},
),
);
}
@@ -117,7 +140,7 @@ class MenuScreen extends StatelessWidget {
CupertinoDialogAction(
onPressed: () async {
try {
await sl<Dio>().post('$baseUrl/api/profile/logout');
await sl<Dio>().post('${sl<AppConfig>().baseUrl}/api/profile/logout');
} finally {
await TokenStorage.removeTokenInStorage();
if (context.mounted) {

View File

@@ -1,4 +1,5 @@
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked_users_cubit.dart';
import 'package:eatvio_app/features/profile/models/profile_model.dart';
@@ -33,7 +34,7 @@ class _BlockedUserWidgetState extends State<BlockedUserWidget> {
child: Row(
children: [
CircleAvatar(
foregroundImage: NetworkImage(baseUrl + widget.profile.profilePhotoUrl),
foregroundImage: NetworkImage(sl<AppConfig>().baseUrl + widget.profile.profilePhotoUrl),
backgroundImage: const AssetImage('assets/images/no_avatar.png'),
radius: 28,
),

View File

@@ -1,6 +1,7 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/app_router.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/enums/product_type.dart';
@@ -56,7 +57,7 @@ class _MyDietWidgetState extends State<MyDietWidget> {
child: ClipRRect(
borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
child: CachedNetworkImage(
imageUrl: '$baseUrl/storage/${widget.diet.image}',
imageUrl: '${sl<AppConfig>().baseUrl}/storage/${widget.diet.image}',
fit: BoxFit.fitWidth,
width: MediaQuery.of(context).size.width,
),
@@ -153,7 +154,7 @@ class _MyDietWidgetState extends State<MyDietWidget> {
final box = context.findRenderObject() as RenderBox?;
await SharePlus.instance.share(
ShareParams(
uri: Uri.parse('$baseUrl/ru/diet/${widget.diet.id}'),
uri: Uri.parse('${sl<AppConfig>().baseUrl}/ru/diet/${widget.diet.id}'),
sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
),
);

View File

@@ -1,5 +1,6 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/enums/product_type.dart';
@@ -42,7 +43,7 @@ class _MyPlanWidgetState extends State<MyPlanWidget> {
onTap: () => GoRouter.of(context).pushNamed('aboutPlanScreen', extra: {'slug': widget.plan.slug, 'navigateToComments': false}),
child: ClipRRect(
borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
child: CachedNetworkImage(imageUrl: '$baseUrl/storage/${widget.plan.image}', fit: BoxFit.fitWidth, width: MediaQuery.of(context).size.width),
child: CachedNetworkImage(imageUrl: '${sl<AppConfig>().baseUrl}/storage/${widget.plan.image}', fit: BoxFit.fitWidth, width: MediaQuery.of(context).size.width),
),
),
Positioned(
@@ -157,7 +158,7 @@ class _MyPlanWidgetState extends State<MyPlanWidget> {
final box = context.findRenderObject() as RenderBox?;
await SharePlus.instance.share(
ShareParams(
uri: Uri.parse('$baseUrl/ru/plan/${widget.plan.id}'),
uri: Uri.parse('${sl<AppConfig>().baseUrl}/ru/plan/${widget.plan.id}'),
sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
),
);

View File

@@ -1,5 +1,6 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/widgets/main_background_bouble.dart';
@@ -31,7 +32,7 @@ class PlanInfo extends StatelessWidget {
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: CachedNetworkImage(
imageUrl: '$baseUrl/storage/$imagePath',
imageUrl: '${sl<AppConfig>().baseUrl}/storage/$imagePath',
height: 220,
width: MediaQuery.sizeOf(context).width,
fit: BoxFit.fill,

View File

@@ -1,7 +1,7 @@
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/enums/complained_content.dart';
import 'package:eatvio_app/core/enums/product_type.dart';
import 'package:eatvio_app/core/utils/localization_utils.dart';
@@ -401,7 +401,7 @@ class _AboutPlanScreenState extends State<AboutPlanScreen> {
Stack(
children: [
CachedNetworkImage(
imageUrl: '$baseUrl/storage/${state.planModel?.image}',
imageUrl: '${sl<AppConfig>().baseUrl}/storage/${state.planModel?.image}',
height: 300,
width: MediaQuery.sizeOf(context).width,
fit: BoxFit.fill,

View File

@@ -0,0 +1,15 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'pass_key_params.freezed.dart';
part 'pass_key_params.g.dart';
@freezed
abstract class PassKeyParams with _$PassKeyParams {
factory PassKeyParams({
@JsonKey(name: 'route_name') required String routeName,
@JsonKey(name: 'route_params') Map<String, dynamic>? routeParams,
}) = _PassKeyParams;
factory PassKeyParams.fromJson(Map<String, dynamic> json) => _$PassKeyParamsFromJson(json);
}

View File

@@ -1,6 +1,7 @@
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dismissible_page/dismissible_page.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/app_router.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/enums/complained_content.dart';
@@ -655,7 +656,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
borderRadius: BorderRadius.circular(4),
boxShadow: [BoxShadow(color: Colors.black.withAlpha((255 * 0.2).toInt()), blurRadius: 32)],
),
child: SvgPicture.network('$baseUrl/storage/${state.profile.badges[i].image}', width: 40, height: 40),
child: SvgPicture.network('${sl<AppConfig>().baseUrl}/storage/${state.profile.badges[i].image}', width: 40, height: 40),
)
: Tooltip(
message: state.profile.badges[i].description,
@@ -667,7 +668,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
borderRadius: BorderRadius.circular(4),
boxShadow: [BoxShadow(color: Colors.black.withAlpha((255 * 0.2).toInt()), blurRadius: 32)],
),
child: CachedNetworkImage(imageUrl: '$baseUrl/storage/${state.profile.badges[i].image}', width: 40, height: 40),
child: CachedNetworkImage(imageUrl: '${sl<AppConfig>().baseUrl}/storage/${state.profile.badges[i].image}', width: 40, height: 40),
),
i < state.profile.badges.length - 1 ? const SizedBox(width: 8) : const SizedBox.shrink(),
],
@@ -803,7 +804,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
icon: 'assets/icons/eye.svg',
text: 'Посмотреть',
onTap: () async {
context.pushTransparentRoute(rootNavigator: true, PhotoViewScreen(imageUrls: [baseUrl + state.profile.profilePhotoUrl], index: 0));
context.pushTransparentRoute(rootNavigator: true, PhotoViewScreen(imageUrls: [sl<AppConfig>().baseUrl + state.profile.profilePhotoUrl], index: 0));
},
),
if (widget.author == null || widget.author!.authorIsMe) ...[
@@ -885,7 +886,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
child: CircleAvatar(
radius: 32,
foregroundImage: NetworkImage(
state.profile.profilePhotoUrl.contains('https') ? state.profile.profilePhotoUrl : baseUrl + state.profile.profilePhotoUrl,
state.profile.profilePhotoUrl.contains('https') ? state.profile.profilePhotoUrl : sl<AppConfig>().baseUrl + state.profile.profilePhotoUrl,
),
backgroundImage: const AssetImage('assets/images/no_avatar.png'),
),
@@ -960,7 +961,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
onTap: () {
final box = context.findRenderObject() as RenderBox?;
SharePlus.instance.share(
ShareParams(uri: Uri.parse('$baseUrl/ru/profile/${state.profile.slug}'), sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size),
ShareParams(uri: Uri.parse('${sl<AppConfig>().baseUrl}/ru/profile/${state.profile.slug}'), sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size),
);
},
),

View File

@@ -1,7 +1,8 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dismissible_page/dismissible_page.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/enums/complained_content.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/utils/date_time_utils.dart';
import 'package:eatvio_app/core/widgets/custom_popup.dart';
import 'package:eatvio_app/core/widgets/feed_icon_button.dart';
@@ -69,7 +70,7 @@ class _ProfileBlogPostWidgetState extends State<ProfileBlogPostWidget> {
foregroundImage: NetworkImage(
state.blogPosts[widget.index].author.authorProfileIcon.contains('https')
? state.blogPosts[widget.index].author.authorProfileIcon
: baseUrl + state.blogPosts[widget.index].author.authorProfileIcon,
: sl<AppConfig>().baseUrl + state.blogPosts[widget.index].author.authorProfileIcon,
),
backgroundImage: const AssetImage('assets/images/no_avatar.png'),
),
@@ -157,17 +158,17 @@ class _ProfileBlogPostWidgetState extends State<ProfileBlogPostWidget> {
context.pushTransparentRoute(
rootNavigator: true,
PhotoViewScreen(
imageUrls: ['$baseUrl/storage/${state.blogPosts[widget.index].image}'],
imageUrls: ['${sl<AppConfig>().baseUrl}/storage/${state.blogPosts[widget.index].image}'],
index: 0,
),
);
},
child: Hero(
tag: '$baseUrl/storage/${state.blogPosts[widget.index].image}',
tag: '${sl<AppConfig>().baseUrl}/storage/${state.blogPosts[widget.index].image}',
child: CachedNetworkImage(
fit: BoxFit.fitWidth,
width: MediaQuery.of(context).size.width,
imageUrl: '$baseUrl/storage/${state.blogPosts[widget.index].image}',
imageUrl: '${sl<AppConfig>().baseUrl}/storage/${state.blogPosts[widget.index].image}',
errorWidget: (context, str, object) => const SizedBox.shrink(),
),
),
@@ -226,7 +227,7 @@ class _ProfileBlogPostWidgetState extends State<ProfileBlogPostWidget> {
final box = context.findRenderObject() as RenderBox?;
SharePlus.instance.share(
ShareParams(
uri: Uri.parse('$baseUrl/ru/blog_post/${state.blogPosts[widget.index].id}'),
uri: Uri.parse('${sl<AppConfig>().baseUrl}/ru/blog_post/${state.blogPosts[widget.index].id}'),
sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
),
);

View File

@@ -1,4 +1,5 @@
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/features/profile/models/sub_model.dart';
import 'package:eatvio_app/features/profile/presentation/widgets/sub_action_button_widget.dart';
@@ -36,7 +37,7 @@ class _SubWidgetState extends State<SubWidget> {
child: Row(
children: [
CircleAvatar(
foregroundImage: NetworkImage(baseUrl + widget.subModel.profilePhotoUrl),
foregroundImage: NetworkImage(sl<AppConfig>().baseUrl + widget.subModel.profilePhotoUrl),
backgroundImage: const AssetImage('assets/images/no_avatar.png'),
radius: 28,
),

View File

@@ -4,6 +4,7 @@ import 'dart:io';
import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart';
import 'package:eatvio_app/features/profile/models/chosen_diets_pagination_model.dart';
import 'package:eatvio_app/features/profile/models/circumference_model.dart';
import 'package:eatvio_app/features/profile/models/pass_key_params.dart';
import 'package:eatvio_app/features/profile/models/profile_model.dart';
import 'package:eatvio_app/features/profile/models/sub_model.dart';
import 'package:eatvio_app/features/profile/models/weight_model.dart';
@@ -154,10 +155,10 @@ class ProfileRepository {
}
}
Future<String> getPassKey(String phone) async {
return (jsonDecode(
(await profileService.getPassKey(json: '{"route_name": "user_detailz.change-phone-verify", "route_params": {"phone": "$phone"}}')),
))['key_is']!;
Future<String> getPassKey({required String routeName, Map<String, dynamic>? routeParams}) async {
return (await profileService.getPassKey(
json: PassKeyParams(routeName: routeName, routeParams: routeParams),
)).data['key_is']!;
}
Future<String> getMyPhone() async {

View File

@@ -4,6 +4,7 @@ import 'package:dio/dio.dart';
import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart';
import 'package:eatvio_app/features/profile/models/chosen_diets_pagination_model.dart';
import 'package:eatvio_app/features/profile/models/circumference_model.dart';
import 'package:eatvio_app/features/profile/models/pass_key_params.dart';
import 'package:eatvio_app/features/profile/models/profile_model.dart';
import 'package:eatvio_app/features/profile/models/sub_model.dart';
import 'package:eatvio_app/features/profile/models/weight_model.dart';
@@ -75,7 +76,7 @@ abstract class ProfileService {
Future<ChosenDietsPaginationModel> getChosenDiets();
@POST('/api/profile/make_pass_key')
Future<String> getPassKey({@Body() required String json});
Future<HttpResponse> getPassKey({@Body() required PassKeyParams json});
@GET('/api/profile/my_phone')
Future<String> getMyPhone();

View File

@@ -2,7 +2,7 @@ import 'dart:developer';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/enums/complained_content.dart';
import 'package:eatvio_app/core/enums/product_type.dart';
import 'package:eatvio_app/core/utils/localization_utils.dart';
@@ -247,7 +247,7 @@ class _AboutRecipeScreenState extends State<AboutRecipeScreen> {
Stack(
children: [
CachedNetworkImage(
imageUrl: '$baseUrl/storage/${recipeState.recipe.image}',
imageUrl: '${sl<AppConfig>().baseUrl}/storage/${recipeState.recipe.image}',
height: 300,
width: MediaQuery.sizeOf(context).width,
fit: BoxFit.fill,

View File

@@ -1,5 +1,5 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
@@ -71,7 +71,7 @@ class _MyRecipeWidgetState extends State<MyRecipeWidget> {
child: ClipRRect(
borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
child: CachedNetworkImage(
imageUrl: '$baseUrl/storage/${widget.recipe.image}',
imageUrl: '${sl<AppConfig>().baseUrl}/storage/${widget.recipe.image}',
fit: BoxFit.fitWidth,
width: MediaQuery.of(context).size.width,
),
@@ -162,7 +162,7 @@ class _MyRecipeWidgetState extends State<MyRecipeWidget> {
final box = context.findRenderObject() as RenderBox?;
await SharePlus.instance.share(
ShareParams(
uri: Uri.parse('$baseUrl/ru/recipe/${widget.recipe.slug}'),
uri: Uri.parse('${sl<AppConfig>().baseUrl}/ru/recipe/${widget.recipe.slug}'),
sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
),
);

View File

@@ -1,4 +1,5 @@
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/widgets/main_background_bouble.dart';
@@ -44,7 +45,7 @@ class StepsWidget extends StatelessWidget {
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Image.network(
'$baseUrl/storage/${recipe.steps![index].image}',
'${sl<AppConfig>().baseUrl}/storage/${recipe.steps![index].image}',
fit: BoxFit.cover,
),
),

View File

@@ -1,4 +1,5 @@
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/widgets/loader.dart';
import 'package:eatvio_app/features/registration/services/registration_analytics_service.dart';
@@ -89,7 +90,7 @@ class _VerifyScreenState extends State<VerifyScreen> {
},
),
)
..loadRequest(Uri.parse('$baseUrl/login_with_pass_key?id=${widget.passKey}'));
..loadRequest(Uri.parse('${sl<AppConfig>().baseUrl}/login_with_pass_key?id=${widget.passKey}'));
}
@override

View File

@@ -1,7 +1,7 @@
import 'dart:convert';
import 'dart:developer';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart';
import 'package:eatvio_app/features/registration/services/registration_analytics_service.dart';
@@ -54,7 +54,7 @@ class _WebViewRegistrationScreenState extends State<WebViewRegistrationScreen> {
},
),
)
..loadRequest(Uri.parse('$baseUrl/registration/step1'));
..loadRequest(Uri.parse('${sl<AppConfig>().baseUrl}/registration/step1'));
_injectJavaScript();
}

View File

@@ -1,4 +1,6 @@
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/utils/toasts.dart';
import 'package:eatvio_app/core/widgets/custom_divider.dart';
import 'package:eatvio_app/generated/l10n.dart';
@@ -71,7 +73,7 @@ class SupportScreen extends StatelessWidget {
const SizedBox(height: 12),
if (!hidePlans) ...[
InkWell(
onTap: () async => await launchUrl(Uri.parse('$baseUrl/docs/public_offer.pdf')),
onTap: () async => await launchUrl(Uri.parse('${sl<AppConfig>().baseUrl}/docs/public_offer.pdf')),
borderRadius: BorderRadius.circular(16),
child: const Padding(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 4),
@@ -81,7 +83,7 @@ class SupportScreen extends StatelessWidget {
const SizedBox(height: 8),
],
InkWell(
onTap: () async => await launchUrl(Uri.parse('$baseUrl/docs/privacy.pdf')),
onTap: () async => await launchUrl(Uri.parse('${sl<AppConfig>().baseUrl}/docs/privacy.pdf')),
borderRadius: BorderRadius.circular(16),
child: const Padding(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 4),
@@ -90,7 +92,7 @@ class SupportScreen extends StatelessWidget {
),
const SizedBox(height: 8),
InkWell(
onTap: () async => await launchUrl(Uri.parse('$baseUrl/company-details')),
onTap: () async => await launchUrl(Uri.parse('${sl<AppConfig>().baseUrl}/company-details')),
borderRadius: BorderRadius.circular(16),
child: const Padding(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 4),

View File

@@ -1,3 +1,4 @@
import 'package:eatvio_app/app_keys.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/token_storage.dart';
import 'package:flutter/material.dart';
@@ -79,6 +80,7 @@ class _WelcomeScreenState extends State<WelcomeScreen> {
),
const SizedBox(height: 24),
InkWell(
key: AppKeys.welcomeScreenButton,
onTap: () async {
final sharedPreferences = await SharedPreferences.getInstance();
await sharedPreferences.setBool('welcomeScreenWasShowed', true);

View File

@@ -28,9 +28,10 @@ class S {
static const AppLocalizationDelegate delegate = AppLocalizationDelegate();
static Future<S> load(Locale locale) {
final name = (locale.countryCode?.isEmpty ?? false)
? locale.languageCode
: locale.toString();
final name =
(locale.countryCode?.isEmpty ?? false)
? locale.languageCode
: locale.toString();
final localeName = Intl.canonicalizedLocale(name);
return initializeMessages(localeName).then((_) {
Intl.defaultLocale = localeName;

View File

@@ -1,6 +1,7 @@
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/app_initializer.dart';
import 'package:eatvio_app/core/app_router.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@@ -8,7 +9,7 @@ import 'package:flutter_portal/flutter_portal.dart';
import 'package:keyboard_dismisser/keyboard_dismisser.dart';
Future<void> main() async {
await AppInitializer.initialize();
await AppInitializer.initialize(buildType: AppBuildType.prod);
await AppInitializer.runAppWithSentry(() => runApp(const MyApp()));
}
@@ -18,15 +19,15 @@ class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: AppConfig.globalBlocProviders,
providers: sl<AppConfig>().globalBlocProviders,
child: Portal(
child: KeyboardDismisser(
child: MaterialApp.router(
theme: ThemeHelper().themeData(),
routerConfig: AppRouter.appRouter,
routerConfig: AppRouter.appRouter,
debugShowCheckedModeBanner: false,
localizationsDelegates: AppConfig.localizationDelegates,
supportedLocales: AppConfig.supportedLocales,
localizationsDelegates: sl<AppConfig>().localizationDelegates,
supportedLocales: sl<AppConfig>().supportedLocales,
),
),
),

View File

@@ -1,6 +1,6 @@
name: eatvio_app
description: A new Flutter project.
version: 1.2.14+74
version: 1.3.1+80
publish_to: 'none'
environment:
@@ -88,6 +88,8 @@ dev_dependencies:
sdk: flutter
flutter_lints: ^6.0.0
integration_test:
sdk: flutter
flutter:
uses-material-design: true