Merge remote-tracking branch 'upstream/main' into personalDiets

This commit is contained in:
misha
2025-10-24 13:21:03 +03:00
179 changed files with 42002 additions and 2610 deletions

View File

@@ -0,0 +1,52 @@
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:vk_id/vk_id.dart';
part 'auth_result_entity.freezed.dart';
@freezed
abstract class AuthResultEntity with _$AuthResultEntity {
const factory AuthResultEntity({
required String accessToken,
required String userId,
required String clientId,
String? refreshToken,
String? firstName,
String? lastName,
String? email,
String? phone,
GenderEnum? gender,
String? birthDate,
}) = _AuthResultEntity;
}
enum GenderEnum {
male,
female,
notSet;
static GenderEnum? fromVkGender(VkSex? vkGender) {
switch (vkGender) {
case VkSex.male:
return GenderEnum.male;
case VkSex.female:
return GenderEnum.female;
case VkSex.notStated:
return GenderEnum.notSet;
case null:
return null;
}
}
static GenderEnum? fromString(String? gender) {
switch (gender) {
case 'male':
return GenderEnum.male;
case 'female':
return GenderEnum.female;
case 'notSet':
return GenderEnum.notSet;
default:
return null;
}
}
}

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

@@ -0,0 +1,30 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'yandex_profile_model.freezed.dart';
part 'yandex_profile_model.g.dart';
@freezed
abstract class YandexProfileModel with _$YandexProfileModel {
factory YandexProfileModel({
required String id,
required String login,
required String birthday,
@JsonKey(name: 'client_id') required String clientId,
@JsonKey(name: 'display_name') required String displayName,
@JsonKey(name: 'real_name') required String realName,
@JsonKey(name: 'first_name') required String firstName,
@JsonKey(name: 'last_name') required String lastName,
@JsonKey(name: 'sex') String? sex,
@JsonKey(name: 'default_email') required String defaultEmail,
@JsonKey(name: 'default_phone') required YandexPhoneData defaultPhone,
}) = _YandexProfileModel;
factory YandexProfileModel.fromJson(Map<String, dynamic> json) => _$YandexProfileModelFromJson(json);
}
@freezed
abstract class YandexPhoneData with _$YandexPhoneData {
factory YandexPhoneData({required int id, required String number}) = _YandexPhoneData;
factory YandexPhoneData.fromJson(Map<String, dynamic> json) => _$YandexPhoneDataFromJson(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,6 +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';
@@ -9,9 +10,14 @@ import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/utils/image_constant.dart';
import 'package:eatvio_app/core/utils/toasts.dart';
import 'package:eatvio_app/core/websockets/ws_manager.dart';
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';
@@ -44,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();
@@ -87,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);
@@ -100,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) {
@@ -110,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(
@@ -119,6 +259,41 @@ class _AuthScreenState extends State<AuthScreen> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Center(child: Text('Авторизация через')),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
_SocialButton(
onTap: () => _onVkPressed(),
backgroundColor: const Color(0xFF2787F5),
tooltip: 'VK ID',
child: SvgPicture.asset('assets/icons/vk_logo.svg', height: 24, width: 24),
),
_SocialButton(
onTap: _onOkPressed,
backgroundColor: const Color(0xFFF58220),
tooltip: 'Одноклассники',
child: SvgPicture.asset('assets/icons/ok_logo.svg', height: 24, width: 24),
),
_SocialButton(
onTap: _onMailRuPressed,
backgroundColor: const Color(0xFF005FF9),
tooltip: 'Mail.ru',
child: SvgPicture.asset('assets/icons/mail_logo.svg', height: 24, width: 24),
),
_SocialButton(
onTap: _onYandexPressed,
backgroundColor: const Color(0xFFFFCC00),
tooltip: 'Яндекс ID',
child: SvgPicture.asset('assets/icons/yandex_logo.svg', height: 24, width: 24),
),
],
),
const SizedBox(height: 16),
const CustomDivider(),
const SizedBox(height: 8),
const SizedBox(height: 16),
Text(s.email),
const SizedBox(height: 4),
CustomTextFormField(
@@ -126,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),
@@ -134,6 +310,7 @@ class _AuthScreenState extends State<AuthScreen> {
CustomTextFormField(
obscureText: hidePassword,
controller: passwordController,
key: AppKeys.passwordTextFieldAuthScreen,
hintText: 'Введите пароль',
suffix: IconButton(
onPressed: () {
@@ -168,52 +345,6 @@ class _AuthScreenState extends State<AuthScreen> {
),
],
),
// const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
_SocialButton(
onTap: () => _onVkPressed(context),
backgroundColor: const Color(0xFF2787F5),
tooltip: 'VK ID',
child: SvgPicture.asset(
'assets/icons/vk.svg',
height: 24,
width: 24,
colorFilter: const ColorFilter.mode(Colors.white, BlendMode.srcIn),
),
),
_SocialButton(
onTap: _onOkPressed,
backgroundColor: const Color(0xFFF58220),
tooltip: 'Одноклассники',
child: SvgPicture.asset(
'assets/icons/ok.svg',
height: 24,
width: 24,
colorFilter: const ColorFilter.mode(Colors.white, BlendMode.srcIn),
),
),
const _SocialButton(
onTap: _onMailRuPressed,
backgroundColor: Color(0xFF005FF9),
tooltip: 'Mail.ru',
child: Text(
'Mail',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.w700),
),
),
const _SocialButton(
onTap: _onYandexPressed,
backgroundColor: Color(0xFFFFCC00),
tooltip: 'Яндекс ID',
child: Text(
'Yandex',
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w700),
),
),
],
),
const Spacer(),
Center(
child: RichText(
@@ -232,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: ' и '),
],
@@ -244,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')),
),
],
),
@@ -257,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()
@@ -304,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(
@@ -367,7 +505,6 @@ class _AuthScreenState extends State<AuthScreen> {
}
}
// ignore: unused_element
class _SocialButton extends StatelessWidget {
const _SocialButton({required this.onTap, required this.child, required this.backgroundColor, required this.tooltip});
@@ -381,73 +518,19 @@ class _SocialButton extends StatelessWidget {
return Tooltip(
message: tooltip,
child: InkWell(
borderRadius: BorderRadius.circular(12),
borderRadius: BorderRadius.circular(20),
onTap: onTap,
child: Ink(
height: 48,
width: (MediaQuery.of(context).size.width - 16 * 2 - 12 * 3) / 4,
decoration: BoxDecoration(color: backgroundColor, borderRadius: BorderRadius.circular(12)),
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.circular(20),
border: Border.all(color: const Color(0xFFDBDBDB), width: 1),
),
child: Center(child: child),
),
),
);
}
}
// ignore: unused_element
void _onVkPressed(BuildContext context) async {
final accessToken = await SocialAuthFacade.signInWithVk(context: context);
if (accessToken == null) return;
final isAuthenticated = await sl<AuthCubit>().getTokenBySocial(provider: 'vk', accessToken: accessToken);
if (isAuthenticated) {
if (AppRouter.navigatorKey.currentContext != null) {
// Reuse success flow
// ignore: use_build_context_synchronously
await _reconnectAfterAuth();
}
}
}
void _onOkPressed() async {
final accessToken = await SocialAuthFacade.signInWithOk();
if (accessToken == null) return;
final isAuthenticated = await sl<AuthCubit>().getTokenBySocial(provider: 'ok', accessToken: accessToken);
if (isAuthenticated) {
await _reconnectAfterAuth();
}
}
void _onMailRuPressed() async {
final accessToken = await SocialAuthFacade.signInWithMailRu();
if (accessToken == null) return;
final isAuthenticated = await sl<AuthCubit>().getTokenBySocial(provider: 'mailru', accessToken: accessToken);
if (isAuthenticated) {
await _reconnectAfterAuth();
}
}
void _onYandexPressed() async {
final accessToken = await SocialAuthFacade.signInWithYandex();
if (accessToken == null) return;
final isAuthenticated = await sl<AuthCubit>().getTokenBySocial(provider: 'yandex', accessToken: accessToken);
if (isAuthenticated) {
await _reconnectAfterAuth();
}
}
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,125 +1,214 @@
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:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_login_yandex/flutter_login_yandex.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';
class VkAuthResult {
VkAuthResult({required this.accessToken, this.refreshToken, this.userId, this.firstName, this.lastName, this.email, this.phone, this.gender, this.birthDate});
final String accessToken;
final String? refreshToken;
final String? userId;
final String? firstName;
final String? lastName;
final String? email;
final String? phone;
final String? gender;
final String? birthDate;
}
class SocialAuthFacade {
static Future<String?> signInWithVk({required BuildContext context}) async {
static Future<String?> signInWithVk() async {
final context = AppRouter.navigatorKey.currentContext;
if (context == null) return null;
final result = await signInWithVkAndFetchProfile(context: context);
return result?.accessToken;
}
static Future<VkAuthResult?> signInWithVkAndFetchProfile({required BuildContext context}) async {
final clientIdStr = dotenv.maybeGet('VK_CLIENT_ID')?.trim() ?? Platform.environment['VK_CLIENT_ID'];
if (clientIdStr == null || clientIdStr.isEmpty) {
static Future<AuthResultEntity?> signInWithVkAndFetchProfile({required BuildContext context}) async {
final clientIdStr = Platform.isIOS ? EnvConfig.vkClientIdIos.trim() : EnvConfig.vkClientIdAndroid.trim();
if (clientIdStr.isEmpty) {
return null;
}
try {
dynamic controller = VkIDController(clID: int.parse(clientIdStr));
final authUri = controller.generateAuthorizeLinkWithCodeVerifier();
final redirectScheme = 'vk$clientIdStr://';
final redirectParams = await _presentOAuthWebView(context: context, initialUrl: authUri.toString(), redirectSchemePrefix: redirectScheme);
if (redirectParams == null) return null;
final code = redirectParams['code'];
final deviceId = redirectParams['device_id'];
if (code == null || deviceId == null) return null;
final controller = VkIDController(clID: int.parse(clientIdStr));
final authUri = controller.generateAuthorizeLinkWithCodeVerifier(provider: VkProvider.vkID, scopes: [VkScope.email, VkScope.phone]);
final tokenResponse = await controller.exchangeAuthorizationCodeForToken(code: code, deviceId: deviceId);
final accessToken = _extractAccessToken(tokenResponse);
if (accessToken == null) return null;
return VkAuthResult(accessToken: accessToken);
} catch (_) {
final authUrl = authUri.value.toString();
final codeVerifier = authUri.key;
final redirectScheme = 'vk$clientIdStr://';
final redirectParams = await _presentOAuthWebView(context: context, initialUrl: authUrl, redirectSchemePrefix: redirectScheme);
if (redirectParams == null) {
return null;
}
return await _parseVKAuthResult(redirectParams: redirectParams, controller: controller, codeVerifier: codeVerifier, clientId: clientIdStr);
} catch (e) {
return null;
}
}
static Future<String?> signInWithOk() async {
static Future<AuthResultEntity?> _parseVKAuthResult({
required Map<String, String> redirectParams,
required VkIDController controller,
required String codeVerifier,
required String clientId,
}) async {
final code = redirectParams['code'];
final deviceId = redirectParams['device_id'];
final state = redirectParams['state'];
if (code == null || deviceId == null || state == null) {
return null;
}
final authRes = await controller.retrieveOAuthToken(authorizationCode: code, deviceId: deviceId, codeVerifier: codeVerifier, state: state);
final auth = authRes.result;
if (auth == null) {
var msg = "Retrieve OAuth token error";
final err = authRes.error?.vkErr;
if (err != null) {
msg += ": ${err.error} - ${err.description}";
}
log(msg);
return null;
}
final profileRes = await controller.getProfileInfo();
final profile = profileRes.result;
if (profile == null) {
var msg = "Profile info load error";
final err = profileRes.error?.vkErr;
if (err != null) {
msg += ": ${err.error} - ${err.description}";
}
log(msg);
return null;
}
return AuthResultEntity(
accessToken: auth.accessToken,
refreshToken: auth.refreshToken,
userId: profile.userId.toString(),
firstName: profile.firstName,
lastName: profile.lastName,
email: profile.email,
phone: profile.phone,
gender: GenderEnum.fromVkGender(profile.parsedSex),
birthDate: profile.bDayDt?.toString(),
clientId: clientId,
);
}
static Future<AuthResultEntity?> signInWithOkAndFetchProfile() async {
final context = AppRouter.navigatorKey.currentContext;
if (context == null) return null;
return _signInWithVkIdProvider(context: context, provider: 'ok');
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;
return _signInWithVkIdProvider(context: context, provider: 'mail');
return await _signInWithVkIdProvider(context: context, provider: VkProvider.mailRu);
}
static Future<String?> signInWithYandex() async {
final clientId = dotenv.maybeGet('YANDEX_CLIENT_ID')?.trim() ?? Platform.environment['YANDEX_CLIENT_ID'];
final redirectUri = dotenv.maybeGet('YANDEX_REDIRECT_URI')?.trim() ?? Platform.environment['YANDEX_REDIRECT_URI'];
static Future<AuthResultEntity?> signInWithYandex() async {
final clientId = EnvConfig.yandexClientId.trim();
final redirectUri = EnvConfig.yandexRedirectUri.trim();
if (clientId == null || clientId.isEmpty || redirectUri == null || redirectUri.isEmpty) {
if (clientId.isEmpty || redirectUri.isEmpty) {
return null;
}
try {
final plugin = FlutterLoginYandex();
final response = await plugin.signIn();
final token = (response is Map) ? response['token'] as String? : null;
return (token != null && token.isNotEmpty) ? token : null;
} catch (_) {
return null;
}
}
static Future<String?> _signInWithVkIdProvider({required BuildContext context, required String provider}) async {
final clientIdStr = dotenv.maybeGet('VK_CLIENT_ID')?.trim() ?? Platform.environment['VK_CLIENT_ID'];
if (clientIdStr == null || clientIdStr.isEmpty) {
return null;
}
try {
dynamic controller = VkIDController(clID: int.parse(clientIdStr));
final authUri = controller.generateAuthorizeLinkWithCodeVerifier(provider: provider);
final redirectScheme = 'vk$clientIdStr://';
final redirectParams = await _presentOAuthWebView(context: context, initialUrl: authUri.toString(), redirectSchemePrefix: redirectScheme);
if (redirectParams == null) return null;
final code = redirectParams['code'];
final deviceId = redirectParams['device_id'];
if (code == null || deviceId == null) return null;
final tokenResponse = await controller.exchangeAuthorizationCodeForToken(code: code, deviceId: deviceId, provider: provider);
final accessToken = _extractAccessToken(tokenResponse);
return accessToken;
} catch (_) {
return null;
}
}
final context = AppRouter.navigatorKey.currentContext;
if (context == null) return null;
static String? _extractAccessToken(dynamic tokenResponse) {
if (tokenResponse == null) return null;
if (tokenResponse is Map) {
return (tokenResponse['access_token'] as String?) ?? (tokenResponse['token'] as String?);
final authorizeUrl = Uri.https('oauth.yandex.ru', '/authorize', {
'response_type': 'code',
'client_id': clientId,
'redirect_uri': redirectUri,
'force_confirm': 'true',
}).toString();
final redirectSchemePrefix = redirectUri;
final params = await _presentOAuthWebView(context: context, initialUrl: authorizeUrl, redirectSchemePrefix: redirectSchemePrefix);
if (params == null) return null;
final code = params['code'];
if (code == null || code.isEmpty) {
return null;
}
final tokens = await _getTokensFomYandex(code: code, clientId: clientId, clientSecret: EnvConfig.yandexClientSecret);
if (tokens == null) {
return null;
}
final response = await http.get(Uri.parse('https://login.yandex.ru/info?format=json'), headers: {'Authorization': 'OAuth ${tokens.accessToken}'});
final Map<String, dynamic> json = jsonDecode(response.body);
final yandexProfileData = YandexProfileModel.fromJson(json);
return AuthResultEntity(
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
userId: yandexProfileData.id,
firstName: yandexProfileData.firstName,
lastName: yandexProfileData.lastName,
email: yandexProfileData.defaultEmail,
phone: yandexProfileData.defaultPhone.number,
gender: GenderEnum.fromString(yandexProfileData.sex),
birthDate: yandexProfileData.birthday,
clientId: clientId,
);
} catch (e) {
log(e.toString());
}
try {
final token = (tokenResponse as dynamic).accessToken as String?;
if (token != null && token.isNotEmpty) return token;
} catch (_) {}
try {
final token = (tokenResponse as dynamic).token as String?;
if (token != null && token.isNotEmpty) return token;
} catch (_) {}
return null;
}
static Future<({String accessToken, String refreshToken})?> _getTokensFomYandex({
required String code,
required String clientId,
required 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) {
log('Yandex token exchange failed: ${response.body}');
return null;
}
final tokens = jsonDecode(response.body);
final accessToken = tokens['access_token'] as String;
final refreshToken = tokens['refresh_token'] as String;
return (accessToken: accessToken, refreshToken: refreshToken);
}
static Future<AuthResultEntity?> _signInWithVkIdProvider({required BuildContext context, required VkProvider provider}) async {
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, scopes: [VkScope.phone, VkScope.email]);
final codeVerifier = authUri.key;
final authUrl = authUri.value.toString();
final redirectScheme = 'vk$clientIdStr://';
final redirectParams = await _presentOAuthWebView(context: context, initialUrl: authUrl, redirectSchemePrefix: redirectScheme);
if (redirectParams == null) return null;
final code = redirectParams['code'];
final deviceId = redirectParams['device_id'];
if (code == null || deviceId == null) return null;
return await _parseVKAuthResult(redirectParams: redirectParams, controller: controller, codeVerifier: codeVerifier, clientId: clientIdStr);
} catch (e) {
return null;
}
}
static Future<Map<String, String>?> _presentOAuthWebView({
required BuildContext context,
required String initialUrl,
@@ -134,22 +223,49 @@ class SocialAuthFacade {
if (url.startsWith(redirectSchemePrefix)) {
final uri = Uri.parse(url);
final params = <String, String>{}..addAll(uri.queryParameters);
Navigator.of(context, rootNavigator: true).pop(params);
if (uri.fragment.isNotEmpty) {
final fragPairs = uri.fragment.split('&');
for (final pair in fragPairs) {
final eq = pair.indexOf('=');
if (eq > 0 && eq < pair.length - 1) {
final key = Uri.decodeComponent(pair.substring(0, eq));
final value = Uri.decodeComponent(pair.substring(eq + 1));
params[key] = value;
}
}
}
if (GoRouter.of(context).canPop()) {
GoRouter.of(context).pop(params);
}
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
onPageStarted: (url) {},
onPageFinished: (url) {},
onWebResourceError: (error) {},
),
)
..loadRequest(Uri.parse(initialUrl));
);
try {
await controller.loadRequest(Uri.parse(initialUrl));
} catch (e) {
return null;
}
if (!context.mounted) return null;
return showDialog<Map<String, String>>(
context: context,
barrierDismissible: false,
builder: (_) {
const borderRadius = BorderRadius.all(Radius.circular(16));
return Dialog(
insetPadding: const EdgeInsets.all(16),
child: SizedBox(height: 560, child: WebViewWidget(controller: controller)),
shape: const RoundedRectangleBorder(borderRadius: borderRadius),
elevation: 0,
child: ClipRRect(
borderRadius: borderRadius,
child: SizedBox(height: 560, child: WebViewWidget(controller: controller)),
),
);
},
);

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';
@@ -198,7 +198,7 @@ class _BlogPostScreenState extends State<BlogPostScreen> {
child: Column(
children: [
GestureDetector(
onTap: () => GoRouter.of(context).pushNamed('profileScreen', extra: blogPostState.blogPostModel?.author),
onTap: () => GoRouter.of(context).pushNamed('profileScreen', extra: blogPostState.blogPostModel?.author.authorSlug),
child: Ink(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
@@ -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,62 +1,35 @@
import 'dart:developer';
import 'package:eatvio_app/core/cubit/base_cubit.dart';
import 'package:eatvio_app/features/blog_post_create/bloc/blog_post_create_cubit/blog_post_create_state.dart';
import 'package:eatvio_app/features/blog_post_create/repositories/blog_post_repository.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
class BlogPostCreateCubit extends Cubit<BlogPostCreateState> {
class BlogPostCreateCubit extends BaseCubit<BlogPostCreateState> {
final BlogPostRepository blogPostRepository;
BlogPostCreateCubit({
required this.blogPostRepository,
}) : super(const BlogPostCreateState());
BlogPostCreateCubit({required this.blogPostRepository}) : super(const BlogPostCreateState());
Future<bool> createBlogPost({
String? title,
String? videoUrl,
String? description,
XFile? image,
}) async {
Future<bool> createBlogPost({String? title, String? videoUrl, String? description, XFile? image}) async {
try {
emit(const BlogPostCreateState.loading());
await blogPostRepository.createBlogPost(
title,
videoUrl,
description,
image,
);
return true;
} catch (e, st) {
log(e.toString(), stackTrace: st);
await blogPostRepository.createBlogPost(title, videoUrl, description, image);
emit(const BlogPostCreateState.loaded());
return true;
} catch (error, stackTrace) {
handleError(error, stackTrace);
emit(BlogPostCreateState.error(errorMessage: error.toString()));
return false;
}
}
Future<bool> updateBlogPost({
required int id,
String? title,
String? videoUrl,
String? description,
XFile? image,
String? oldImageUrl,
}) async {
Future<bool> updateBlogPost({required int id, String? title, String? videoUrl, String? description, XFile? image, String? oldImageUrl}) async {
try {
emit(const BlogPostCreateState.loading());
await blogPostRepository.updateBlogPost(
id,
title,
videoUrl,
description,
image,
oldImageUrl,
);
await blogPostRepository.updateBlogPost(id, title, videoUrl, description, image, oldImageUrl);
emit(const BlogPostCreateState.loaded());
return true;
} catch (e, st) {
log(e.toString(), stackTrace: st);
emit(const BlogPostCreateState.loaded());
} catch (error, stackTrace) {
handleError(error, stackTrace);
emit(BlogPostCreateState.error(errorMessage: error.toString()));
return false;
}
}
@@ -65,8 +38,8 @@ class BlogPostCreateCubit extends Cubit<BlogPostCreateState> {
try {
await blogPostRepository.deleteBlogPost(id);
return true;
} catch (e, st) {
log(e.toString(), stackTrace: st);
} catch (error, stackTrace) {
handleError(error, stackTrace);
return false;
}
}

View File

@@ -1,7 +1,8 @@
import 'dart:async';
import 'dart:io';
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/permission_handler/permission_handler.dart';
import 'package:eatvio_app/core/theme/app_decoration.dart';
import 'package:eatvio_app/core/widgets/show_error_dialog.dart';
@@ -153,6 +154,7 @@ class _BlogPostCreateScreenState extends State<BlogPostCreateScreen> {
floatingActionButton: SizedBox(
width: MediaQuery.of(context).size.width - 32,
child: FloatingActionButton.extended(
key: AppKeys.blogPostCreateScreenCreateButton,
heroTag: 'createBlogPost',
highlightElevation: 0,
elevation: 0,
@@ -225,12 +227,14 @@ class _BlogPostCreateScreenState extends State<BlogPostCreateScreen> {
const Text('Заголовок'),
const SizedBox(height: 8),
CustomTextFormField(
key: AppKeys.blogPostCreateScreenTitleTextField,
controller: titleController,
),
const SizedBox(height: 16),
const Text('Описание'),
const SizedBox(height: 8),
CustomTextFormField(
key: AppKeys.blogPostCreateScreenContentTextField,
controller: descriptionController,
maxLines: 6,
minLines: 4,
@@ -244,6 +248,7 @@ class _BlogPostCreateScreenState extends State<BlogPostCreateScreen> {
if (image == null && widget.feedBlogPostModel?.image == null) const SizedBox(height: 8),
if (image == null && widget.feedBlogPostModel?.image == null)
CustomTextFormField(
key: AppKeys.blogPostCreateScreenVideoLinkTextField,
controller: videoUrlController,
),
const SizedBox(height: 80),
@@ -304,7 +309,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

@@ -18,7 +18,6 @@ import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/features/chat/presentation/widgets/notification_banner.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
import 'package:eatvio_app/features/order_info/presentation/info_by_order_screen.dart';
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
@@ -154,12 +153,7 @@ class _ChatScreenState extends State<ChatScreen> {
onTap: () {
GoRouter.of(context).pushNamed(
'profileScreen',
extra: Author(
authorSlug: state.chatRoom.users.receiver.slug,
authorName: state.chatRoom.users.receiver.name,
authorProfileIcon: state.chatRoom.users.receiver.profilePhotoUrl ?? '',
authorIsMe: false,
),
extra: state.chatRoom.users.receiver.slug,
);
},
child: Row(

View File

@@ -6,7 +6,7 @@ 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/features/chat/repositories/chat_repository.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/features/profile/models/profile_model.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
@@ -16,12 +16,9 @@ import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked
import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked_users_state.dart';
class EmptyChatScreen extends StatefulWidget {
final Author author;
final ProfileModel user;
const EmptyChatScreen({
super.key,
required this.author,
});
const EmptyChatScreen({super.key, required this.user});
@override
State<EmptyChatScreen> createState() => _EmptyChatScreenState();
@@ -40,34 +37,19 @@ class _EmptyChatScreenState extends State<EmptyChatScreen> {
centerTitle: false,
title: GestureDetector(
onTap: () {
GoRouter.of(context).pushNamed(
'profileScreen',
extra: Author(
authorSlug: widget.author.authorSlug,
authorName: widget.author.authorName,
authorProfileIcon: widget.author.authorProfileIcon,
authorIsMe: false,
),
);
GoRouter.of(context).pushNamed('profileScreen', extra: widget.user.slug);
},
child: Row(
children: [
CircleAvatar(
radius: 20,
foregroundImage: NetworkImage(widget.author.authorProfileIcon),
foregroundImage: NetworkImage(widget.user.profilePhotoUrl),
backgroundImage: const AssetImage('assets/images/no_avatar.png'),
),
const SizedBox(width: 16),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.author.authorName,
style: CustomTextStyles.titleSmallBold.copyWith(
color: PrimaryColors().black,
),
),
],
children: [Text(widget.user.name, style: CustomTextStyles.titleSmallBold.copyWith(color: PrimaryColors().black))],
),
],
),
@@ -84,18 +66,14 @@ class _EmptyChatScreenState extends State<EmptyChatScreen> {
children: [
const SizedBox(width: 8),
InkWell(
onTap: () => showImagePicker(widget.author.authorSlug),
onTap: () => showImagePicker(widget.user.slug),
customBorder: const CircleBorder(),
child: Ink(
height: 40,
width: 40,
child: Transform.rotate(
angle: pi / 4,
child: const Icon(
Icons.attach_file_rounded,
size: 30,
color: Color(0xFF858E99),
),
child: const Icon(Icons.attach_file_rounded, size: 30, color: Color(0xFF858E99)),
),
),
),
@@ -117,8 +95,10 @@ class _EmptyChatScreenState extends State<EmptyChatScreen> {
hintText: 'Сообщение',
hintStyle: const TextStyle(fontSize: 14, fontWeight: FontWeight.w400, height: 1, color: Color(0xFFAEAEB2)),
filled: true,
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(100), borderSide: const BorderSide(color: Color(0xFFD1D1D6), width: 1)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(100),
borderSide: const BorderSide(color: Color(0xFFD1D1D6), width: 1),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(100),
borderSide: const BorderSide(color: Color(0xFFD1D1D6), width: 1),
@@ -139,40 +119,29 @@ class _EmptyChatScreenState extends State<EmptyChatScreen> {
final blockedUsersCubit = sl<BlockedUsersCubit>();
await blockedUsersCubit.getBlockedUsers();
final blockedState = blockedUsersCubit.state;
if (blockedState is BlockedUsersStateLoaded) {
final isBlocked = blockedState.profilesList.any((profile) => profile.slug == widget.author.authorSlug);
final isBlocked = blockedState.profilesList.any((profile) => profile.slug == widget.user.slug);
if (isBlocked) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Вы не можете отправить сообщение заблокированному пользователю'),
backgroundColor: Colors.red,
),
const SnackBar(content: Text('Вы не можете отправить сообщение заблокированному пользователю'), backgroundColor: Colors.red),
);
}
return;
}
}
if (textEditingController.text.isNotEmpty) {
await sl<ChatRepository>().sendMessage(
data: textEditingController.text.trim(),
slug: widget.author.authorSlug,
);
await sl<ChatRepository>().sendMessage(data: textEditingController.text.trim(), slug: widget.user.slug);
if (mounted) {
setState(() {
textEditingController.clear();
});
}
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.author.authorSlug);
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
if (context.mounted) {
AppRouter.navigatorKey.currentContext?.pushReplacementNamed(
'chatScreen',
extra: {
'uuid': chatIdOrError,
},
);
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError});
}
}
},
@@ -201,53 +170,36 @@ class _EmptyChatScreenState extends State<EmptyChatScreen> {
CupertinoActionSheetAction(
onPressed: () async {
Navigator.of(context).pop();
// Проверяем, заблокирован ли пользователь
final blockedUsersCubit = sl<BlockedUsersCubit>();
await blockedUsersCubit.getBlockedUsers();
final blockedState = blockedUsersCubit.state;
if (blockedState is BlockedUsersStateLoaded) {
final isBlocked = blockedState.profilesList.any((profile) => profile.slug == widget.author.authorSlug);
final isBlocked = blockedState.profilesList.any((profile) => profile.slug == widget.user.slug);
if (isBlocked) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Вы не можете отправить сообщение заблокированному пользователю'),
backgroundColor: Colors.red,
),
const SnackBar(content: Text('Вы не можете отправить сообщение заблокированному пользователю'), backgroundColor: Colors.red),
);
}
return;
}
}
final picker = ImagePicker();
List<XFile>? images = await picker.pickMultiImage();
if (images.isNotEmpty) {
List<File> files = images.map((image) => File(image.path)).toList();
await sl<ChatRepository>().sendMessage(
files: files,
slug: widget.author.authorSlug,
);
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.author.authorSlug);
await sl<ChatRepository>().sendMessage(files: files, slug: widget.user.slug);
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
if (mounted) {
AppRouter.navigatorKey.currentContext?.pushReplacementNamed(
'chatScreen',
extra: {
'uuid': chatIdOrError,
},
);
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError});
}
}
},
child: const Row(
children: [
Icon(Icons.photo_library_rounded),
SizedBox(width: 8),
Text('Галерея'),
],
),
child: const Row(children: [Icon(Icons.photo_library_rounded), SizedBox(width: 8), Text('Галерея')]),
),
CupertinoActionSheetAction(
onPressed: () async {
@@ -256,28 +208,14 @@ class _EmptyChatScreenState extends State<EmptyChatScreen> {
List<XFile>? images = await picker.pickMultiImage();
if (images.isNotEmpty) {
List<File> files = images.map((image) => File(image.path)).toList();
await sl<ChatRepository>().sendMessage(
files: files,
slug: widget.author.authorSlug,
);
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.author.authorSlug);
await sl<ChatRepository>().sendMessage(files: files, slug: widget.user.slug);
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
if (mounted) {
AppRouter.navigatorKey.currentContext?.pushReplacementNamed(
'chatScreen',
extra: {
'uuid': chatIdOrError,
},
);
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError});
}
}
},
child: const Row(
children: [
Icon(Icons.photo_camera),
SizedBox(width: 8),
Text('Фото'),
],
),
child: const Row(children: [Icon(Icons.photo_camera), SizedBox(width: 8), Text('Фото')]),
),
CupertinoActionSheetAction(
onPressed: () async {
@@ -308,35 +246,17 @@ class _EmptyChatScreenState extends State<EmptyChatScreen> {
);
if (result != null) {
List<File> files = result.paths.map((path) => File(path!)).toList();
await sl<ChatRepository>().sendMessage(
files: files,
slug: widget.author.authorSlug,
);
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.author.authorSlug);
await sl<ChatRepository>().sendMessage(files: files, slug: widget.user.slug);
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
if (mounted) {
AppRouter.navigatorKey.currentContext?.pushReplacementNamed(
'chatScreen',
extra: {
'uuid': chatIdOrError,
},
);
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError});
}
}
},
child: const Row(
children: [
Icon(Icons.file_present_rounded),
SizedBox(width: 8),
Text('Файлы'),
],
),
child: const Row(children: [Icon(Icons.file_present_rounded), SizedBox(width: 8), Text('Файлы')]),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.of(context).pop(),
isDestructiveAction: true,
child: const Text('Отмена'),
),
cancelButton: CupertinoActionSheetAction(onPressed: () => Navigator.of(context).pop(), isDestructiveAction: true, child: const Text('Отмена')),
),
);
}

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

@@ -13,6 +13,7 @@ abstract class StatisticsModel with _$StatisticsModel {
@JsonKey(name: 'count_diets') int? dietsCount,
@JsonKey(name: 'count_consultants') int? consultationsCount,
@JsonKey(name: 'count_products_nutritional_values') int? qwe,
@JsonKey(name: 'referral_link') String? refLink,
}) = _StatisticsModel;
factory StatisticsModel.fromJson(Map<String, dynamic> json) => _$StatisticsModelFromJson(json);

View File

@@ -1,6 +1,7 @@
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/toasts.dart';
import 'package:eatvio_app/core/widgets/custom_outlined_button.dart';
import 'package:eatvio_app/core/widgets/data_error_widget.dart';
import 'package:eatvio_app/features/consultant_rating/presentation/cubit/consultant_rating_cubit.dart';
@@ -10,6 +11,7 @@ import 'package:eatvio_app/features/consultant_rating/presentation/widgets/ratin
import 'package:eatvio_app/features/consultant_rating/presentation/widgets/statistic_widget.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class ConsultantRatingScreen extends StatelessWidget {
@@ -53,8 +55,8 @@ class ConsultantRatingPageContent extends StatelessWidget {
child: Column(
children: [
const SizedBox(height: 16),
const RatingWidget(
rating: 1058,
RatingWidget(
rating: state.absoluteRating!,
),
const SizedBox(height: 16),
Padding(
@@ -67,7 +69,10 @@ class ConsultantRatingPageContent extends StatelessWidget {
side: const WidgetStatePropertyAll(BorderSide.none),
backgroundColor: WidgetStatePropertyAll(appTheme.blueA400),
),
onPressed: () {},
onPressed: () {
Clipboard.setData(ClipboardData(text: state.statistics?.refLink ?? ''));
showInfoToast(s.link_was_copied);
},
),
),
const SizedBox(height: 16),

View File

@@ -2,17 +2,23 @@ import 'dart:developer';
import 'package:eatvio_app/features/consultant_rating/presentation/cubit/consultant_rating_state.dart';
import 'package:eatvio_app/features/consultant_rating/repositories/consultant_rating_repository.dart';
import 'package:eatvio_app/features/feed/repositories/feed_repository.dart';
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class ConsultantRatingCubit extends Cubit<ConsultantRatingState> {
final ConsultantRatingRepository repository;
ConsultantRatingCubit(this.repository) : super(ConsultantRatingState());
final FeedRepository feedRepository;
final ProfileRepository profileRepository;
ConsultantRatingCubit({required this.repository, required this.feedRepository, required this.profileRepository}) : super(ConsultantRatingState());
Future<void> getConsultantStatistics({String? date}) async {
try {
emit(state.copyWith(isStatisticsLoading: true));
final statistics = await repository.getConsultantStatistics(date: date);
emit(state.copyWith(isStatisticsLoading: false, statistics: statistics, error: null));
final absoluteRating = await feedRepository.getConsultants((await profileRepository.getMyProfile()).name);
emit(state.copyWith(isStatisticsLoading: false, statistics: statistics, error: null, absoluteRating: absoluteRating.first.totalScores));
} catch (e, st) {
emit(state.copyWith(isStatisticsLoading: true, error: e.toString()));
log(e.toString(), stackTrace: st);

View File

@@ -12,5 +12,6 @@ abstract class ConsultantRatingState with _$ConsultantRatingState {
@Default(null) StatisticsModel? statistics,
@Default(null) String? error,
@Default(<RatingModel>[]) List<RatingModel> ratings,
@Default(0) int? absoluteRating,
}) = _ConsultantRatingState;
}

View File

@@ -71,7 +71,7 @@ class StatisticWidget extends StatelessWidget {
children: [
Expanded(child: StatisticBouble(number: statistics?.consultationsCount ?? 0, title: s.consultations_count)),
const SizedBox(width: 8),
Expanded(child: StatisticBouble(number: statistics?.qwe ?? 0, title: s.active_consultations_count)),
Expanded(child: StatisticBouble(number: statistics?.qwe ?? 0, title: s.added_products_in_glossary)),
],
),
const SizedBox(

View File

@@ -2,8 +2,11 @@ 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/app_initializer.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';
@@ -45,6 +48,7 @@ class CreateDietCubit extends Cubit<CreateDietState> {
type['veg'] = diet.type.veg ?? false;
type['carb'] = diet.type.carb ?? false;
type['light'] = diet.type.light ?? false;
final appConfig = sl<AppConfig>();
emit(
state.copyWith.dietData(
dailySchedule: dailySchedule,
@@ -53,7 +57,8 @@ class CreateDietCubit extends Cubit<CreateDietState> {
name: diet.name,
duration: diet.duration,
type: type,
imageUrl: '$baseUrl/storage/${diet.image}',
// Avoid network image URLs during tests to prevent HTTP fetch attempts
imageUrl: appConfig.buildType == AppBuildType.tests ? null : '${appConfig.baseUrl}/storage/${diet.image}',
),
);
emit(state.copyWith(dietState: diet.state, durationIndex: durationValues.indexOf(diet.duration)));
@@ -74,11 +79,7 @@ class CreateDietCubit extends Cubit<CreateDietState> {
final dailySchedule = state.dietData.dailySchedule;
if (currentDaysValue != null && dailySchedule != null) {
final deepCopyOfDailySchedule = dailySchedule
.map(
(day) => day.map((meal) => [...meal]).toList(),
)
.toList();
final deepCopyOfDailySchedule = dailySchedule.map((day) => day.map((meal) => [...meal]).toList()).toList();
if (currentDaysValue > selectedDaysValue) {
final difference = currentDaysValue - selectedDaysValue;
@@ -91,28 +92,16 @@ class CreateDietCubit extends Cubit<CreateDietState> {
deepCopyOfDailySchedule.add([[], [], [], [], []]);
}
}
emit(
state.copyWith(
dietData: state.dietData.copyWith(
dailySchedule: deepCopyOfDailySchedule,
),
),
);
emit(state.copyWith(dietData: state.dietData.copyWith(dailySchedule: deepCopyOfDailySchedule)));
} else {
final List<List<List<DailySchedule>>> dailySchedule = List.generate(selectedDaysValue, (index) => [[], [], [], [], []]);
emit(
state.copyWith(
dietData: state.dietData.copyWith(dailySchedule: dailySchedule),
),
);
emit(state.copyWith(dietData: state.dietData.copyWith(dailySchedule: dailySchedule)));
}
emit(
state.copyWith(
durationIndex: index,
dietData: state.dietData.copyWith(
duration: durationValues[index],
),
dietData: state.dietData.copyWith(duration: durationValues[index]),
dietDurationError: null,
),
);
@@ -123,7 +112,12 @@ class CreateDietCubit extends Cubit<CreateDietState> {
}
void setImage(XFile? image, {String? imageUrl}) {
emit(state.copyWith(dietData: state.dietData.copyWith(image: image, imageUrl: imageUrl), dietImageError: null));
emit(
state.copyWith(
dietData: state.dietData.copyWith(image: image, imageUrl: imageUrl),
dietImageError: null,
),
);
}
void setDailySchedule(List<List<List<DailySchedule>>> dailySchedule) {
@@ -131,27 +125,25 @@ class CreateDietCubit extends Cubit<CreateDietState> {
}
void setDietState(DietState dietState) {
emit(state.copyWith(dietData: state.dietData.copyWith(state: dietState), dietState: dietState, dietStateError: null));
emit(
state.copyWith(
dietData: state.dietData.copyWith(state: dietState),
dietState: dietState,
dietStateError: null,
),
);
}
void setDietType({required String key, required bool value}) {
final type = Map<String, bool>.from(state.dietData.type);
type[key] = value;
emit(
state.copyWith(
dietData: state.dietData.copyWith(type: type),
),
);
emit(state.copyWith(dietData: state.dietData.copyWith(type: type)));
}
void addPortion({required int dayIndex, required int mealIndex, required DailySchedule portion}) {
final dailySchedule = state.dietData.dailySchedule;
if (dailySchedule != null) {
final deepCopyOfDailySchedule = dailySchedule
.map(
(day) => day.map((meal) => [...meal]).toList(),
)
.toList();
final deepCopyOfDailySchedule = dailySchedule.map((day) => day.map((meal) => [...meal]).toList()).toList();
deepCopyOfDailySchedule[dayIndex][mealIndex].add(portion);
final newDietData = state.dietData.copyWith(dailySchedule: deepCopyOfDailySchedule);
@@ -160,18 +152,10 @@ class CreateDietCubit extends Cubit<CreateDietState> {
}
}
void removePortion({
required int day,
required int meal,
required int portionIndex,
}) {
void removePortion({required int day, required int meal, required int portionIndex}) {
final dailySchedule = state.dietData.dailySchedule;
if (dailySchedule != null) {
final deepCopyOfDailySchedule = dailySchedule
.map(
(day) => day.map((meal) => [...meal]).toList(),
)
.toList();
final deepCopyOfDailySchedule = dailySchedule.map((day) => day.map((meal) => [...meal]).toList()).toList();
deepCopyOfDailySchedule[day][meal].removeAt(portionIndex);
final newDietData = state.dietData.copyWith(dailySchedule: deepCopyOfDailySchedule);
@@ -182,11 +166,7 @@ class CreateDietCubit extends Cubit<CreateDietState> {
void updatePortion({required int dayIndex, required int mealIndex, required int portionIndex, required DailySchedule portion}) {
final dailySchedule = state.dietData.dailySchedule;
if (dailySchedule != null) {
final deepCopyOfDailySchedule = dailySchedule
.map(
(day) => day.map((meal) => [...meal]).toList(),
)
.toList();
final deepCopyOfDailySchedule = dailySchedule.map((day) => day.map((meal) => [...meal]).toList()).toList();
deepCopyOfDailySchedule[dayIndex][mealIndex][portionIndex] = portion;
final newDietData = state.dietData.copyWith(dailySchedule: deepCopyOfDailySchedule);
@@ -197,11 +177,7 @@ class CreateDietCubit extends Cubit<CreateDietState> {
void copyDay(int dayIndex) {
final dailySchedule = state.dietData.dailySchedule;
if (dailySchedule != null) {
final deepCopyOfDailySchedule = dailySchedule
.map(
(day) => day.map((meal) => [...meal]).toList(),
)
.toList();
final deepCopyOfDailySchedule = dailySchedule.map((day) => day.map((meal) => [...meal]).toList()).toList();
final copiedDay = deepCopyOfDailySchedule[dayIndex];
emit(state.copyWith(copiedDay: copiedDay));
}
@@ -211,11 +187,7 @@ class CreateDietCubit extends Cubit<CreateDietState> {
final dailySchedule = state.dietData.dailySchedule;
final copiedDay = state.copiedDay;
if (dailySchedule != null && copiedDay != null) {
final deepCopyOfDailySchedule = dailySchedule
.map(
(day) => day.map((meal) => [...meal]).toList(),
)
.toList();
final deepCopyOfDailySchedule = dailySchedule.map((day) => day.map((meal) => [...meal]).toList()).toList();
deepCopyOfDailySchedule[dayIndex] = copiedDay;
final newDietData = state.dietData.copyWith(dailySchedule: deepCopyOfDailySchedule);
emit(state.copyWith(dietData: newDietData));
@@ -266,14 +238,7 @@ class CreateDietCubit extends Cubit<CreateDietState> {
final dailyNutrition = <DailyNutrition>[];
if (carbs != null && calories != null && fats != null && proteins != null) {
for (int i = 0; i < carbs.length; i++) {
dailyNutrition.add(
DailyNutrition(
carbohydrates: carbs[i],
energy: calories[i],
fats: fats[i],
proteins: proteins[i],
),
);
dailyNutrition.add(DailyNutrition(carbohydrates: carbs[i], energy: calories[i], fats: fats[i], proteins: proteins[i]));
}
}
final dailySchedule = <int, Map<int, Map<int, DailySchedule>>>{};

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,3 +1,4 @@
import 'package:eatvio_app/app_keys.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/widgets/bottom_sheet_with_blur.dart';
@@ -18,10 +19,7 @@ import 'package:go_router/go_router.dart';
class RecipeCreateScreen extends StatefulWidget {
final Recipe? recipe;
const RecipeCreateScreen({
super.key,
this.recipe,
});
const RecipeCreateScreen({super.key, this.recipe});
static const name = 'recipeCreateScreen';
static const path = '/recipe-create-screen';
@@ -52,20 +50,14 @@ class _RecipeCreateScreenState extends State<RecipeCreateScreen> {
child: BlocBuilder<CreateRecipeCubit, CreateRecipeState>(
builder: (BuildContext context, CreateRecipeState state) {
if (state.loading) {
return const Scaffold(
body: Loader(),
);
return const Scaffold(body: Loader());
} else {
return Scaffold(
backgroundColor: const Color(0xFFF0F2F5),
appBar: AppBar(
title: widget.recipe != null ? const Text('Редактирование рецепта') : const Text('Добавление рецепта'),
centerTitle: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
bottom: Radius.circular(12),
),
),
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(bottom: Radius.circular(12))),
),
body: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
@@ -73,24 +65,21 @@ class _RecipeCreateScreenState extends State<RecipeCreateScreen> {
child: Column(
spacing: 16,
children: [
InfoAboutRecipeWidget(
createRecipeCubit: createRecipeCubit,
),
InfoAboutRecipeWidget(createRecipeCubit: createRecipeCubit),
const IngredientsWidget(),
StepsWidget(
createRecipeCubit: createRecipeCubit,
),
StepsWidget(createRecipeCubit: createRecipeCubit),
BlocBuilder<CreateRecipeCubit, CreateRecipeState>(
builder: (context, state) {
return Builder(
builder: (context) {
return InkWell(
key: AppKeys.recipeCreateScreenPublishButton,
onTap: () async {
if (context.read<CreateRecipeCubit>().validateAll()) {
final isSuccess = await context.read<CreateRecipeCubit>().publishRecipe(
widget.recipe == null ? false : true,
widget.recipe?.slug,
);
widget.recipe == null ? false : true,
widget.recipe?.slug,
);
if (isSuccess) {
Future.delayed(const Duration(milliseconds: 500), () {
if (!context.mounted) return;
@@ -98,9 +87,7 @@ class _RecipeCreateScreenState extends State<RecipeCreateScreen> {
showBottomSheetWithBlur(
userRootNavigator: true,
context: context,
child: SuccessPublishedRecipeBottomSheet(
title: state.entity.title ?? 'Рецепт',
),
child: SuccessPublishedRecipeBottomSheet(title: state.entity.title ?? 'Рецепт'),
);
});
} else {
@@ -112,20 +99,13 @@ class _RecipeCreateScreenState extends State<RecipeCreateScreen> {
borderRadius: BorderRadius.circular(20),
child: Ink(
width: MediaQuery.of(context).size.width - 32,
decoration: BoxDecoration(
color: appTheme.blueA400,
borderRadius: BorderRadius.circular(20),
),
decoration: BoxDecoration(color: appTheme.blueA400, borderRadius: BorderRadius.circular(20)),
child: Container(
padding: const EdgeInsets.all(16),
alignment: Alignment.center,
child: Text(
widget.recipe != null ? 'Обновить' : 'Опубликовать',
style: const TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w600,
),
style: const TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.w600),
),
),
),

View File

@@ -1,4 +1,5 @@
import 'package:easy_debounce/easy_debounce.dart';
import 'package:eatvio_app/app_keys.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/widgets/custom_divider.dart';
@@ -12,13 +13,7 @@ import 'package:eatvio_app/features/glossary/models/glossary_model.dart';
import 'package:flutter/material.dart';
class AddPortionWidget extends StatefulWidget {
const AddPortionWidget({
super.key,
required this.createRecipeCubit,
this.portionIndex,
this.productNameControllerText,
this.quantityControllerText,
});
const AddPortionWidget({super.key, required this.createRecipeCubit, this.portionIndex, this.productNameControllerText, this.quantityControllerText});
final CreateRecipeCubit createRecipeCubit;
final String? productNameControllerText;
final String? quantityControllerText;
@@ -43,76 +38,65 @@ class _AddPortionWidgetState extends State<AddPortionWidget> {
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16) +
EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
padding: const EdgeInsets.all(16) + EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
const Text(
'Добавление блюда',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Color(0xFF323F4B),
),
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600, color: Color(0xFF323F4B)),
),
const SizedBox(height: 16),
Row(
mainAxisSize: MainAxisSize.min,
mainAxisSize: MainAxisSize.max,
children: [
SizedBox(
width: MediaQuery.of(context).size.width * 0.8 - 32,
Expanded(
flex: 4,
child: CustomTextFormField(
key: AppKeys.recipeCreateScreenIngredientNameField,
controller: productNameController,
autofocus: true,
hintText: 'Введите название продукта/блюда',
onChanged: (query) {
EasyDebounce.debounce(
'glossary-search',
const Duration(milliseconds: 250),
() async {
EasyDebounce.debounce('glossary-search', const Duration(milliseconds: 250), () async {
selectedGlossary = null;
if (query.isEmpty) {
glossariesList = [];
selectedGlossary = null;
if (query.isEmpty) {
glossariesList = [];
selectedGlossary = null;
setState(() {});
return;
}
glossariesList = await widget.createRecipeCubit.getGlossaryListByQuery(query);
setState(() {});
},
);
return;
}
glossariesList = await widget.createRecipeCubit.getGlossaryListByQuery(query);
setState(() {});
});
},
),
),
const SizedBox(width: 4),
SizedBox(
width: MediaQuery.of(context).size.width * 0.2 - 4,
Expanded(
flex: 1,
child: CustomTextFormField(
key: AppKeys.recipeCreateScreenIngredientQuantityField,
controller: quantityController,
keyboardType: TextInputType.number,
hintText: selectedGlossary == null
? '100'
: selectedGlossary!.grInPortion == 0
? '100'
: '1',
? '100'
: '1',
suffixText: selectedGlossary == null
? 'гр'
: selectedGlossary?.grInPortion == 0
? 'гр'
: 'шт',
? 'гр'
: 'шт',
),
),
],
),
glossariesList.isEmpty ? const SizedBox(height: 16) : const SizedBox.shrink(),
Container(
constraints: const BoxConstraints(
maxHeight: 256,
),
constraints: const BoxConstraints(maxHeight: 256),
child: ListView.separated(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
@@ -127,28 +111,12 @@ class _AddPortionWidgetState extends State<AddPortionWidget> {
setState(() {});
FocusManager.instance.primaryFocus?.nextFocus();
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
title: Text(
glossariesList[i].name,
style: const TextStyle(
height: 1,
),
),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
title: Text(glossariesList[i].name, style: const TextStyle(height: 1)),
subtitle: glossariesList[i].grInPortion == 0
? null
: Text(
'${glossariesList[i].grInPortion} г',
style: TextStyle(
height: 1,
color: Colors.grey.shade600,
),
),
trailing: Icon(
Icons.add_rounded,
color: Colors.grey.shade400,
),
: Text('${glossariesList[i].grInPortion} г', style: TextStyle(height: 1, color: Colors.grey.shade600)),
trailing: Icon(Icons.add_rounded, color: Colors.grey.shade400),
contentPadding: const EdgeInsets.only(left: 12),
);
},
@@ -170,34 +138,23 @@ class _AddPortionWidgetState extends State<AddPortionWidget> {
child: Ink(
width: 52,
height: 52,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color(0xFFF6F6F6),
),
child: const Icon(
Icons.delete_outline_rounded,
color: Colors.red,
),
decoration: BoxDecoration(borderRadius: BorderRadius.circular(20), color: const Color(0xFFF6F6F6)),
child: const Icon(Icons.delete_outline_rounded, color: Colors.red),
),
),
if (widget.portionIndex != null) const SizedBox(width: 8),
InkWell(
onTap: () => addPortion(context),
borderRadius: BorderRadius.circular(20),
child: Ink(
width: MediaQuery.of(context).size.width - (widget.portionIndex == null ? 32 : 92),
height: 52,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: appTheme.blueA400,
),
child: Center(
child: Text(
widget.portionIndex == null ? 'Добавить' : 'Сохранить',
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
color: Colors.white,
Expanded(
child: InkWell(
key: AppKeys.recipeCreateScreenIngredientAddButton,
onTap: () => addPortion(context),
borderRadius: BorderRadius.circular(20),
child: Ink(
height: 52,
decoration: BoxDecoration(borderRadius: BorderRadius.circular(20), color: appTheme.blueA400),
child: Center(
child: Text(
widget.portionIndex == null ? 'Добавить' : 'Сохранить',
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Colors.white),
),
),
),
@@ -215,8 +172,8 @@ class _AddPortionWidgetState extends State<AddPortionWidget> {
var measurementUnits = selectedGlossary?.grInPortion == null
? Portion.pcs
: selectedGlossary?.grInPortion == 0
? Portion.grams
: Portion.pcs;
? Portion.grams
: Portion.pcs;
final glossary = selectedGlossary;
if (glossary != null) {
final [calories, carbohydrates, proteins, fats] = _getCPFC(glossary, measurementUnits);
@@ -229,12 +186,7 @@ class _AddPortionWidgetState extends State<AddPortionWidget> {
);
if (portionIndex == null) {
widget.createRecipeCubit.addIngredient(
Ingredient(
name: portion.name,
unit: portion.portion.getValue(),
portion: portion.quantity.toString(),
productId: glossary.id,
),
Ingredient(name: portion.name, unit: portion.portion.getValue(), portion: portion.quantity.toString(), productId: glossary.id),
);
if (context.mounted) {
Navigator.of(context).pop();
@@ -247,13 +199,8 @@ class _AddPortionWidgetState extends State<AddPortionWidget> {
useRootNavigator: true,
context: context,
builder: (context) => Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
child: GlossaryModerationRequestModalWidget(
productName: productNameController.text,
diaryCubit: sl<DiaryCubit>(),
),
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
child: GlossaryModerationRequestModalWidget(productName: productNameController.text, diaryCubit: sl<DiaryCubit>()),
),
);
if (newGlossary != null) {
@@ -268,12 +215,7 @@ class _AddPortionWidgetState extends State<AddPortionWidget> {
);
if (portionIndex == null) {
widget.createRecipeCubit.addIngredient(
Ingredient(
name: portion.name,
unit: portion.portion.getValue(),
portion: portion.quantity.toString(),
productId: newGlossary.id,
),
Ingredient(name: portion.name, unit: portion.portion.getValue(), portion: portion.quantity.toString(), productId: newGlossary.id),
);
if (context.mounted) {
Navigator.of(context).pop();
@@ -281,12 +223,7 @@ class _AddPortionWidgetState extends State<AddPortionWidget> {
} else {
widget.createRecipeCubit.updateIngredient(
index: portionIndex,
ingredient: Ingredient(
name: portion.name,
unit: portion.portion.getValue(),
portion: portion.quantity.toString(),
productId: newGlossary.id,
),
ingredient: Ingredient(name: portion.name, unit: portion.portion.getValue(), portion: portion.quantity.toString(), productId: newGlossary.id),
);
}
}

View File

@@ -1,3 +1,4 @@
import 'package:eatvio_app/app_keys.dart';
import 'package:eatvio_app/core/data/selectionPopupModel/selection_popup_model.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/widgets/custom_drop_down.dart';
@@ -46,125 +47,121 @@ class _InfoAboutRecipeWidgetState extends State<InfoAboutRecipeWidget> {
borderRadius: BorderRadius.circular(12),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Название'),
const SizedBox(height: 4),
BlocBuilder<CreateRecipeCubit, CreateRecipeState>(
bloc: widget.createRecipeCubit,
buildWhen: (previous, current) => previous.titleValidationError != current.titleValidationError,
builder: (context, state) {
return Column(
children: [
CustomTextFormField(
hintText: 'Например: тар-тар из говядины',
hasError: state.titleValidationError != null,
initialValue: state.entity.title,
onChanged: (value) {
widget.createRecipeCubit.replaceTitle(value);
if (state.titleValidationError != null) {
widget.createRecipeCubit.validateTitle();
}
},
),
if (state.titleValidationError != null) ...[
const SizedBox(height: 4),
ValidationErrorWidget(
error: state.titleValidationError!,
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Название'),
const SizedBox(height: 4),
BlocBuilder<CreateRecipeCubit, CreateRecipeState>(
bloc: widget.createRecipeCubit,
buildWhen: (previous, current) => previous.titleValidationError != current.titleValidationError,
builder: (context, state) {
return Column(
children: [
CustomTextFormField(
key: AppKeys.recipeCreateScreenTitleField,
hintText: 'Например: тар-тар из говядины',
hasError: state.titleValidationError != null,
initialValue: state.entity.title,
onChanged: (value) {
widget.createRecipeCubit.replaceTitle(value);
if (state.titleValidationError != null) {
widget.createRecipeCubit.validateTitle();
}
},
),
if (state.titleValidationError != null) ...[const SizedBox(height: 4), ValidationErrorWidget(error: state.titleValidationError!)],
],
],
);
},
),
const SizedBox(height: 12),
const Text('Тип блюда'),
const SizedBox(height: 4),
CustomDropDown(
items: items,
value: selectedType,
onChanged: (newSelectedType) {
setState(() {
selectedType = newSelectedType;
});
widget.createRecipeCubit.changeType(
TypeOfRecipe.fromString(selectedType.title) ?? TypeOfRecipe.other,
);
},
),
const SizedBox(height: 12),
const TagsWidget(),
const SizedBox(height: 12),
const PortionWidget(),
const SizedBox(height: 12),
const TimeOfCookWidget(),
const SizedBox(height: 12),
const Text('Описание'),
const SizedBox(height: 4),
BlocBuilder<CreateRecipeCubit, CreateRecipeState>(
buildWhen: (previous, current) => previous.descriptionValidationError != current.descriptionValidationError,
builder: (context, state) {
return Column(
children: [
CustomTextFormField(
hintText: 'Расскажите, почему вы выбрали именно этот рецепт? Опишите, каким будет готовое блюдо и в чём его достоинства.',
minLines: 5,
initialValue: state.entity.description,
maxLines: 5,
hasError: state.descriptionValidationError != null,
onChanged: (value) {
widget.createRecipeCubit.replaceDescription(value);
if (state.descriptionValidationError != null) {
widget.createRecipeCubit.validateDescription();
}
},
),
if (state.descriptionValidationError != null) ...[
const SizedBox(height: 4),
ValidationErrorWidget(
error: state.descriptionValidationError!,
);
},
),
const SizedBox(height: 12),
const Text('Тип блюда'),
const SizedBox(height: 4),
CustomDropDown(
key: AppKeys.recipeCreateScreenTypeDropdown,
items: items,
value: selectedType,
onChanged: (newSelectedType) {
setState(() {
selectedType = newSelectedType;
});
widget.createRecipeCubit.changeType(TypeOfRecipe.fromString(selectedType.title) ?? TypeOfRecipe.other);
},
),
const SizedBox(height: 12),
const TagsWidget(),
const SizedBox(height: 12),
const PortionWidget(),
const SizedBox(height: 12),
const TimeOfCookWidget(),
const SizedBox(height: 12),
const Text('Описание'),
const SizedBox(height: 4),
BlocBuilder<CreateRecipeCubit, CreateRecipeState>(
buildWhen: (previous, current) => previous.descriptionValidationError != current.descriptionValidationError,
builder: (context, state) {
return Column(
children: [
CustomTextFormField(
key: AppKeys.recipeCreateScreenDescriptionField,
hintText: 'Расскажите, почему вы выбрали именно этот рецепт? Опишите, каким будет готовое блюдо и в чём его достоинства.',
minLines: 5,
initialValue: state.entity.description,
maxLines: 5,
hasError: state.descriptionValidationError != null,
onChanged: (value) {
widget.createRecipeCubit.replaceDescription(value);
if (state.descriptionValidationError != null) {
widget.createRecipeCubit.validateDescription();
}
},
),
if (state.descriptionValidationError != null) ...[
const SizedBox(height: 4),
ValidationErrorWidget(error: state.descriptionValidationError!),
],
],
],
);
},
),
const SizedBox(height: 12),
const Text('Фото обложка'),
const SizedBox(height: 4),
BlocBuilder<CreateRecipeCubit, CreateRecipeState>(
buildWhen: (previous, current) => previous.imageValidationError != current.imageValidationError || previous.entity.image != current.entity.image,
builder: (context, state) {
return Column(
children: [
Container(
decoration: state.imageValidationError != null
? BoxDecoration(border: Border.all(width: 1, color: appTheme.red), borderRadius: BorderRadius.circular(8))
: null,
child: ImageWidget(image: state.entity.image),
),
if (state.imageValidationError != null) ...[
const SizedBox(height: 4),
ValidationErrorWidget(
error: state.imageValidationError!,
);
},
),
const SizedBox(height: 12),
const Text('Фото обложка'),
const SizedBox(height: 4),
BlocBuilder<CreateRecipeCubit, CreateRecipeState>(
buildWhen: (previous, current) =>
previous.imageValidationError != current.imageValidationError || previous.entity.image != current.entity.image,
builder: (context, state) {
return Column(
children: [
Container(
decoration: state.imageValidationError != null
? BoxDecoration(
border: Border.all(width: 1, color: appTheme.red),
borderRadius: BorderRadius.circular(8),
)
: null,
child: ImageWidget(key: AppKeys.recipeCreateScreenImageWidget, image: state.entity.image),
),
if (state.imageValidationError != null) ...[const SizedBox(height: 4), ValidationErrorWidget(error: state.imageValidationError!)],
],
],
);
},
),
const SizedBox(height: 12),
const Text('Ссылка на видео (если есть)'),
const SizedBox(height: 4),
CustomTextFormField(
hintText: 'Прикрепите ссылку на видео',
initialValue: widget.createRecipeCubit.state.entity.videoUrl,
onChanged: (value) {
widget.createRecipeCubit.replaceVideoUrl(value);
},
),
],
);
},
),
const SizedBox(height: 12),
const Text('Ссылка на видео (если есть)'),
const SizedBox(height: 4),
CustomTextFormField(
hintText: 'Прикрепите ссылку на видео',
initialValue: widget.createRecipeCubit.state.entity.videoUrl,
onChanged: (value) {
widget.createRecipeCubit.replaceVideoUrl(value);
},
),
],
),
),
),
);

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/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart';
import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_state.dart';
@@ -40,11 +41,7 @@ class _IngredientsWidgetState extends State<IngredientsWidget> {
padding: EdgeInsets.symmetric(horizontal: 16),
child: Text(
'Ингредиенты ',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Color(0xFF323F4B),
),
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600, color: Color(0xFF323F4B)),
),
),
ReorderableListView(
@@ -63,46 +60,29 @@ class _IngredientsWidgetState extends State<IngredientsWidget> {
ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 16),
key: Key('$index'),
leading: Icon(
Icons.drag_handle_rounded,
color: Colors.grey.shade600,
),
leading: Icon(Icons.drag_handle_rounded, color: Colors.grey.shade600),
title: Text(state.entity.ingredients[index].name),
subtitle: Text('${state.entity.ingredients[index].portion} ${state.entity.ingredients[index].unit == 'gr' ? 'гр' : 'шт'}'),
trailing: IconButton(
onPressed: () {
createRecipeCubit.removeIngredient(index);
},
icon: Icon(
Icons.delete_outline_rounded,
color: Colors.grey.shade600,
),
icon: Icon(Icons.delete_outline_rounded, color: Colors.grey.shade600),
),
),
],
),
ListTile(
key: AppKeys.recipeCreateScreenAddIngredientButton,
onTap: () {
nameController.clear();
gramsController.clear();
pcsController.clear();
_modalBottomSheet(
createRecipeCubit: createRecipeCubit,
);
_modalBottomSheet(createRecipeCubit: createRecipeCubit);
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
title: Text(
'Добавить ингредиент',
style: TextStyle(
color: appTheme.blueA400,
),
),
leading: Icon(
Icons.add_rounded,
color: appTheme.blueA400,
),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
title: Text('Добавить ингредиент', style: TextStyle(color: appTheme.blueA400)),
leading: Icon(Icons.add_rounded, color: appTheme.blueA400),
),
],
),
@@ -121,9 +101,7 @@ class _IngredientsWidgetState extends State<IngredientsWidget> {
return showModalBottomSheet(
useRootNavigator: true,
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
),
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(12))),
isScrollControlled: true,
builder: (context) {
return AddPortionWidget(

View File

@@ -1,3 +1,4 @@
import 'package:eatvio_app/app_keys.dart';
import 'package:eatvio_app/core/widgets/custom_text_form_field.dart';
import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart';
import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart';
@@ -39,12 +40,13 @@ class _PortionWidgetState extends State<PortionWidget> {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Кол-во порций'),
const Text('Количество порций'),
const SizedBox(height: 4),
Column(
children: [
CustomTextFormField(
hintText: '1',
key: AppKeys.recipeCreateScreenPortionsField,
hintText: 'Например: 1',
hasError: state.servingsValidationError != null,
initialValue: state.entity.countOfPortions?.toString(),
textInputType: TextInputType.number,
@@ -57,9 +59,7 @@ class _PortionWidgetState extends State<PortionWidget> {
),
if (state.servingsValidationError != null) ...[
const SizedBox(height: 4),
ValidationErrorWidget(
error: state.servingsValidationError!,
),
ValidationErrorWidget(error: state.servingsValidationError!),
],
],
),
@@ -72,11 +72,12 @@ class _PortionWidgetState extends State<PortionWidget> {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Ккал в одной порции'),
const Text('Калорийность'),
const SizedBox(height: 4),
Column(
children: [
CustomTextFormField(
key: AppKeys.recipeCreateScreenCaloriesField,
hintText: '100',
hasError: state.energyPerServingValidationError != null,
initialValue: state.entity.energyInOnePortion?.toString(),
@@ -91,9 +92,7 @@ class _PortionWidgetState extends State<PortionWidget> {
),
if (state.energyPerServingValidationError != null) ...[
const SizedBox(height: 4),
ValidationErrorWidget(
error: state.energyPerServingValidationError!,
),
ValidationErrorWidget(error: state.energyPerServingValidationError!),
],
],
),

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/widgets/custom_text_form_field.dart';
import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart';
@@ -22,107 +23,92 @@ class _StepsWidgetState extends State<StepsWidget> {
bloc: widget.createRecipeCubit,
builder: (BuildContext context, CreateRecipeState state) {
return Material(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Пошаговая инструкция',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Color(0xFF323F4B),
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Пошаговая инструкция',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600, color: Color(0xFF323F4B)),
),
),
const SizedBox(height: 12),
ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemBuilder: (context, index) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 4,
),
decoration: BoxDecoration(
color: appTheme.blueA400,
borderRadius: BorderRadius.circular(8),
),
child: Text(
'Шаг ${index + 1}',
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
),
),
),
GestureDetector(
onTap: () {
context.read<CreateRecipeCubit>().removeStep(state.entity.steps[index]);
},
child: const Icon(Icons.delete_outline_rounded),
),
],
),
const SizedBox(height: 12),
const Text('Описание'),
const SizedBox(height: 4),
CustomTextFormField(
hintText: 'Например: подготовьте ингредиенты',
initialValue: widget.createRecipeCubit.state.entity.steps[index].description,
maxLines: 5,
minLines: 3,
onChanged: (value) {
widget.createRecipeCubit.replaceDescriptionInStep(value, index);
},
),
const SizedBox(height: 12),
const Text('Фото шага'),
const SizedBox(height: 4),
StepImageWidget(
index: index,
createRecipeCubit: widget.createRecipeCubit,
),
],
),
itemCount: state.entity.steps.length,
separatorBuilder: (BuildContext context, int index) => const SizedBox(height: 24),
),
InkWell(
onTap: () {
context.read<CreateRecipeCubit>().addStep();
},
borderRadius: BorderRadius.circular(20),
child: Ink(
width: MediaQuery.of(context).size.width - 32,
decoration: BoxDecoration(
color: appTheme.blueA400,
borderRadius: BorderRadius.circular(20),
),
child: Container(
padding: const EdgeInsets.all(16),
alignment: Alignment.center,
child: const Text(
'Добавить шаг',
style: TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w600,
const SizedBox(height: 12),
InkWell(
key: AppKeys.recipeCreateScreenAddStepButton,
onTap: () {
context.read<CreateRecipeCubit>().addStep();
},
borderRadius: BorderRadius.circular(20),
child: Ink(
width: MediaQuery.of(context).size.width - 32,
decoration: BoxDecoration(color: appTheme.blueA400, borderRadius: BorderRadius.circular(20)),
child: Container(
padding: const EdgeInsets.all(16),
alignment: Alignment.center,
child: const Text(
'Добавить шаг',
style: TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.w600),
),
),
),
),
),
],
const SizedBox(height: 12),
ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemBuilder: (context, index) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
decoration: BoxDecoration(color: appTheme.blueA400, borderRadius: BorderRadius.circular(8)),
child: Text(
'Шаг ${index + 1}',
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
),
),
GestureDetector(
onTap: () {
context.read<CreateRecipeCubit>().removeStep(state.entity.steps[index]);
},
child: const Icon(Icons.delete_outline_rounded),
),
],
),
const SizedBox(height: 12),
const Text('Описание'),
const SizedBox(height: 4),
CustomTextFormField(
key: AppKeys.recipeCreateScreenStepDescriptionField,
hintText: 'Например: подготовьте ингредиенты',
initialValue: widget.createRecipeCubit.state.entity.steps[index].description,
maxLines: 5,
minLines: 3,
onChanged: (value) {
widget.createRecipeCubit.replaceDescriptionInStep(value, index);
},
),
const SizedBox(height: 12),
const Text('Фото шага'),
const SizedBox(height: 4),
StepImageWidget(
key: Key('${AppKeys.recipeCreateScreenStepImageWidget}_$index'),
index: index,
createRecipeCubit: widget.createRecipeCubit,
),
],
),
itemCount: state.entity.steps.length,
separatorBuilder: (BuildContext context, int index) => const SizedBox(height: 24),
),
],
),
),
),
);

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/widgets/custom_text_form_field.dart';
import 'package:eatvio_app/features/create_recipe/presentation/bloc/create_recipe_cubit/create_recipe_cubit.dart';
@@ -26,9 +27,11 @@ class _TagsWidgetState extends State<TagsWidget> {
const Text('Теги'),
const SizedBox(height: 4),
CustomTextFormField(
key: AppKeys.recipeCreateScreenTagField,
hintText: 'Например: без майонеза',
controller: tagController,
suffix: IconButton(
key: AppKeys.recipeCreateScreenAddTagButton,
onPressed: () {
if (tagController.text.isNotEmpty) {
context.read<CreateRecipeCubit>().addTag(tagController.text);
@@ -37,10 +40,7 @@ class _TagsWidgetState extends State<TagsWidget> {
});
}
},
icon: Icon(
Icons.done,
color: appTheme.blueA400,
),
icon: Icon(Icons.done, color: appTheme.blueA400),
),
),
const SizedBox(height: 12),
@@ -56,22 +56,13 @@ class _TagsWidgetState extends State<TagsWidget> {
borderRadius: BorderRadius.circular(16),
child: Ink(
padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 12),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
color: Colors.grey.shade200,
),
decoration: BoxDecoration(borderRadius: BorderRadius.circular(16), color: Colors.grey.shade200),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
state.entity.tags[i],
),
Text(state.entity.tags[i]),
const SizedBox(width: 4),
Icon(
Icons.delete_outline_rounded,
color: Colors.grey.shade600,
size: 20,
),
Icon(Icons.delete_outline_rounded, color: Colors.grey.shade600, size: 20),
],
),
),

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/widgets/custom_text_form_field.dart';
import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart';
@@ -43,20 +44,12 @@ class _TimeOfCookWidgetState extends State<TimeOfCookWidget> {
builder: (context) => const AlertDialog(
content: Text(
'Общее время приготовления - это период времени от начала приготовления блюда до подачи его на стол.',
style: TextStyle(
fontWeight: FontWeight.w500,
color: Color(0xFF323F4B),
height: 1.2,
),
style: TextStyle(fontWeight: FontWeight.w500, color: Color(0xFF323F4B), height: 1.2),
),
),
);
},
child: Icon(
Icons.help_outline_rounded,
color: appTheme.blueA400,
size: 20,
),
child: Icon(Icons.help_outline_rounded, color: appTheme.blueA400, size: 20),
),
],
),
@@ -66,9 +59,13 @@ class _TimeOfCookWidgetState extends State<TimeOfCookWidget> {
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Часы'),
const SizedBox(height: 4),
CustomTextFormField(
hintText: 'Часов',
key: AppKeys.recipeCreateScreenTotalHoursField,
hintText: '',
hasError: state.cookingTimeValidationError != null,
textInputType: TextInputType.number,
initialValue: state.entity.totalCookHours?.toString(),
@@ -83,9 +80,7 @@ class _TimeOfCookWidgetState extends State<TimeOfCookWidget> {
),
if (state.cookingTimeValidationError != null) ...[
const SizedBox(height: 4),
ValidationErrorWidget(
error: state.cookingTimeValidationError!,
),
ValidationErrorWidget(error: state.cookingTimeValidationError!),
],
],
),
@@ -93,9 +88,13 @@ class _TimeOfCookWidgetState extends State<TimeOfCookWidget> {
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Минуты'),
const SizedBox(height: 4),
CustomTextFormField(
hintText: 'Минут',
key: AppKeys.recipeCreateScreenTotalMinutesField,
hintText: '',
hasError: state.cookingTimeValidationError != null,
textInputType: TextInputType.number,
initialValue: state.entity.totalCookMinutes?.toString(),
@@ -110,9 +109,7 @@ class _TimeOfCookWidgetState extends State<TimeOfCookWidget> {
),
if (state.cookingTimeValidationError != null) ...[
const SizedBox(height: 4),
ValidationErrorWidget(
error: state.cookingTimeValidationError!,
),
ValidationErrorWidget(error: state.cookingTimeValidationError!),
],
],
),
@@ -131,20 +128,12 @@ class _TimeOfCookWidgetState extends State<TimeOfCookWidget> {
builder: (context) => const AlertDialog(
content: Text(
'Активное время приготовления - это период времени, требующий активного участия в приготовлении блюда. Оно включает мытье и очистку продуктов, нарезку, шинковку, взбивание, перемешивание, размешивание, перекладывание и т.п.',
style: TextStyle(
fontWeight: FontWeight.w500,
color: Color(0xFF323F4B),
height: 1.2,
),
style: TextStyle(fontWeight: FontWeight.w500, color: Color(0xFF323F4B), height: 1.2),
),
),
);
},
child: Icon(
Icons.help_outline_rounded,
color: appTheme.blueA400,
size: 20,
),
child: Icon(Icons.help_outline_rounded, color: appTheme.blueA400, size: 20),
),
],
),
@@ -154,9 +143,13 @@ class _TimeOfCookWidgetState extends State<TimeOfCookWidget> {
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Часы'),
const SizedBox(height: 4),
CustomTextFormField(
hintText: 'Часов',
key: AppKeys.recipeCreateScreenActiveHoursField,
hintText: '',
hasError: state.activeTimeValidationError != null,
initialValue: state.entity.activeCookHours?.toString(),
textInputType: TextInputType.number,
@@ -172,9 +165,7 @@ class _TimeOfCookWidgetState extends State<TimeOfCookWidget> {
),
if (state.activeTimeValidationError != null) ...[
const SizedBox(height: 4),
ValidationErrorWidget(
error: state.activeTimeValidationError!,
),
ValidationErrorWidget(error: state.activeTimeValidationError!),
],
],
),
@@ -182,9 +173,13 @@ class _TimeOfCookWidgetState extends State<TimeOfCookWidget> {
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Минуты'),
const SizedBox(height: 4),
CustomTextFormField(
hintText: 'Минут',
key: AppKeys.recipeCreateScreenActiveMinutesField,
hintText: '',
hasError: state.activeTimeValidationError != null,
initialValue: state.entity.activeCookMinutes?.toString(),
textInputType: TextInputType.number,
@@ -200,9 +195,7 @@ class _TimeOfCookWidgetState extends State<TimeOfCookWidget> {
),
if (state.activeTimeValidationError != null) ...[
const SizedBox(height: 4),
ValidationErrorWidget(
error: state.activeTimeValidationError!,
),
ValidationErrorWidget(error: state.activeTimeValidationError!),
],
],
),

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

@@ -0,0 +1,22 @@
import 'package:eatvio_app/features/diary/models/diary_day_model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'diary_day_entity.freezed.dart';
@freezed
abstract class DiaryDayEntity with _$DiaryDayEntity {
factory DiaryDayEntity({
@JsonKey(name: "id") required int id,
@JsonKey(name: "date") required String date,
@JsonKey(name: "wakeup") String? wakeup,
@JsonKey(name: "retire") String? retire,
@JsonKey(name: "closed") required int closed,
@JsonKey(name: "comment") required String comment,
@JsonKey(name: "state") required TypeOfDiaryModel typeOfDiary,
@JsonKey(name: "meals") required List<MealModel> meals,
@JsonKey(name: "chosen_plan_id") required int? chosenPlanId,
@JsonKey(name: "day_of_chosen_diet") required int? dayOfChosenDiet,
@JsonKey(name: "chosen_diet", fromJson: parseDiet) required DiaryDietModel? diet,
}) = _DiaryDayEntity;
}

View File

@@ -0,0 +1,18 @@
import 'package:eatvio_app/features/diary/models/diary_day_model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'diary_future_diet_day_entity.freezed.dart';
@freezed
abstract class DiaryFutureDietDayEntity with _$DiaryFutureDietDayEntity {
const factory DiaryFutureDietDayEntity({
required String date,
required TypeOfDiaryModel typeOfDiary,
required List<MealModel> meals,
required DiaryDietModel? diet,
required int? dayOfChosenDiet,
}) = _DiaryFutureDietDayEntity;
}

View File

@@ -0,0 +1,11 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'create_day_model.freezed.dart';
part 'create_day_model.g.dart';
@freezed
abstract class CreateDayModel with _$CreateDayModel {
factory CreateDayModel({required String day}) = _CreateDayModel;
factory CreateDayModel.fromJson(Map<String, dynamic> json) => _$CreateDayModelFromJson(json);
}

View File

@@ -1,4 +1,6 @@
import 'package:eatvio_app/features/consultations/models/consultation_model.dart';
import 'package:eatvio_app/features/diary/entities/diary_day_entity.dart';
import 'package:eatvio_app/features/diary/entities/diary_future_diet_day_entity.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'diary_day_model.freezed.dart';
@@ -30,7 +32,7 @@ abstract class DiaryDayWrapperModel with _$DiaryDayWrapperModel {
@freezed
abstract class DiaryDayModel with _$DiaryDayModel {
const factory DiaryDayModel({
@JsonKey(name: "id") required int id,
@JsonKey(name: "id") required int? id,
@JsonKey(name: "date") required String date,
@JsonKey(name: "wakeup") String? wakeup,
@JsonKey(name: "retire") String? retire,
@@ -40,26 +42,36 @@ abstract class DiaryDayModel with _$DiaryDayModel {
@JsonKey(name: "meals") required List<MealModel> meals,
@JsonKey(name: "chosen_plan_id") required int? chosenPlanId,
@JsonKey(name: "day_of_chosen_diet") required int? dayOfChosenDiet,
@JsonKey(name: "chosen_diet", fromJson: _parseDiet) required DiaryDietModel? diet,
@JsonKey(name: "chosen_diet", fromJson: parseDiet) required DiaryDietModel? diet,
}) = _DiaryDayModel;
const DiaryDayModel._();
factory DiaryDayModel.fromJson(Map<String, dynamic> json) => _$DiaryDayModelFromJson(json);
DiaryDayEntity? toEntity() {
if (id == null) {
return null;
}
return DiaryDayEntity(
id: id!,
date: date,
closed: closed,
comment: comment,
typeOfDiary: typeOfDiary,
meals: meals,
chosenPlanId: chosenPlanId,
dayOfChosenDiet: dayOfChosenDiet,
wakeup: wakeup,
retire: retire,
diet: diet,
);
}
DiaryFutureDietDayEntity toDiaryFutureDayEntity() {
return DiaryFutureDietDayEntity(date: date, typeOfDiary: typeOfDiary, meals: meals, dayOfChosenDiet: dayOfChosenDiet, diet: diet);
}
}
@freezed
abstract class DiaryFutureDietDayModel with _$DiaryFutureDietDayModel {
const factory DiaryFutureDietDayModel({
@JsonKey(name: "date") required String date,
@JsonKey(name: "state", fromJson: _parseDayTypeForFutureDay) required TypeOfDiaryModel typeOfDiary,
@JsonKey(name: "meals") required List<MealModel> meals,
@JsonKey(name: "chosen_diet", fromJson: _parseDiet) required DiaryDietModel? diet,
@JsonKey(name: "day_of_chosen_diet") required int? dayOfChosenDiet,
}) = _DiaryFutureDietDayModel;
factory DiaryFutureDietDayModel.fromJson(Map<String, dynamic> json) => _$DiaryFutureDietDayModelFromJson(json);
}
DiaryDietModel? _parseDiet(dynamic json) {
DiaryDietModel? parseDiet(dynamic json) {
if (json == null) return null;
return DiaryDietModel.fromJson(json['diet']);
}
@@ -71,10 +83,6 @@ abstract class DiaryDietModel with _$DiaryDietModel {
factory DiaryDietModel.fromJson(Map<String, dynamic> json) => _$DiaryDietModelFromJson(json);
}
TypeOfDiaryModel _parseDayTypeForFutureDay(dynamic json) {
return TypeOfDiaryModel(hasChosenDiet: json['has_chosen_diet'] as bool, hasChosenPlan: json['has_chosen_plan'] as bool, diaryState: DiaryStateEnum.init);
}
@freezed
abstract class MealModel with _$MealModel {
const factory MealModel({
@@ -141,7 +149,7 @@ abstract class TypeOfDiaryModel with _$TypeOfDiaryModel {
const factory TypeOfDiaryModel({
@JsonKey(name: "has_chosen_diet") required bool hasChosenDiet,
@JsonKey(name: "has_chosen_plan") required bool hasChosenPlan,
@JsonKey(name: "last_state") required DiaryStateEnum diaryState,
@JsonKey(name: "last_state") required DiaryStateEnum? diaryState,
}) = _TypeOfDiaryModel;
factory TypeOfDiaryModel.fromJson(Map<String, dynamic> json) => _$TypeOfDiaryModelFromJson(json);

View File

@@ -0,0 +1,11 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'get_day_model.freezed.dart';
part 'get_day_model.g.dart';
@freezed
abstract class GetDayModel with _$GetDayModel {
factory GetDayModel({required String day}) = _GetDayModel;
factory GetDayModel.fromJson(Map<String, dynamic> json) => _$GetDayModelFromJson(json);
}

View File

@@ -1,10 +1,13 @@
import 'dart:developer';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:eatvio_app/core/image_compressing/image_compress_utility.dart';
import 'package:eatvio_app/core/utils/date_time_utils.dart';
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
import 'package:eatvio_app/features/consultations/models/consultation_model.dart';
import 'package:eatvio_app/features/diary/entities/diary_day_entity.dart';
import 'package:eatvio_app/features/diary/entities/diary_future_diet_day_entity.dart';
import 'package:eatvio_app/features/diary/models/consultant_review_model.dart';
import 'package:eatvio_app/features/diary/models/diary_day_model.dart';
import 'package:eatvio_app/features/diary/models/nutrition_model.dart';
@@ -20,7 +23,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
class DiaryCubit extends Cubit<DiaryState> {
late final DateTime today;
late DateTime selectedDay;
late int selectedMeal;
int selectedMeal = 1;
final DiaryRepository diaryRepository;
final GlossaryRepository glossaryRepository;
final ProfileRepository profileRepository;
@@ -39,19 +42,79 @@ class DiaryCubit extends Cubit<DiaryState> {
today = DateTime.now();
selectedDay = today;
diaryRepository.forceFetchStream.listen((_) {
fetchDiary(true, diaryId);
fetchDiaryV2(needLoading: true, diaryId: diaryId);
});
}
String comment = '';
Future<bool?> setSelectedDay(DateTime day, {bool? forDietOnly}) async {
Future<bool> setSelectedDay(DateTime day) async {
final prevDay = selectedDay;
selectedDay = day;
if (forDietOnly ?? false) {
final result = await fetchDiaryForDietOnly();
return result;
final canSelect = await fetchDiaryV2(needLoading: true);
if (!canSelect) {
selectedDay = prevDay;
}
return canSelect;
}
Future<bool> fetchDiaryV2({bool needLoading = false, int? diaryId}) async {
final currentState = state;
if (needLoading) {
emit(const DiaryState.loading());
}
if (diaryId != null) {
final diaryDayById = await diaryRepository.getDiaryDay(diaryId);
final diaryEntity = diaryDayById.toEntity();
if (diaryEntity != null) {
setDiary(diaryDay: diaryEntity, diaryId: diaryId);
return true;
}
}
final diaryDay = await getDiary();
if (diaryDay == null) {
emit(const DiaryState.error(errorMessage: 'Diary not found'));
return true;
}
final diaryEntity = diaryDay.toEntity();
if (diaryEntity != null) {
setDiary(diaryDay: diaryEntity, diaryId: diaryId);
return true;
}
if (diaryDay.typeOfDiary.hasChosenDiet == true && diaryDay.typeOfDiary.diaryState == null) {
setDiaryForDietOnly(diaryDay.toDiaryFutureDayEntity());
return true;
}
emit(currentState);
return false;
}
Future<void> updateCurrentDiary() async {
try {
final diaryDay = await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
final diaryEntity = diaryDay.toEntity();
if (diaryEntity != null) {
setDiary(diaryDay: diaryEntity, diaryId: diaryId);
}
} catch (e) {
log(e.toString());
}
}
Future<DiaryDayModel?> getDiary() async {
try {
await diaryRepository.createDiaryDay(day: selectedDay.toISO8601WithTimeZoneOffset());
final diaryDay = await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
return diaryDay;
} on DioException catch (e) {
if (e.response?.statusCode == 422) {
final diaryDay = await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
return diaryDay;
}
}
await fetchDiary(true);
return null;
}
@@ -65,9 +128,7 @@ class DiaryCubit extends Cubit<DiaryState> {
}
}
Future<bool> fetchDiaryForDietOnly() async {
final stringDate = selectedDay.format('yyyy-MM-dd');
final diaryDay = await diaryRepository.getDiaryByDateForDietOnly(stringDate);
Future<bool> setDiaryForDietOnly(DiaryFutureDietDayEntity diaryDay) async {
if (!diaryDay.typeOfDiary.hasChosenDiet) {
return false;
}
@@ -146,22 +207,14 @@ class DiaryCubit extends Cubit<DiaryState> {
return false;
}
Future<void> fetchDiary([bool needLoading = false, int? diaryId, int? currentDay]) async {
Future<void> setDiary({int? diaryId, required DiaryDayEntity diaryDay}) async {
this.diaryId ??= diaryId;
final isConsultantView = this.diaryId != null;
if (needLoading) {
emit(const DiaryState.loading());
selectedMeal = 1;
}
try {
final DiaryDayModel diaryDay;
bool isMoodEnabled = false;
bool isWakeUpAndRetireTimeEnabled = false;
if (diaryId != null) {
diaryDay = await diaryRepository.getDiaryDay(diaryId);
} else {
final stringDate = selectedDay.format('yyyy-MM-dd');
diaryDay = await diaryRepository.getDiaryByDate(stringDate);
final profileSettings = await settingsRepository.getProfileSettings();
isMoodEnabled = profileSettings.isMoodFillable;
isWakeUpAndRetireTimeEnabled = profileSettings.isBedtimeFillable;
@@ -214,7 +267,7 @@ class DiaryCubit extends Cubit<DiaryState> {
Future<void> finishDiaryDay({required int diaryId, required String wakeUp, required String retire}) async {
await diaryRepository.finishDiaryDay(diaryId: diaryId, wakeUp: wakeUp, retire: retire, comment: comment.isEmpty ? null : comment);
await fetchDiary();
await updateCurrentDiary();
}
Future<NutritionDataModel> getNutrition(int index) async {
@@ -238,7 +291,7 @@ class DiaryCubit extends Cubit<DiaryState> {
quantity: quantity,
productNutritionalValueId: productNutritionalValueId,
);
await fetchDiary();
await updateCurrentDiary();
}
Future<void> updateProductInMeal({
@@ -272,27 +325,27 @@ class DiaryCubit extends Cubit<DiaryState> {
portionState: portionState,
);
}
await fetchDiary();
await updateCurrentDiary();
}
Future<void> markEaten({required int diaryId, required int mealId, required int portionId}) async {
await diaryRepository.markEaten(diaryId: diaryId, mealId: mealId, portionId: portionId);
await fetchDiary();
await updateCurrentDiary();
}
Future<void> unmarkEaten({required int diaryId, required int mealId, required int portionId}) async {
await diaryRepository.unmarkEaten(diaryId: diaryId, mealId: mealId, portionId: portionId);
await fetchDiary();
await updateCurrentDiary();
}
Future<void> restore({required int diaryId, required int mealId, required int portionId}) async {
await diaryRepository.restore(diaryId: diaryId, mealId: mealId, portionId: portionId);
await fetchDiary();
await updateCurrentDiary();
}
Future<void> deleteProductFromMeal({required int diaryId, required int mealId, required int portionId}) async {
await diaryRepository.deleteProductFromMeal(diaryId: diaryId, mealId: mealId, portionId: portionId);
await fetchDiary();
await updateCurrentDiary();
}
Future<List<GlossaryModel>> getGlossaryListByQuery(String query) async {
@@ -301,12 +354,12 @@ class DiaryCubit extends Cubit<DiaryState> {
Future<void> uploadPhotos({required List<File> files, required int diaryId}) async {
await diaryRepository.uploadPhotos(files: await ImageCompressUtility.compressFilesList(files), diaryId: diaryId, mealId: selectedMeal);
await fetchDiary();
await updateCurrentDiary();
}
Future<void> deletePhoto({required DiaryPhotoModel photo, required int diaryId}) async {
await diaryRepository.deletePhoto(photo: photo, diaryId: diaryId, mealId: selectedMeal);
await fetchDiary();
await updateCurrentDiary();
}
Future<GlossaryModerationModel?> sendProductToModeration({
@@ -326,30 +379,32 @@ class DiaryCubit extends Cubit<DiaryState> {
Future<void> fillTime({required int diaryId, required String time}) async {
await diaryRepository.fillTime(diaryId: diaryId, mealId: selectedMeal, time: time);
await fetchDiary();
await updateCurrentDiary();
}
Future<void> fillWakeup({required int diaryId, required String time}) async {
await diaryRepository.fillWakeup(diaryId: diaryId, time: time);
await fetchDiary();
await updateCurrentDiary();
}
Future<void> fillRetire({required int diaryId, required String time}) async {
await diaryRepository.fillRetire(diaryId: diaryId, time: time);
await fetchDiary();
await updateCurrentDiary();
}
Future<void> fillSatiety({required int diaryId, required int satiety}) async {
await diaryRepository.fillSatiety(diaryId: diaryId, mealId: selectedMeal, satiety: satiety);
await fetchDiary();
await updateCurrentDiary();
}
Future<void> fillMood({required int diaryId, required int mood}) async {
await diaryRepository.fillMood(diaryId: diaryId, mealId: selectedMeal, mood: mood);
await fetchDiary();
await updateCurrentDiary();
}
void fillComment(String comment) {
this.comment = comment;
}
}
enum DiaryFetchingErrors { canNotCreateFutureDays, dayAlreadyExists }

View File

@@ -1,5 +1,6 @@
import 'package:eatvio_app/features/diary/entities/diary_day_entity.dart';
import 'package:eatvio_app/features/diary/entities/diary_future_diet_day_entity.dart';
import 'package:eatvio_app/features/diary/models/consultant_review_model.dart';
import 'package:eatvio_app/features/diary/models/diary_day_model.dart';
import 'package:eatvio_app/features/diary/models/nutrition_model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
@@ -11,12 +12,10 @@ abstract class DiaryState with _$DiaryState {
const factory DiaryState.loading() = DiaryStateLoading;
const factory DiaryState.error({
required String errorMessage,
}) = DiaryStateError;
const factory DiaryState.error({required String errorMessage}) = DiaryStateError;
const factory DiaryState.loaded({
required DiaryDayModel diary,
required DiaryDayEntity diary,
required NutritionDataModel nutrition,
required DateTime selectedDay,
required int selectedMeal,
@@ -32,9 +31,6 @@ abstract class DiaryState with _$DiaryState {
@Default(false) bool isLoadingAddingProductInMeal,
}) = DiaryStateLoaded;
const factory DiaryState.loadedTomorrowWithDiet({
required DiaryFutureDietDayModel diary,
required DateTime selectedDay,
required int selectedMeal,
}) = DiaryStateLoadedTomorrowWithDiet;
const factory DiaryState.loadedTomorrowWithDiet({required DiaryFutureDietDayEntity diary, required DateTime selectedDay, required int selectedMeal}) =
DiaryStateLoadedTomorrowWithDiet;
}

View File

@@ -35,19 +35,12 @@ class DiaryScreen extends StatelessWidget {
class UserDiaryScreen extends StatelessWidget {
static const path = '/user-diary-screen';
static const name = 'userDiaryScreen';
const UserDiaryScreen({
super.key,
required this.diaryId,
required this.currentPlanDay,
});
const UserDiaryScreen({super.key, required this.diaryId, required this.currentPlanDay});
final int diaryId;
final int currentPlanDay;
@override
Widget build(BuildContext context) {
return DiaryScreenContent(
diaryId: diaryId,
currentPlanDay: currentPlanDay,
);
return DiaryScreenContent(diaryId: diaryId, currentPlanDay: currentPlanDay);
}
}
@@ -60,12 +53,8 @@ class DiaryScreenContent extends StatelessWidget {
final s = S.of(context);
return MultiBlocProvider(
providers: [
BlocProvider<DiaryCubit>(
create: (BuildContext context) => sl<DiaryCubit>()..fetchDiary(true, diaryId, currentPlanDay),
),
BlocProvider(
create: (context) => sl<ConsultantCommentsCubit>(),
),
BlocProvider<DiaryCubit>(create: (BuildContext context) => sl<DiaryCubit>()..fetchDiaryV2(needLoading: true, diaryId: diaryId)),
BlocProvider(create: (context) => sl<ConsultantCommentsCubit>()),
],
child: BlocBuilder<DiaryCubit, DiaryState>(
builder: (BuildContext context, DiaryState state) {
@@ -74,16 +63,14 @@ class DiaryScreenContent extends StatelessWidget {
}
if (state is DiaryStateError) {
return Scaffold(
body: DataErrorWidget(onReload: () => context.read<DiaryCubit>().fetchDiary(false, diaryId)),
body: DataErrorWidget(onReload: () => context.read<DiaryCubit>().fetchDiaryV2(needLoading: false, diaryId: diaryId)),
);
}
return Scaffold(
backgroundColor: Colors.grey.shade200,
appBar: diaryId == null
? AppBar(
toolbarHeight: 0,
)
? AppBar(toolbarHeight: 0)
: AppBar(
title: Text(
state is DiaryStateLoaded ? DateTime.parse(state.diary.date).toLocal().format('d MMMM') : '',
@@ -97,12 +84,7 @@ class DiaryScreenContent extends StatelessWidget {
child: Column(
children: [
if (diaryId == null) const CalendarWidget(),
if (state is DiaryStateLoading) ...[
const SizedBox(
height: 60,
),
const Loader()
],
if (state is DiaryStateLoading) ...[const SizedBox(height: 60), const Loader()],
if (state is DiaryStateLoaded)
WakeupAndRetireWidget(
isEnabled: state.diary.typeOfDiary.hasChosenPlan || state.isConsultantView || state.isWakeUpAndRetireEnabled,
@@ -114,40 +96,31 @@ class DiaryScreenContent extends StatelessWidget {
showMood: state.diary.typeOfDiary.hasChosenPlan || state.isConsultantView || state.isMoodEnabled,
showAddButton: !state.isConsultantView && !state.isDiaryFinished && !state.isDiaryCommented,
),
if (state is DiaryStateLoadedTomorrowWithDiet)
const MealWidget(
showMood: false,
showAddButton: false,
),
if (state is DiaryStateLoadedTomorrowWithDiet) const MealWidget(showMood: false, showAddButton: false),
if (state is DiaryStateLoaded) const CaloriesChartWidget(),
const SizedBox(height: 12),
Builder(builder: (context) {
if (state is DiaryStateLoaded && state.diary.typeOfDiary.hasChosenPlan) {
if (state.diary.comment.isNotEmpty) {
return CommentForConsultantWidget(
comment: state.diary.comment,
);
Builder(
builder: (context) {
if (state is DiaryStateLoaded && state.diary.typeOfDiary.hasChosenPlan) {
if (state.diary.comment.isNotEmpty) {
return CommentForConsultantWidget(comment: state.diary.comment);
}
if (state.isDiaryCommented || state.isDiaryFinished) {
return const SizedBox.shrink();
}
return const CommentForConsultantWidget();
}
if (state.isDiaryCommented || state.isDiaryFinished) {
return const SizedBox.shrink();
}
return const CommentForConsultantWidget();
}
return const SizedBox.shrink();
}),
return const SizedBox.shrink();
},
),
if (state is DiaryStateLoaded && !state.isConsultantView && !state.isDiaryFinished && !state.isDiaryCommented)
Padding(
padding: const EdgeInsets.only(top: 12),
child: FinishDayButtonWidget(
diaryDay: state.diary,
),
child: FinishDayButtonWidget(diaryDay: state.diary),
),
if (state is DiaryStateLoaded && state.isConsultantView && !state.isDiaryCommented) ...[
const SizedBox(height: 16),
const MainBackgroundBouble(
padding: EdgeInsets.all(16),
child: DayCommentWidget(),
)
const MainBackgroundBouble(padding: EdgeInsets.all(16), child: DayCommentWidget()),
],
if (state is DiaryStateLoaded && state.consultantReview?.consultantComments.dayComment != null) ...[
const SizedBox(height: 12),
@@ -155,10 +128,7 @@ class DiaryScreenContent extends StatelessWidget {
padding: const EdgeInsets.all(16),
child: Column(
children: [
Text(
s.dayComment,
style: TextStyles.textLSemibold.copyWith(color: appTheme.black),
),
Text(s.dayComment, style: TextStyles.textLSemibold.copyWith(color: appTheme.black)),
const SizedBox(height: 12),
CommentContainer(comment: state.consultantReview?.consultantComments.dayComment ?? ''),
],

View File

@@ -25,26 +25,30 @@ class _AddProductModalState extends State<AddProductModal> {
final quantityController = TextEditingController();
GlossaryModel? selectedGlossary;
List<GlossaryModel> glossariesList = [];
late final String? _previousProductName;
@override
void initState() {
super.initState();
if (widget.portion != null) {
_previousProductName = widget.portion!.productName;
productNameController.text = widget.portion!.productName;
quantityController.text = '${widget.portion!.quantity}';
selectedGlossary = GlossaryModel(
id: widget.portion!.id,
name: widget.portion!.productName,
grInPortion: widget.portion!.portion == 'gr' ? 0 : 1,
energyOn100Gr: 0,
proteinsOn100Gr: 0,
fatsOn100Gr: 0,
carbohydratesOn100Gr: 0,
energyOnPortion: 0,
proteinsOnPortion: 0,
fatsOnPortion: 0,
carbohydratesOnPortion: 0,
);
final productNutritionalValueId = widget.portion?.productNutritionalValueId;
if (productNutritionalValueId != null) {
selectedGlossary = GlossaryModel(
id: productNutritionalValueId,
name: widget.portion!.productName,
grInPortion: widget.portion!.portion == 'gr' ? 0 : 1,
energyOn100Gr: 0,
proteinsOn100Gr: 0,
fatsOn100Gr: 0,
carbohydratesOn100Gr: 0,
energyOnPortion: 0,
proteinsOnPortion: 0,
fatsOnPortion: 0,
carbohydratesOnPortion: 0,
);
}
}
}
@@ -191,7 +195,7 @@ class _AddProductModalState extends State<AddProductModal> {
);
}
Navigator.of(context).pop();
if (selectedGlossary == null) {
if (selectedGlossary == null && _previousProductName != productNameController.text) {
showModalBottomSheet(
isScrollControlled: true,
useRootNavigator: true,

View File

@@ -43,46 +43,24 @@ class _CalendarWidgetState extends State<CalendarWidget> {
locale: 'ru_RU',
startingDayOfWeek: StartingDayOfWeek.monday,
calendarFormat: _calendarFormat,
headerStyle: const HeaderStyle(
titleCentered: true,
formatButtonVisible: false,
leftChevronVisible: false,
rightChevronVisible: false,
),
headerStyle: const HeaderStyle(titleCentered: true, formatButtonVisible: false, leftChevronVisible: false, rightChevronVisible: false),
onDaySelected: (selectedDay, focusedDay) async {
if (!isSameDay(_selectedDay, selectedDay)) {
final today = DateTime.now();
if (selectedDay.isAfter(today)) {
if ((state is DiaryStateLoaded)) {
final result = await context.read<DiaryCubit>().setSelectedDay(_selectedDay, forDietOnly: true);
if (result == false && context.mounted) {
showErrorDialog(context, title: s.want_to_see_tomorrow, description: s.can_not_see_next_day);
return;
}
setState(() {
_selectedDay = selectedDay;
_focusedDay = focusedDay;
});
return;
}
if (state is DiaryStateLoadedTomorrowWithDiet) {
final result = await context.read<DiaryCubit>().setSelectedDay(_selectedDay, forDietOnly: true);
if (result == false && context.mounted) {
showErrorDialog(context, title: s.want_to_see_tomorrow, description: s.can_not_see_next_day);
return;
}
setState(() {
_selectedDay = selectedDay;
_focusedDay = focusedDay;
});
return;
}
}
final previousSelectedDay = _selectedDay;
final previousFocusedDay = _selectedDay;
setState(() {
_selectedDay = selectedDay;
_focusedDay = focusedDay;
});
context.read<DiaryCubit>().setSelectedDay(_selectedDay);
final canOpenNextDay = await context.read<DiaryCubit>().setSelectedDay(selectedDay);
if (!canOpenNextDay && context.mounted) {
showErrorDialog(context, title: s.want_to_see_tomorrow, description: s.can_not_see_next_day);
setState(() {
_selectedDay = previousSelectedDay;
_focusedDay = previousFocusedDay;
});
return;
}
}
},
selectedDayPredicate: (day) {
@@ -101,26 +79,12 @@ class _CalendarWidgetState extends State<CalendarWidget> {
}
},
calendarStyle: CalendarStyle(
weekendDecoration: const BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
defaultDecoration: const BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
selectedDecoration: BoxDecoration(
color: appTheme.blueA400,
shape: BoxShape.circle,
),
todayTextStyle: const TextStyle(
color: Colors.black,
),
weekendDecoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle),
defaultDecoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle),
selectedDecoration: BoxDecoration(color: appTheme.blueA400, shape: BoxShape.circle),
todayTextStyle: const TextStyle(color: Colors.black),
todayDecoration: BoxDecoration(
border: Border.all(
color: appTheme.blueA400,
width: 2,
),
border: Border.all(color: appTheme.blueA400, width: 2),
color: Colors.white,
shape: BoxShape.circle,
),
@@ -152,10 +116,7 @@ class _CalendarWidgetState extends State<CalendarWidget> {
child: Container(
width: double.infinity,
padding: const EdgeInsets.only(top: 8, bottom: 16),
child: Icon(
_calendarFormat == CalendarFormat.month ? Icons.keyboard_arrow_up_rounded : Icons.keyboard_arrow_down_rounded,
color: Colors.grey.shade600,
),
child: Icon(_calendarFormat == CalendarFormat.month ? Icons.keyboard_arrow_up_rounded : Icons.keyboard_arrow_down_rounded, color: Colors.grey.shade600),
),
);
}

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,11 +1,11 @@
import 'package:eatvio_app/features/diary/models/diary_day_model.dart';
import 'package:eatvio_app/features/diary/entities/diary_day_entity.dart';
import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class FinishDayButtonWidget extends StatefulWidget {
final DiaryDayModel diaryDay;
final DiaryDayEntity diaryDay;
const FinishDayButtonWidget({super.key, required this.diaryDay});

View File

@@ -9,11 +9,7 @@ class GlossaryModerationRequestModalWidget extends StatefulWidget {
final DiaryCubit diaryCubit;
final String productName;
const GlossaryModerationRequestModalWidget({
super.key,
required this.productName,
required this.diaryCubit,
});
const GlossaryModerationRequestModalWidget({super.key, required this.productName, required this.diaryCubit});
@override
State<GlossaryModerationRequestModalWidget> createState() => _GlossaryModerationRequestModalWidgetState();
@@ -55,21 +51,13 @@ class _GlossaryModerationRequestModalWidgetState extends State<GlossaryModeratio
const Text(
'Добавление нового продукта',
textAlign: TextAlign.center,
style: TextStyle(
color: Color(0xFF323F4B),
fontSize: 20,
fontWeight: FontWeight.w600,
),
style: TextStyle(color: Color(0xFF323F4B), fontSize: 20, fontWeight: FontWeight.w600),
),
const SizedBox(height: 16),
const Text(
'Оу... а у нас нет в базе калорийности такого продукта. Если вы знаете, давайте её запишем?',
textAlign: TextAlign.center,
style: TextStyle(
color: Color(0xFF323F4B),
fontSize: 14,
fontWeight: FontWeight.w400,
),
style: TextStyle(color: Color(0xFF323F4B), fontSize: 14, fontWeight: FontWeight.w400),
),
const SizedBox(height: 24),
Row(
@@ -77,25 +65,27 @@ class _GlossaryModerationRequestModalWidgetState extends State<GlossaryModeratio
children: [
Expanded(
child: InkWell(
onTap: () {
Navigator.pop(context);
onTap: () async {
glossary = (await widget.diaryCubit.sendProductToModeration(
name: productNameController.text,
energy: 0,
proteins: 0,
fats: 0,
carbohydrates: 0,
))?.glossary;
setState(() {
glossaryState = GlossaryState.success;
});
},
borderRadius: BorderRadius.circular(20),
child: Ink(
decoration: BoxDecoration(
color: const Color(0xFFF6F6F6),
borderRadius: BorderRadius.circular(20),
),
decoration: BoxDecoration(color: const Color(0xFFF6F6F6), borderRadius: BorderRadius.circular(20)),
child: Container(
padding: const EdgeInsets.all(16),
alignment: Alignment.center,
child: const Text(
'В другой раз',
style: TextStyle(
color: Color(0xFF6D6F71),
fontSize: 18,
fontWeight: FontWeight.w500,
),
'Отказаться',
style: TextStyle(color: Color(0xFF6D6F71), fontSize: 18, fontWeight: FontWeight.w500),
),
),
),
@@ -111,20 +101,13 @@ class _GlossaryModerationRequestModalWidgetState extends State<GlossaryModeratio
},
borderRadius: BorderRadius.circular(20),
child: Ink(
decoration: BoxDecoration(
color: appTheme.blueA400,
borderRadius: BorderRadius.circular(20),
),
decoration: BoxDecoration(color: appTheme.blueA400, borderRadius: BorderRadius.circular(20)),
child: Container(
padding: const EdgeInsets.all(16),
alignment: Alignment.center,
child: const Text(
'Записать',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w500,
),
style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w500),
),
),
),
@@ -146,18 +129,10 @@ class _GlossaryModerationRequestModalWidgetState extends State<GlossaryModeratio
const Text(
'Продукт успешно отправлен\nна модерацию',
textAlign: TextAlign.center,
style: TextStyle(
color: Color(0xFF323F4B),
fontSize: 20,
fontWeight: FontWeight.w600,
),
style: TextStyle(color: Color(0xFF323F4B), fontSize: 20, fontWeight: FontWeight.w600),
),
const SizedBox(height: 16),
Lottie.asset(
'assets/lottie_animations/success.json',
width: 160,
height: 160,
),
Lottie.asset('assets/lottie_animations/success.json', width: 160, height: 160),
const SizedBox(height: 16),
InkWell(
onTap: () {
@@ -165,20 +140,13 @@ class _GlossaryModerationRequestModalWidgetState extends State<GlossaryModeratio
},
borderRadius: BorderRadius.circular(20),
child: Ink(
decoration: BoxDecoration(
color: appTheme.blueA400,
borderRadius: BorderRadius.circular(20),
),
decoration: BoxDecoration(color: appTheme.blueA400, borderRadius: BorderRadius.circular(20)),
child: Container(
padding: const EdgeInsets.all(16),
alignment: Alignment.center,
child: const Text(
'Закрыть',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w500,
),
style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w500),
),
),
),
@@ -198,27 +166,16 @@ class _GlossaryModerationRequestModalWidgetState extends State<GlossaryModeratio
const Text(
'Добавление нового продукта',
textAlign: TextAlign.center,
style: TextStyle(
color: Color(0xFF323F4B),
fontSize: 20,
fontWeight: FontWeight.w600,
),
style: TextStyle(color: Color(0xFF323F4B), fontSize: 20, fontWeight: FontWeight.w600),
),
const SizedBox(height: 16),
const Text(
'Если у вас данные по нему\nпросим заполнить значения на 100гр.',
textAlign: TextAlign.center,
style: TextStyle(
color: Color(0xFF323F4B),
fontSize: 14,
fontWeight: FontWeight.w400,
),
style: TextStyle(color: Color(0xFF323F4B), fontSize: 14, fontWeight: FontWeight.w400),
),
const SizedBox(height: 24),
CustomTextFormField(
hintText: 'Сырный суп',
controller: productNameController,
),
CustomTextFormField(hintText: 'Сырный суп', controller: productNameController),
const SizedBox(height: 8),
Row(
mainAxisSize: MainAxisSize.min,
@@ -245,11 +202,7 @@ class _GlossaryModerationRequestModalWidgetState extends State<GlossaryModeratio
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: CustomTextFormField(
hintText: 'Жиры',
controller: fatsController,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
),
child: CustomTextFormField(hintText: 'Жиры', controller: fatsController, keyboardType: const TextInputType.numberWithOptions(decimal: true)),
),
const SizedBox(width: 8),
Expanded(
@@ -270,8 +223,7 @@ class _GlossaryModerationRequestModalWidgetState extends State<GlossaryModeratio
proteins: double.parse(proteinsController.text.replaceAll(',', '.')),
fats: double.parse(fatsController.text.replaceAll(',', '.')),
carbohydrates: double.parse(carbohydratesController.text.replaceAll(',', '.')),
))
?.glossary;
))?.glossary;
setState(() {
glossaryState = GlossaryState.success;
});
@@ -279,20 +231,13 @@ class _GlossaryModerationRequestModalWidgetState extends State<GlossaryModeratio
borderRadius: BorderRadius.circular(20),
child: Ink(
padding: const EdgeInsets.symmetric(horizontal: 8),
decoration: BoxDecoration(
color: appTheme.blueA400,
borderRadius: BorderRadius.circular(20),
),
decoration: BoxDecoration(color: appTheme.blueA400, borderRadius: BorderRadius.circular(20)),
child: Container(
padding: const EdgeInsets.all(16),
alignment: Alignment.center,
child: const Text(
'Сохранить',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
),
style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w600),
),
),
),

View File

@@ -1,11 +1,12 @@
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';
import 'package:eatvio_app/features/diary/entities/diary_day_entity.dart';
import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart';
import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart';
import 'package:eatvio_app/generated/l10n.dart';
@@ -34,7 +35,7 @@ class _PhotoGalleryWidgetState extends State<PhotoGalleryWidget> {
diaryCubit = context.read<DiaryCubit>();
}
void showImagePicker(DiaryDayModel diaryDay) {
void showImagePicker(DiaryDayEntity diaryDay) {
showCupertinoModalPopup<void>(
context: context,
builder: (context) {
@@ -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

@@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:io';
import 'package:eatvio_app/features/diary/models/consultant_comment_model.dart';
import 'package:eatvio_app/features/diary/models/consultant_review_model.dart';
import 'package:eatvio_app/features/diary/models/create_day_model.dart';
import 'package:eatvio_app/features/diary/models/diary_day_model.dart';
import 'package:eatvio_app/features/diary/models/finish_diary_day_model.dart';
import 'package:eatvio_app/features/diary/models/nutrition_model.dart';
@@ -69,14 +70,6 @@ class DiaryRepository {
}
}
Future<DiaryFutureDietDayModel> getDiaryByDateForDietOnly(String date) async {
try {
return (await diaryService.getDiaryIndexByDateForDietOnly(date: date)).last;
} catch (e) {
rethrow;
}
}
Future<List<DiaryDayModel>> getDiaryIndexByDate(String date) async {
return (await diaryService.getDiaryIndexByDate(date: date));
}
@@ -164,7 +157,7 @@ class DiaryRepository {
required PortionState portionState,
}) async {
Map<String, Object?> data = ProductInMeal(productName: productName, portion: portion, quantity: quantity).toJson();
data['product_nutritional_value_id'] = productNutritionalValueId;
if (productNutritionalValueId != null) data['product_nutritional_value_id'] = productNutritionalValueId;
data['state'] = portionState.name;
return await diaryService.updateProductInMeal(diary: diaryId, typeNo: mealId, portionModel: portionId, productInMeal: data);
}
@@ -300,4 +293,69 @@ class DiaryRepository {
rethrow;
}
}
Future<DiaryDayModel> getDiaryDayV2({required String day}) async {
try {
final diaryDay = await diaryService.getDiaryDayV2(day: day);
return setCPFCToDiary(diaryDay);
} catch (e) {
rethrow;
}
}
Future<void> createDiaryDay({required String day}) async {
try {
await diaryService.createDay(body: CreateDayModel(day: day));
await getDiaryByDate(day);
} catch (e) {
rethrow;
}
}
Future<DiaryDayModel> setCPFCToDiary(DiaryDayModel diaryDay) async {
Set<int> ids = {};
for (var meal in diaryDay.meals) {
for (var portion in meal.portions) {
if (portion.productNutritionalValueId != null) {
ids.add(portion.productNutritionalValueId!);
}
}
}
if (ids.isNotEmpty) {
final glossary = await getGlossariesIndex(ids: ids.toList());
final List<MealModel> updatedMeals = List.from(diaryDay.meals);
for (var mealIndex = 0; mealIndex < updatedMeals.length; mealIndex++) {
final meal = updatedMeals[mealIndex];
final updatedPortions = meal.portions.map((portion) {
if (portion.productNutritionalValueId != null) {
try {
final glossaryItem = glossary.glossariesList.firstWhere((g) => g.id == portion.productNutritionalValueId);
return portion.copyWith(
productCaloriesInfo: ProductCaloriesInfoModel(
id: glossaryItem.id,
productName: glossaryItem.name,
calories: glossaryItem.energyOn100Gr,
proteins: glossaryItem.proteinsOn100Gr,
fats: glossaryItem.fatsOn100Gr,
carbohydrates: glossaryItem.carbohydratesOn100Gr,
energyOnPortion: glossaryItem.energyOnPortion,
proteinsOnPortion: glossaryItem.proteinsOnPortion,
fatsOnPortion: glossaryItem.fatsOnPortion,
carbohydratesOnPortion: glossaryItem.carbohydratesOnPortion,
),
);
} catch (e) {
return portion;
}
}
return portion;
}).toList();
updatedMeals[mealIndex] = meal.copyWith(portions: updatedPortions);
}
final updatedDiaryDay = diaryDay.copyWith(meals: updatedMeals);
return updatedDiaryDay;
}
return diaryDay;
}
}

View File

@@ -2,6 +2,7 @@ import 'dart:io';
import 'package:dio/dio.dart';
import 'package:eatvio_app/features/diary/models/consultant_comment_model.dart';
import 'package:eatvio_app/features/diary/models/consultant_review_model.dart';
import 'package:eatvio_app/features/diary/models/create_day_model.dart';
import 'package:eatvio_app/features/diary/models/diary_day_model.dart';
import 'package:eatvio_app/features/diary/models/finish_diary_day_model.dart';
import 'package:eatvio_app/features/diary/models/nutrition_model.dart';
@@ -17,8 +18,6 @@ abstract class DiaryService {
@GET('/api/diary/index/{date}')
Future<List<DiaryDayModel>> getDiaryIndexByDate({@Path('date') required String date});
@GET('/api/diary/index/{date}')
Future<List<DiaryFutureDietDayModel>> getDiaryIndexByDateForDietOnly({@Path('date') required String date});
@GET('/api/diary/{diary}/show')
Future<DiaryDayWrapperModel> getDiaryDay({@Path('diary') required int diary});
@@ -103,4 +102,10 @@ abstract class DiaryService {
@GET('/api/glossaries/index')
Future<GlossaryPaginationModel> getGlossariesIndex({@Queries() Map<String, dynamic>? filters});
@POST('/api/v2/diary/create/day')
Future<void> createDay({@Body() required CreateDayModel body});
@GET('/api/v2/diary/index/{day?}')
Future<DiaryDayModel> getDiaryDayV2({@Query('day') required String day});
}

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';
@@ -18,7 +19,7 @@ class AuthorCard extends StatelessWidget {
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
GoRouter.of(context).pushNamed('profileScreen', extra: author);
GoRouter.of(context).pushNamed('profileScreen', extra: author.authorSlug);
},
child: Container(
width: MediaQuery.sizeOf(context).width,
@@ -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,4 +1,5 @@
import 'package:easy_debounce/easy_debounce.dart';
import 'package:eatvio_app/app_keys.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/views/cubit/views_cubit.dart';
import 'package:eatvio_app/core/widgets/add_item_button.dart';
@@ -215,7 +216,7 @@ class _FeedScreenContentState extends State<FeedScreenContent> {
3 when !hidePlans => AddItemButton(
onTap: state.profile?.roles.contains('consultant') ?? false ? () => GoRouter.of(context).pushNamed(CreatePlanScreen.name) : null,
),
_ => const AddItemButton(),
_ => const AddItemButton(key: AppKeys.feedScreenBlogPostCreationButton),
},
],
),

View File

@@ -1,13 +1,13 @@
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';
import 'package:eatvio_app/core/widgets/feed_icon_button.dart';
import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart';
import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_state.dart';
import 'package:eatvio_app/features/feed/presentation/widgets/subscribe_button_widget.dart';
@@ -59,14 +59,7 @@ class _BlogPostWidgetState extends State<BlogPostWidget> {
onTap: () {
GoRouter.of(context).pushNamed(
'profileScreen',
extra: Author(
authorSlug: state.feedBlogPostList[widget.index].author.authorSlug,
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,
authorIsMe: state.feedBlogPostList[widget.index].author.authorIsMe,
),
extra: state.feedBlogPostList[widget.index].author.authorSlug,
);
},
child: CircleAvatar(
@@ -75,7 +68,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 +150,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 +212,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';
@@ -8,7 +8,6 @@ import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/prof
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_state.dart';
import 'package:eatvio_app/features/complaining/presentation/complaining_bottom_sheet.dart';
import 'package:eatvio_app/features/feed/models/comment_model.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/core/comments/comments_cubit/comments_cubit.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
@@ -96,16 +95,11 @@ class _CommentsWidgetState extends State<CommentsWidget> {
onTap: () {
GoRouter.of(context).pushNamed(
'profileScreen',
extra: Author(
authorSlug: comment.authorSlug,
authorName: comment.authorName,
authorProfileIcon: comment.authorProfileIcon.contains('https') ? comment.authorProfileIcon : baseUrl + comment.authorProfileIcon,
authorIsMe: isMe,
),
extra: comment.authorSlug,
);
},
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,10 +1,7 @@
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';
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_state.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/features/feed/models/feed_consultant_model.dart';
import 'package:eatvio_app/features/profile/models/badge_model.dart';
import 'package:flutter/material.dart';
@@ -14,10 +11,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) {
@@ -25,21 +19,13 @@ class ConsultantWidget extends StatelessWidget {
onTap: () {
GoRouter.of(context).pushNamed(
'profileScreen',
extra: Author(
authorSlug: consultant.slug,
authorName: consultant.name,
authorProfileIcon: consultant.photo,
authorIsMe: (sl<ProfileAvatarCubit>().state as ProfileAvatarStateLoaded).profile.slug == consultant.slug ? true : false,
),
extra: consultant.slug,
);
},
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 +37,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 +70,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 +92,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,13 +1,13 @@
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';
import 'package:eatvio_app/core/widgets/feed_icon_button.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/features/feed/models/plan_pagination_model.dart';
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
@@ -61,7 +61,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,
@@ -169,12 +169,7 @@ class _PlanWidgetState extends State<PlanWidget> {
onTap: () {
GoRouter.of(context).pushNamed(
'profileScreen',
extra: Author(
authorSlug: widget.plan.author.authorSlug,
authorName: widget.plan.author.authorName,
authorProfileIcon: widget.plan.author.authorProfileIcon,
authorIsMe: widget.plan.author.authorIsMe,
),
extra: widget.plan.author.authorSlug,
);
},
child: Padding(
@@ -187,7 +182,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 +258,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

@@ -133,9 +133,9 @@ class FeedRepository {
}
}
Future<List<FeedConsultantModel>> getConsultants() async {
Future<List<FeedConsultantModel>> getConsultants([String? name]) async {
try {
return (await feedService.getConsultants()).data;
return (await feedService.getConsultants(name: name)).data;
} catch (e) {
rethrow;
}

View File

@@ -16,15 +16,10 @@ abstract class FeedService {
factory FeedService(Dio dio, {String baseUrl}) = _FeedService;
@GET('/api/blogPosts/index')
Future<FeedBlogPostSettingsModel> getBlogPostList({
@Query('page') required int page,
@Query('query_search') String? query,
});
Future<FeedBlogPostSettingsModel> getBlogPostList({@Query('page') required int page, @Query('query_search') String? query});
@GET('/api/blogPosts/show/{postId}')
Future<FeedBlogPostModel> getBlogPost({
@Path('postId') required int postId,
});
Future<FeedBlogPostModel> getBlogPost({@Path('postId') required int postId});
@GET('/api/recipes/index')
Future<RecipesPagination> getRecipes({
@@ -53,88 +48,50 @@ abstract class FeedService {
});
@GET('/api/blogPosts/{id}/comments/show')
Future<CommentModel> getBlogPostComments({
@Path() required String id,
});
Future<CommentModel> getBlogPostComments({@Path() required String id});
@POST('/api/blogPosts/{id}/comment/create')
Future<void> sendBlogPostComment({
@Path() required String id,
@Part() required String body,
@Part() int? parentCommentId,
});
Future<void> sendBlogPostComment({@Path() required String id, @Part() required String body, @Part() int? parentCommentId});
@GET('/api/diets/{id}/comments/show')
Future<CommentModel> getDietsComments({
@Path() required String id,
});
Future<CommentModel> getDietsComments({@Path() required String id});
@POST('/api/diets/{id}/comment/create')
Future<void> sendDietsComment({
@Path() required String id,
@Part() required String body,
@Part() int? parentCommentId,
});
Future<void> sendDietsComment({@Path() required String id, @Part() required String body, @Part() int? parentCommentId});
@GET('/api/plans/{slug}/comments/show')
Future<CommentModel> getPlansComments({
@Path() required String slug,
});
Future<CommentModel> getPlansComments({@Path() required String slug});
@POST('/api/plans/{slug}/comment/create')
Future<void> sendPlansComment({
@Path() required String slug,
@Part() required String body,
@Part() int? parentCommentId,
});
Future<void> sendPlansComment({@Path() required String slug, @Part() required String body, @Part() int? parentCommentId});
@GET('/api/recipes/{id}/comments/show')
Future<CommentModel> getRecipesComments({
@Path() required String id,
});
Future<CommentModel> getRecipesComments({@Path() required String id});
@POST('/api/recipes/{id}/comment/create')
Future<void> sendRecipesComment({
@Path() required String id,
@Part() required String body,
@Part() int? parentCommentId,
});
Future<void> sendRecipesComment({@Path() required String id, @Part() required String body, @Part() int? parentCommentId});
@POST('/api/blogPosts/{id}/like')
Future<void> likeBlogPost({
@Path() required int id,
});
Future<void> likeBlogPost({@Path() required int id});
@POST('/api/blogPosts/{id}/unliked')
Future<void> unlikedBlogPost({
@Path() required int id,
});
Future<void> unlikedBlogPost({@Path() required int id});
@GET('/api/consultants/index')
Future<FeedConsultantPaginationModel> getConsultants();
Future<FeedConsultantPaginationModel> getConsultants({@Query('filters[name][\$startsWith]') String? name});
@POST('/api/blogPosts/{id}/view')
Future<void> viewPost({
@Path() required int id,
});
Future<void> viewPost({@Path() required int id});
@POST('/api/recipes/{slug}/view')
Future<void> viewRecipe({
@Path() required String slug,
});
Future<void> viewRecipe({@Path() required String slug});
@POST('/api/diets/{id}/view')
Future<void> viewDiet({
@Path() required int id,
});
Future<void> viewDiet({@Path() required int id});
@POST('/api/plans/{slug}/view')
Future<void> viewPlan({
@Path() required String slug,
});
Future<void> viewPlan({@Path() required String slug});
@POST('/api/views')
Future<void> viewContent({
@Body() required ViewModel viewModel,
});
Future<void> viewContent({@Body() required ViewModel viewModel});
}

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/finance.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,5 +1,5 @@
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.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';
import 'package:flutter/material.dart';
@@ -20,20 +20,14 @@ class _BlockedUserWidgetState extends State<BlockedUserWidget> {
return InkWell(
onTap: () => GoRouter.of(context).pushNamed(
'profileScreen',
extra: Author(
authorSlug: widget.profile.slug,
authorName: widget.profile.name,
authorProfileIcon: widget.profile.profilePhotoUrl,
authorIsMe: false,
isEntitySubscribedByMe: false,
),
extra: widget.profile.slug,
),
child: Ink(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
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';
@@ -57,7 +58,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,
),
@@ -157,7 +158,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

@@ -5,7 +5,6 @@ import 'package:eatvio_app/core/image_compressing/image_compress_utility.dart';
import 'package:eatvio_app/core/utils/toasts.dart';
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_state.dart';
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
@@ -24,9 +23,11 @@ class ProfileCubit extends Cubit<ProfileState> {
emit(const ProfileState.loading());
try {
final profile = await profileRepository.getProfileBySlug(slug);
final myProfile = await profileRepository.getMyProfile();
emit(
ProfileState.loaded(
profile: profile,
isMyProfile: myProfile.slug == profile.slug,
profileDetails: await profileRepository.getProfileDetailsBySlug(slug),
blogPosts: await profileRepository.getBlogPostsByAuthorSlug(slug: slug),
consultantInfo: profile.roles.contains('consultant') ? await consultantRepository.getConsultantRequestStatus(slug) : null,
@@ -46,6 +47,7 @@ class ProfileCubit extends Cubit<ProfileState> {
emit(
ProfileState.loaded(
profile: profile,
isMyProfile: true,
profileDetails: await profileRepository.getMyProfileDetails(),
blogPosts: await profileRepository.getBlogPostsByAuthorSlug(slug: profile.slug),
weightPoints: await profileRepository.getWeight(period: period),
@@ -74,6 +76,7 @@ class ProfileCubit extends Cubit<ProfileState> {
weightPoints: (state as ProfileStateLoaded).weightPoints,
circumferencePoints: (state as ProfileStateLoaded).circumferencePoints,
consultantInfo: (state as ProfileStateLoaded).consultantInfo,
isMyProfile: (state as ProfileStateLoaded).isMyProfile,
),
);
}
@@ -100,11 +103,12 @@ class ProfileCubit extends Cubit<ProfileState> {
}
}
Future<String?> getChatRoomIdBySlug({required Author author}) async {
Future<String?> getChatRoomIdBySlug({required String slug}) async {
try {
final chatIdOrError = await chatRepository.getChatByUserSlug(author.authorSlug);
final chatIdOrError = await chatRepository.getChatByUserSlug(slug);
final userProfile = await profileRepository.getProfileBySlug(slug);
if (chatIdOrError == '404') {
AppRouter.navigatorKey.currentContext?.pushNamed('emptyChatScreen', extra: author);
AppRouter.navigatorKey.currentContext?.pushNamed('emptyChatScreen', extra: userProfile);
} else if (chatIdOrError == 'error') {
showErrorToast('Ошибка создания чата');
} else {

View File

@@ -14,9 +14,10 @@ abstract class ProfileState with _$ProfileState {
const factory ProfileState.loading() = ProfileStateLoading;
const factory ProfileState.loaded({
required ProfileModel profile,
required ProfileModel profile,
required ProfileDetailsModel profileDetails,
required List<FeedBlogPostModel> blogPosts,
required bool isMyProfile,
List<WeightModel>? weightPoints,
List<CircumferenceModel>? circumferencePoints,
ConsultationRequestModel? consultantInfo,

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';
@@ -12,7 +13,6 @@ import 'package:eatvio_app/core/widgets/loader.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/pages/photo_view_screen.dart';
import 'package:eatvio_app/features/complaining/presentation/complaining_bottom_sheet.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/features/feed/presentation/widgets/plan_widget.dart';
import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked_users_cubit.dart';
import 'package:eatvio_app/features/profile/models/circumference_model.dart';
@@ -43,9 +43,9 @@ import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart';
class ProfileScreen extends StatefulWidget {
final Author? author;
final String? slug;
const ProfileScreen({super.key, this.author});
const ProfileScreen({super.key, this.slug});
@override
State<ProfileScreen> createState() => _ProfileScreenState();
@@ -70,7 +70,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
@override
void initState() {
super.initState();
widget.author == null || widget.author!.authorIsMe ? profileCubit.getMyProfile() : profileCubit.getProfileBySlug(widget.author!.authorSlug);
widget.slug == null ? profileCubit.getMyProfile() : profileCubit.getProfileBySlug(widget.slug!);
}
@override
@@ -94,15 +94,37 @@ class _ProfileScreenState extends State<ProfileScreen> {
isFirstFetch = false;
}
return widget.author == null || widget.author!.authorIsMe ? _myProfileScreen(state) : _profileScreen(state);
// Проверяем, заблокировал ли пользователь меня
if (state.profile.isBlockedByUser) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Padding(
padding: const EdgeInsets.all(32.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.block, size: 64, color: Colors.grey[400]),
const SizedBox(height: 16),
Text(
'Пользователь ограничил доступ к своей странице',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500, color: Colors.grey[600]),
),
],
),
),
),
);
}
return state.isMyProfile ? _myProfileScreen(state) : _profileScreen(state);
} else if (state is ProfileStateError) {
return Scaffold(
appBar: AppBar(),
body: DataErrorWidget(
onReload: () async {
widget.author == null || widget.author!.authorIsMe
? await profileCubit.getMyProfile()
: await profileCubit.getProfileBySlug(widget.author!.authorSlug);
widget.slug == null ? await profileCubit.getMyProfile() : await profileCubit.getProfileBySlug(widget.slug!);
},
),
);
@@ -117,7 +139,17 @@ class _ProfileScreenState extends State<ProfileScreen> {
Scaffold _profileScreen(ProfileStateLoaded state) {
return Scaffold(
backgroundColor: Colors.grey.shade200,
appBar: AppBar(),
appBar: AppBar(
leading: BackButton(
onPressed: () {
if (context.canPop()) {
GoRouter.of(context).pop();
return;
}
GoRouter.of(context).go('/feed-screen');
},
),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -220,7 +252,18 @@ class _ProfileScreenState extends State<ProfileScreen> {
Scaffold _myProfileScreen(ProfileStateLoaded state) {
return Scaffold(
backgroundColor: Colors.grey.shade200,
appBar: AppBar(toolbarHeight: widget.author == null ? 0 : null),
appBar: AppBar(
toolbarHeight: widget.slug == null ? 0 : null,
leading: BackButton(
onPressed: () {
if (context.canPop()) {
GoRouter.of(context).pop();
return;
}
GoRouter.of(context).go('/feed-screen');
},
),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -414,7 +457,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
GoRouter.of(context).pushNamed('stepperBecomeConsultantScreen', extra: state.profile.slug);
},
child: Text(
widget.author == null || widget.author!.authorIsMe ? 'Редактировать' : '',
state.isMyProfile ? 'Редактировать' : '',
style: const TextStyle(color: Color(0xFF2F80ED), fontSize: 16, fontWeight: FontWeight.w500),
),
),
@@ -492,7 +535,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
GoRouter.of(context).pushNamed('stepperBecomeConsultantScreen', extra: state.profile.slug);
},
child: Text(
widget.author == null || widget.author!.authorIsMe ? 'Редактировать' : '',
state.isMyProfile ? 'Редактировать' : '',
style: const TextStyle(color: Color(0xFF2F80ED), fontSize: 16, fontWeight: FontWeight.w500),
),
),
@@ -655,7 +698,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 +710,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,10 +846,10 @@ 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) ...[
if (state.isMyProfile) ...[
_buildDivider(),
_buildCompactItem(
icon: 'assets/icons/edit_paint.svg',
@@ -885,7 +928,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,11 +1003,11 @@ 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),
);
},
),
if (widget.author != null) ...[
if (!state.isMyProfile) ...[
_buildDivider(),
_buildCompactItem(
icon: 'assets/icons/complain.svg',
@@ -973,12 +1016,12 @@ class _ProfileScreenState extends State<ProfileScreen> {
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (context) => ComplainingBottomSheet(complainedContentType: ComplainedContent.profile, slug: widget.author?.authorSlug),
builder: (context) => ComplainingBottomSheet(complainedContentType: ComplainedContent.profile, slug: widget.slug),
);
},
),
],
if (widget.author != null && !state.profile.isBlockedByMe) ...[
if (!state.isMyProfile && !state.profile.isBlockedByMe) ...[
_buildDivider(),
_buildCompactItem(
icon: 'assets/icons/complain.svg',
@@ -986,7 +1029,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
onTap: () {
isFirstFetch = true;
sl<BlockedUsersCubit>().blockUser(state.profile.slug);
widget.author == null || widget.author!.authorIsMe ? profileCubit.getMyProfile() : profileCubit.getProfileBySlug(widget.author!.authorSlug);
state.isMyProfile ? profileCubit.getMyProfile() : profileCubit.getProfileBySlug(state.profile.slug);
if (state.profile.roles.contains('consultant')) {
plansCubit.getPlans(state.profile.slug);
}
@@ -994,7 +1037,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
},
),
],
if (widget.author != null && state.profile.isBlockedByMe) ...[
if (!state.isMyProfile && state.profile.isBlockedByMe) ...[
_buildDivider(),
_buildCompactItem(
icon: 'assets/icons/complain.svg',
@@ -1002,7 +1045,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
onTap: () {
isFirstFetch = true;
sl<BlockedUsersCubit>().unblockUser(state.profile.slug);
widget.author == null || widget.author!.authorIsMe ? profileCubit.getMyProfile() : profileCubit.getProfileBySlug(widget.author!.authorSlug);
state.isMyProfile ? profileCubit.getMyProfile() : profileCubit.getProfileBySlug(state.profile.slug);
if (state.profile.roles.contains('consultant')) {
plansCubit.getPlans(state.profile.slug);
}
@@ -1065,7 +1108,7 @@ class _ProfileScreenState extends State<ProfileScreen> {
children: [
const SizedBox(width: 16),
GestureDetector(
onTap: () async => await profileCubit.getChatRoomIdBySlug(author: widget.author!),
onTap: () async => await profileCubit.getChatRoomIdBySlug(slug: widget.slug!),
child: Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(8),

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,6 +1,5 @@
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart';
import 'package:eatvio_app/features/profile/presentation/bloc/sub_cubit/sub_cubit.dart';
import 'package:flutter/material.dart';
@@ -15,13 +14,7 @@ class SubActionButtonWidget extends StatefulWidget {
final String name;
final String porfileIcon;
const SubActionButtonWidget({
super.key,
required this.subActionType,
required this.slug,
required this.name,
required this.porfileIcon,
});
const SubActionButtonWidget({super.key, required this.subActionType, required this.slug, required this.name, required this.porfileIcon});
@override
State<SubActionButtonWidget> createState() => _SubActionButtonWidgetState();
@@ -49,51 +42,25 @@ class _SubActionButtonWidgetState extends State<SubActionButtonWidget> {
borderRadius: BorderRadius.circular(8),
child: Ink(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: appTheme.blueA400,
),
decoration: BoxDecoration(borderRadius: BorderRadius.circular(8), color: appTheme.blueA400),
child: const Text(
'Подписаться',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w500,
color: Colors.white,
),
style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: Colors.white),
),
),
);
} else {
return InkWell(
onTap: () async {
GoRouter.of(context).pushNamed(
'chatScreen',
extra: {
'uuid': await sl<ProfileCubit>().getChatRoomIdBySlug(
author: Author(
authorSlug: widget.slug,
authorName: widget.name,
authorProfileIcon: widget.porfileIcon,
authorIsMe: false,
),
),
},
);
GoRouter.of(context).pushNamed('chatScreen', extra: {'uuid': await sl<ProfileCubit>().getChatRoomIdBySlug(slug: widget.slug)});
},
borderRadius: BorderRadius.circular(8),
child: Ink(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: const Color(0xFFF1F2F6),
),
decoration: BoxDecoration(borderRadius: BorderRadius.circular(8), color: const Color(0xFFF1F2F6)),
child: const Text(
'Сообщение',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w500,
color: Color(0xFF6D6F71),
),
style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: Color(0xFF6D6F71)),
),
),
);

View File

@@ -1,5 +1,5 @@
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart';
import 'package:eatvio_app/core/app_config.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/features/profile/models/sub_model.dart';
import 'package:eatvio_app/features/profile/presentation/widgets/sub_action_button_widget.dart';
import 'package:flutter/material.dart';
@@ -23,20 +23,14 @@ class _SubWidgetState extends State<SubWidget> {
return InkWell(
onTap: () => GoRouter.of(context).pushNamed(
'profileScreen',
extra: Author(
authorSlug: widget.subModel.slug,
authorName: widget.subModel.name,
authorProfileIcon: widget.subModel.profilePhotoUrl,
authorIsMe: false,
isEntitySubscribedByMe: false,
),
extra: widget.subModel.slug,
),
child: Ink(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
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,9 +1,12 @@
import 'package:eatvio_app/app_keys.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/prefs.dart';
import 'package:eatvio_app/core/prefs_keys.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/token_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:go_router/go_router.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
class WelcomeScreen extends StatefulWidget {
@@ -79,9 +82,10 @@ 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);
final sharedPreferences = sl<Prefs>();
await sharedPreferences.setBool(PrefsKeys.welcomeScreenWasShowed, true);
if (await TokenStorage.haveTokenInStorage()) {
goRouter.go('/feed-screen');
} else {