forked from eatvio/eatvio_app
Compare commits
13 Commits
09a00a41ad
...
issue-720
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0ac156307 | ||
|
|
4a9d45a18d | ||
|
|
65fabefdb9 | ||
|
|
f573bb28f8 | ||
|
|
20aca4b9a4 | ||
|
|
5354c3f517 | ||
| 17dbc1d5bf | |||
|
|
21492a1ad9 | ||
|
|
239ff675db | ||
|
|
fa6c2f9000 | ||
|
|
ae0c3a53be | ||
| 21555bfb10 | |||
|
|
b2433b87b6 |
@@ -53,6 +53,6 @@ class AppRouter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static void navigateToRegisterViaSocial({required AuthResultEntity authResult, required String provider}) {
|
static void navigateToRegisterViaSocial({required AuthResultEntity authResult, required String provider}) {
|
||||||
appRouter.goNamed('registerViaSocialScreen', extra: {'authResult': authResult, 'provider': provider});
|
appRouter.pushNamed('registerViaSocialScreen', extra: {'authResult': authResult, 'provider': provider});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,10 +44,15 @@ class ContentRoutes {
|
|||||||
builder: (context, state) {
|
builder: (context, state) {
|
||||||
final slug = state.uri.queryParameters['slug'];
|
final slug = state.uri.queryParameters['slug'];
|
||||||
if (slug != null) {
|
if (slug != null) {
|
||||||
return AboutDietScreen(slug: slug, index: null, navigateToComments: false);
|
return AboutDietScreen(id: null, slug: slug, index: null, navigateToComments: false);
|
||||||
}
|
}
|
||||||
final data = state.extra as Map<String, dynamic>;
|
final data = state.extra as Map<String, dynamic>;
|
||||||
return AboutDietScreen(slug: data['slug'] as String, index: data['index'] as int?, navigateToComments: data['navigateToComments'] as bool);
|
return AboutDietScreen(
|
||||||
|
id: data['id'] as int?,
|
||||||
|
slug: data['slug'] as String?,
|
||||||
|
index: data['index'] as int?,
|
||||||
|
navigateToComments: data['navigateToComments'] as bool,
|
||||||
|
);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
GoRoute(
|
GoRoute(
|
||||||
|
|||||||
15
lib/features/auth/models/oauth_login_request.dart
Normal file
15
lib/features/auth/models/oauth_login_request.dart
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
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({
|
||||||
|
required String provider,
|
||||||
|
@JsonKey(name: 'access_token') required String accessToken,
|
||||||
|
@JsonKey(name: 'refresh_token') required String refreshToken,
|
||||||
|
}) = _OAuthLoginRequest;
|
||||||
|
|
||||||
|
factory OAuthLoginRequest.fromJson(Map<String, dynamic> json) => _$OAuthLoginRequestFromJson(json);
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import 'dart:developer';
|
||||||
import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_state.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:eatvio_app/features/auth/repositories/auth_repository.dart';
|
||||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
@@ -7,6 +8,23 @@ class OAuthCubit extends Cubit<OAuthState> {
|
|||||||
|
|
||||||
OAuthCubit({required this.authRepository}) : super(const OAuthState());
|
OAuthCubit({required this.authRepository}) : super(const OAuthState());
|
||||||
|
|
||||||
|
Future<void> getOAuthLogin({required String provider, required String accessToken, required String refreshToken}) async {
|
||||||
|
try {
|
||||||
|
log('OAuthCubit: Starting OAuth login for provider: $provider');
|
||||||
|
emit(const OAuthState.loading());
|
||||||
|
log('OAuthCubit: Emitted loading state');
|
||||||
|
|
||||||
|
final tokenModel = await authRepository.getOAuthLogin(provider: provider, accessToken: accessToken, refreshToken: refreshToken);
|
||||||
|
log('OAuthCubit: Got token model: ${tokenModel.token}');
|
||||||
|
emit(OAuthState.loaded(token: tokenModel.token));
|
||||||
|
log('OAuthCubit: Emitted loaded state');
|
||||||
|
} catch (e) {
|
||||||
|
log('OAuthCubit: Error occurred: $e');
|
||||||
|
emit(OAuthState.error(errorMessage: e.toString()));
|
||||||
|
log('OAuthCubit: Emitted error state');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> getOAuthToken({
|
Future<void> getOAuthToken({
|
||||||
required String provider,
|
required String provider,
|
||||||
required String accessToken,
|
required String accessToken,
|
||||||
@@ -22,6 +40,7 @@ class OAuthCubit extends Cubit<OAuthState> {
|
|||||||
required int height,
|
required int height,
|
||||||
}) async {
|
}) async {
|
||||||
try {
|
try {
|
||||||
|
emit(const OAuthState.loading());
|
||||||
final token = await authRepository.getOAuthToken(
|
final token = await authRepository.getOAuthToken(
|
||||||
provider: provider,
|
provider: provider,
|
||||||
accessToken: accessToken,
|
accessToken: accessToken,
|
||||||
|
|||||||
@@ -16,6 +16,10 @@ import 'package:eatvio_app/core/widgets/custom_divider.dart';
|
|||||||
import 'package:eatvio_app/core/widgets/custom_text_form_field.dart';
|
import 'package:eatvio_app/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_cubit.dart';
|
||||||
import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_state.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/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/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
|
||||||
import 'package:eatvio_app/features/dev_tools/presentation/dev_tools_screen.dart';
|
import 'package:eatvio_app/features/dev_tools/presentation/dev_tools_screen.dart';
|
||||||
@@ -404,16 +408,29 @@ class _SocialButton extends StatelessWidget {
|
|||||||
|
|
||||||
void _onVkPressed() async {
|
void _onVkPressed() async {
|
||||||
try {
|
try {
|
||||||
|
log('VK button pressed');
|
||||||
final context = AppRouter.navigatorKey.currentContext;
|
final context = AppRouter.navigatorKey.currentContext;
|
||||||
if (context == null) return;
|
if (context == null) {
|
||||||
|
log('Context is null');
|
||||||
final authResult = await SocialAuthFacade.signInWithVkAndFetchProfile(context: context);
|
|
||||||
if (authResult == null) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
AppRouter.navigateToRegisterViaSocial(authResult: authResult, provider: 'vk');
|
|
||||||
|
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');
|
||||||
|
// Пробуем сначала авторизоваться через новый API
|
||||||
|
if (context.mounted) {
|
||||||
|
await _tryOAuthLogin(context, authResult, 'vk');
|
||||||
|
} else {
|
||||||
|
log('Context is not mounted');
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log(e.toString());
|
log('VK button error: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -426,7 +443,11 @@ void _onOkPressed() async {
|
|||||||
if (authResult == null) {
|
if (authResult == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
AppRouter.navigateToRegisterViaSocial(authResult: authResult, provider: 'ok');
|
|
||||||
|
// Пробуем сначала авторизоваться через новый API
|
||||||
|
if (context.mounted) {
|
||||||
|
await _tryOAuthLogin(context, authResult, 'ok');
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log(e.toString());
|
log(e.toString());
|
||||||
}
|
}
|
||||||
@@ -441,7 +462,11 @@ void _onMailRuPressed() async {
|
|||||||
if (authResult == null) {
|
if (authResult == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
AppRouter.navigateToRegisterViaSocial(authResult: authResult, provider: 'mailru');
|
|
||||||
|
// Пробуем сначала авторизоваться через новый API
|
||||||
|
if (context.mounted) {
|
||||||
|
await _tryOAuthLogin(context, authResult, 'mailru');
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log(e.toString());
|
log(e.toString());
|
||||||
}
|
}
|
||||||
@@ -449,14 +474,61 @@ void _onMailRuPressed() async {
|
|||||||
|
|
||||||
void _onYandexPressed() async {
|
void _onYandexPressed() async {
|
||||||
try {
|
try {
|
||||||
|
final context = AppRouter.navigatorKey.currentContext;
|
||||||
|
if (context == null) return;
|
||||||
|
|
||||||
final authResult = await SocialAuthFacade.signInWithYandex();
|
final authResult = await SocialAuthFacade.signInWithYandex();
|
||||||
if (authResult == null) return;
|
if (authResult == null) return;
|
||||||
AppRouter.navigateToRegisterViaSocial(authResult: authResult, provider: 'yandex');
|
|
||||||
|
// Пробуем сначала авторизоваться через новый API
|
||||||
|
if (context.mounted) {
|
||||||
|
await _tryOAuthLogin(context, authResult, 'yandex');
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log(e.toString());
|
log(e.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Пробует авторизоваться через новый OAuth login API
|
||||||
|
/// Если получает ошибку (включая 422 - пользователь не найден), переходит к регистрации
|
||||||
|
Future<void> _tryOAuthLogin(BuildContext context, AuthResultEntity authResult, String provider) async {
|
||||||
|
log('Starting OAuth login for provider: $provider');
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Создаем OAuth cubit
|
||||||
|
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) {
|
||||||
|
// Ошибка авторизации (включая 422 - пользователь не найден) - переходим к регистрации
|
||||||
|
log('OAuth login failed: ${state.errorMessage}');
|
||||||
|
subscription?.cancel();
|
||||||
|
AppRouter.navigateToRegisterViaSocial(authResult: authResult, provider: provider);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Пробуем авторизоваться
|
||||||
|
log('Calling getOAuthLogin with provider: $provider');
|
||||||
|
await oauthCubit.getOAuthLogin(provider: provider, accessToken: authResult.accessToken, refreshToken: authResult.refreshToken ?? '');
|
||||||
|
|
||||||
|
// Ждем немного, чтобы состояние успело обновиться
|
||||||
|
await Future.delayed(const Duration(milliseconds: 100));
|
||||||
|
} catch (e) {
|
||||||
|
// В случае любой ошибки (включая 422 - пользователь не найден) переходим к регистрации
|
||||||
|
log('OAuth login error in catch block: $e');
|
||||||
|
AppRouter.navigateToRegisterViaSocial(authResult: authResult, provider: provider);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _reconnectAfterAuth() async {
|
Future<void> _reconnectAfterAuth() async {
|
||||||
final context = AppRouter.navigatorKey.currentContext;
|
final context = AppRouter.navigatorKey.currentContext;
|
||||||
if (context == null) return;
|
if (context == null) return;
|
||||||
|
|||||||
@@ -31,8 +31,8 @@ class RegisterViaSocialScreen extends StatefulWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
|
class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
|
||||||
final maskFormatter = MaskTextInputFormatter(mask: '+7 (###) ### ## ##', filter: {"#": RegExp(r'[0-9]')});
|
final maskFormatter = MaskTextInputFormatter(mask: '+7 (###) ### ## ##', filter: {"#": RegExp(r'[0-9]')}, type: MaskAutoCompletionType.lazy);
|
||||||
final maskFormatterForBirthday = MaskTextInputFormatter(mask: '##.##.####', filter: {"#": RegExp(r'[0-9]')});
|
final maskFormatterForBirthday = MaskTextInputFormatter(mask: '##.##.####', filter: {"#": RegExp(r'[0-9]')}, type: MaskAutoCompletionType.lazy);
|
||||||
|
|
||||||
// Контроллеры для полей ввода
|
// Контроллеры для полей ввода
|
||||||
final firstNameController = TextEditingController();
|
final firstNameController = TextEditingController();
|
||||||
@@ -79,17 +79,6 @@ class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
|
|||||||
if (widget.authResult != null) {
|
if (widget.authResult != null) {
|
||||||
final authResult = widget.authResult!;
|
final authResult = widget.authResult!;
|
||||||
|
|
||||||
// Логируем полученные данные для отладки
|
|
||||||
print('AuthResult data:');
|
|
||||||
print('firstName: ${authResult.firstName}');
|
|
||||||
print('lastName: ${authResult.lastName}');
|
|
||||||
print('email: ${authResult.email}');
|
|
||||||
print('phone: ${authResult.phone}');
|
|
||||||
print('birthDate: ${authResult.birthDate}');
|
|
||||||
print('gender: ${authResult.gender}');
|
|
||||||
print('provider: ${widget.provider}');
|
|
||||||
|
|
||||||
// Предзаполняем поля из AuthResultEntity
|
|
||||||
if (authResult.firstName != null) {
|
if (authResult.firstName != null) {
|
||||||
firstNameController.text = authResult.firstName!;
|
firstNameController.text = authResult.firstName!;
|
||||||
}
|
}
|
||||||
@@ -100,10 +89,16 @@ class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
|
|||||||
emailController.text = authResult.email!;
|
emailController.text = authResult.email!;
|
||||||
}
|
}
|
||||||
if (authResult.phone != null) {
|
if (authResult.phone != null) {
|
||||||
phoneController.text = authResult.phone!;
|
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) {
|
if (authResult.birthDate != null) {
|
||||||
dateOfBirthController.text = _formatBirthDate(authResult.birthDate!);
|
final formattedDate = _formatBirthDate(authResult.birthDate!);
|
||||||
|
final maskedDate = maskFormatterForBirthday.maskText(formattedDate);
|
||||||
|
dateOfBirthController.text = maskedDate;
|
||||||
}
|
}
|
||||||
if (authResult.gender != null) {
|
if (authResult.gender != null) {
|
||||||
isMaleSelected = authResult.gender == GenderEnum.male;
|
isMaleSelected = authResult.gender == GenderEnum.male;
|
||||||
@@ -147,44 +142,6 @@ class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
|
|||||||
return birthDate;
|
return birthDate;
|
||||||
}
|
}
|
||||||
|
|
||||||
String _getProviderName(String? provider) {
|
|
||||||
switch (provider) {
|
|
||||||
case 'vk':
|
|
||||||
return 'ВКонтакте';
|
|
||||||
case 'yandex':
|
|
||||||
return 'Яндекс';
|
|
||||||
case 'ok':
|
|
||||||
return 'Одноклассники';
|
|
||||||
case 'mailru':
|
|
||||||
return 'Mail.ru';
|
|
||||||
default:
|
|
||||||
return 'социальной сети';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String _getDataStatusMessage(AuthResultEntity authResult) {
|
|
||||||
final hasEmail = authResult.email != null && authResult.email!.isNotEmpty;
|
|
||||||
final hasPhone = authResult.phone != null && authResult.phone!.isNotEmpty;
|
|
||||||
final hasBirthDate = authResult.birthDate != null && authResult.birthDate!.isNotEmpty;
|
|
||||||
|
|
||||||
if (hasEmail && hasPhone && hasBirthDate) {
|
|
||||||
return 'Все данные успешно получены и предзаполнены.';
|
|
||||||
} else if (hasEmail && hasPhone) {
|
|
||||||
return 'Email и номер телефона получены. Дата рождения может быть недоступна из-за настроек приватности.';
|
|
||||||
} else if (hasEmail) {
|
|
||||||
return 'Email получен. Номер телефона и дата рождения могут быть недоступны из-за настроек приватности.';
|
|
||||||
} else if (hasPhone) {
|
|
||||||
return 'Номер телефона получен. Email и дата рождения могут быть недоступны из-за настроек приватности.';
|
|
||||||
} else {
|
|
||||||
// Специальное сообщение для VK
|
|
||||||
if (widget.provider == 'vk') {
|
|
||||||
return 'Основные данные получены. Email запрашивается автоматически. Номер телефона получается через VK API. Если номер замаскирован, это означает, что пользователь ограничил доступ к нему в настройках приватности.';
|
|
||||||
} else {
|
|
||||||
return 'Основные данные получены. Email, номер телефона и дата рождения могут быть недоступны из-за настроек приватности.';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
firstNameController.dispose();
|
firstNameController.dispose();
|
||||||
@@ -202,15 +159,14 @@ class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
|
|||||||
return BlocProvider<OAuthCubit>(
|
return BlocProvider<OAuthCubit>(
|
||||||
create: (context) => CubitRegistrations.sl<OAuthCubit>(),
|
create: (context) => CubitRegistrations.sl<OAuthCubit>(),
|
||||||
child: Scaffold(
|
child: Scaffold(
|
||||||
appBar: AppBar(toolbarHeight: 0),
|
appBar: AppBar(),
|
||||||
body: BlocBuilder<OAuthCubit, OAuthState>(
|
body: BlocBuilder<OAuthCubit, OAuthState>(
|
||||||
builder: (context, state) {
|
builder: (context, state) {
|
||||||
return SingleChildScrollView(
|
return SingleChildScrollView(
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
const SizedBox(height: 24),
|
|
||||||
const Center(
|
const Center(
|
||||||
child: Text(
|
child: Text(
|
||||||
'Регистрация',
|
'Регистрация',
|
||||||
@@ -266,7 +222,10 @@ class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
|
|||||||
controller: phoneController,
|
controller: phoneController,
|
||||||
keyboardType: TextInputType.number,
|
keyboardType: TextInputType.number,
|
||||||
inputFormatters: [maskFormatter],
|
inputFormatters: [maskFormatter],
|
||||||
onChanged: (newValue) {},
|
onChanged: (newValue) {
|
||||||
|
// Дополнительная обработка изменений номера телефона
|
||||||
|
// Это поможет маске корректно работать при редактировании
|
||||||
|
},
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
Row(
|
Row(
|
||||||
@@ -503,6 +462,9 @@ class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Очищаем номер телефона от маски для отправки
|
||||||
|
final cleanPhone = phoneController.text.replaceAll(RegExp(r'[^\d+]'), '');
|
||||||
|
|
||||||
// Вызываем OAuth регистрацию
|
// Вызываем OAuth регистрацию
|
||||||
context.read<OAuthCubit>().getOAuthToken(
|
context.read<OAuthCubit>().getOAuthToken(
|
||||||
provider: widget.provider ?? 'social',
|
provider: widget.provider ?? 'social',
|
||||||
@@ -512,7 +474,7 @@ class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
|
|||||||
firstName: firstNameController.text,
|
firstName: firstNameController.text,
|
||||||
lastName: lastNameController.text,
|
lastName: lastNameController.text,
|
||||||
email: emailController.text,
|
email: emailController.text,
|
||||||
phone: phoneController.text,
|
phone: cleanPhone,
|
||||||
dateOfBirth: dateOfBirthController.text,
|
dateOfBirth: dateOfBirthController.text,
|
||||||
gender: isMaleSelected ? 'М' : 'Ж',
|
gender: isMaleSelected ? 'М' : 'Ж',
|
||||||
weight: weight,
|
weight: weight,
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import 'package:eatvio_app/features/auth/models/credentials_model.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_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/token_model.dart';
|
||||||
import 'package:eatvio_app/features/auth/services/auth_service.dart';
|
import 'package:eatvio_app/features/auth/services/auth_service.dart';
|
||||||
import 'package:eatvio_app/features/auth/models/social_exchange_request.dart';
|
import 'package:eatvio_app/features/auth/models/social_exchange_request.dart';
|
||||||
@@ -29,6 +30,16 @@ class AuthRepository {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<TokenModel> getOAuthLogin({required String provider, required String accessToken, required String refreshToken}) async {
|
||||||
|
try {
|
||||||
|
return await authService.getOAuthLogin(
|
||||||
|
body: OAuthLoginRequest(provider: provider, accessToken: accessToken, refreshToken: refreshToken),
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Future<String> getOAuthToken({
|
Future<String> getOAuthToken({
|
||||||
required String provider,
|
required String provider,
|
||||||
required String accessToken,
|
required String accessToken,
|
||||||
@@ -45,21 +56,22 @@ class AuthRepository {
|
|||||||
}) async {
|
}) async {
|
||||||
try {
|
try {
|
||||||
return (await authService.getOAuthToken(
|
return (await authService.getOAuthToken(
|
||||||
body: OAuthModel(
|
body: OAuthModel(
|
||||||
provider: provider,
|
provider: provider,
|
||||||
accessToken: accessToken,
|
accessToken: accessToken,
|
||||||
id: id,
|
id: id,
|
||||||
refreshToken: refreshToken,
|
refreshToken: refreshToken,
|
||||||
firstName: firstName,
|
firstName: firstName,
|
||||||
lastName: lastName,
|
lastName: lastName,
|
||||||
email: email,
|
email: email,
|
||||||
phone: phone,
|
phone: phone,
|
||||||
dateOfBirth: dateOfBirth,
|
dateOfBirth: dateOfBirth,
|
||||||
gender: gender == 'М' ? 'male' : 'female',
|
gender: gender == 'М' ? 'male' : 'female',
|
||||||
weight: weight,
|
weight: weight,
|
||||||
height: height,
|
height: height,
|
||||||
),
|
),
|
||||||
))['token']! as String;
|
))['token']!
|
||||||
|
as String;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
rethrow;
|
rethrow;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -119,7 +119,6 @@ class SocialAuthFacade {
|
|||||||
'response_type': 'code',
|
'response_type': 'code',
|
||||||
'client_id': clientId,
|
'client_id': clientId,
|
||||||
'redirect_uri': redirectUri,
|
'redirect_uri': redirectUri,
|
||||||
'scope': 'login:info login:email',
|
|
||||||
'force_confirm': 'true',
|
'force_confirm': 'true',
|
||||||
}).toString();
|
}).toString();
|
||||||
|
|
||||||
@@ -189,7 +188,7 @@ class SocialAuthFacade {
|
|||||||
try {
|
try {
|
||||||
final controller = VkIDController(clID: int.parse(clientIdStr));
|
final controller = VkIDController(clID: int.parse(clientIdStr));
|
||||||
|
|
||||||
final authUri = controller.generateAuthorizeLinkWithCodeVerifier(provider: provider);
|
final authUri = controller.generateAuthorizeLinkWithCodeVerifier(provider: provider, scopes: [VkScope.phone, VkScope.email,]);
|
||||||
final codeVerifier = authUri.key;
|
final codeVerifier = authUri.key;
|
||||||
final authUrl = authUri.value.toString();
|
final authUrl = authUri.value.toString();
|
||||||
final redirectScheme = 'vk$clientIdStr://';
|
final redirectScheme = 'vk$clientIdStr://';
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import 'package:dio/dio.dart';
|
import 'package:dio/dio.dart';
|
||||||
import 'package:eatvio_app/features/auth/models/credentials_model.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_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/token_model.dart';
|
||||||
import 'package:eatvio_app/features/auth/models/social_exchange_request.dart';
|
import 'package:eatvio_app/features/auth/models/social_exchange_request.dart';
|
||||||
import 'package:retrofit/retrofit.dart';
|
import 'package:retrofit/retrofit.dart';
|
||||||
@@ -12,17 +13,14 @@ abstract class AuthService {
|
|||||||
factory AuthService(Dio dio, {String? baseUrl}) = _AuthService;
|
factory AuthService(Dio dio, {String? baseUrl}) = _AuthService;
|
||||||
|
|
||||||
@POST('/api/login')
|
@POST('/api/login')
|
||||||
Future<TokenModel> getTokenByCredentials({
|
Future<TokenModel> getTokenByCredentials({@Body() required CredentialsModel credentials});
|
||||||
@Body() required CredentialsModel credentials,
|
|
||||||
});
|
|
||||||
|
|
||||||
@POST('/api/social/login')
|
@POST('/api/social/login')
|
||||||
Future<TokenModel> getTokenBySocial({
|
Future<TokenModel> getTokenBySocial({@Body() required SocialExchangeRequest body});
|
||||||
@Body() required SocialExchangeRequest body,
|
|
||||||
});
|
|
||||||
|
|
||||||
@POST('/api/oauth/callback')
|
@POST('/api/oauth/callback')
|
||||||
Future<Map<String, Object?>> getOAuthToken({
|
Future<Map<String, Object?>> getOAuthToken({@Body() required OAuthModel body});
|
||||||
@Body() required OAuthModel body,
|
|
||||||
});
|
@POST('/api/oauth/login')
|
||||||
|
Future<TokenModel> getOAuthLogin({@Body() required OAuthLoginRequest body});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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/custom_text_style.dart';
|
||||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||||
import 'package:eatvio_app/core/widgets/custom_divider.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:eatvio_app/generated/l10n.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
|
import 'package:go_router/go_router.dart';
|
||||||
|
|
||||||
class ChosenDietWidget extends StatelessWidget {
|
class ChosenDietWidget extends StatelessWidget {
|
||||||
const ChosenDietWidget({super.key});
|
const ChosenDietWidget({super.key});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return BlocBuilder<DiaryCubit, DiaryState>(builder: (context, state) {
|
return BlocBuilder<DiaryCubit, DiaryState>(
|
||||||
if (state is DiaryStateLoaded) {
|
builder: (context, state) {
|
||||||
if (state.diary.typeOfDiary.hasChosenDiet) {
|
if (state is DiaryStateLoaded) {
|
||||||
return ChosenDietWidgetContent(
|
if (state.diary.typeOfDiary.hasChosenDiet) {
|
||||||
currentDietDay: state.diary.dayOfChosenDiet ?? 0,
|
return ChosenDietWidgetContent(
|
||||||
dietName: state.diary.diet?.name ?? '',
|
currentDietDay: state.diary.dayOfChosenDiet ?? 0,
|
||||||
dietDuration: state.diary.diet?.duration ?? 0,
|
dietName: state.diary.diet?.name ?? '',
|
||||||
);
|
dietDuration: state.diary.diet?.duration ?? 0,
|
||||||
|
dietId: state.diary.diet?.id ?? 0,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
if (state is DiaryStateLoadedTomorrowWithDiet) {
|
||||||
if (state is DiaryStateLoadedTomorrowWithDiet) {
|
if (state.diary.typeOfDiary.hasChosenDiet) {
|
||||||
if (state.diary.typeOfDiary.hasChosenDiet) {
|
return Column(
|
||||||
return Column(
|
children: [
|
||||||
children: [
|
const CustomDivider(),
|
||||||
const CustomDivider(),
|
const SizedBox(height: 16),
|
||||||
const SizedBox(height: 16),
|
ChosenDietWidgetContent(
|
||||||
ChosenDietWidgetContent(
|
currentDietDay: state.diary.dayOfChosenDiet ?? 0,
|
||||||
currentDietDay: state.diary.dayOfChosenDiet ?? 0,
|
dietName: state.diary.diet?.name ?? '',
|
||||||
dietName: state.diary.diet?.name ?? '',
|
dietDuration: state.diary.diet?.duration ?? 0,
|
||||||
dietDuration: state.diary.diet?.duration ?? 0,
|
dietId: state.diary.diet?.id ?? 0,
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return const SizedBox.shrink();
|
return const SizedBox.shrink();
|
||||||
});
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ChosenDietWidgetContent extends StatelessWidget {
|
class ChosenDietWidgetContent extends StatelessWidget {
|
||||||
const ChosenDietWidgetContent({
|
const ChosenDietWidgetContent({super.key, required this.currentDietDay, required this.dietName, required this.dietDuration, required this.dietId});
|
||||||
super.key,
|
|
||||||
required this.currentDietDay,
|
|
||||||
required this.dietName,
|
|
||||||
required this.dietDuration,
|
|
||||||
});
|
|
||||||
final int currentDietDay;
|
final int currentDietDay;
|
||||||
final String dietName;
|
final String dietName;
|
||||||
final int dietDuration;
|
final int dietDuration;
|
||||||
|
final int dietId;
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final size = MediaQuery.sizeOf(context);
|
final size = MediaQuery.sizeOf(context);
|
||||||
final s = S.of(context);
|
final s = S.of(context);
|
||||||
return Column(
|
return GestureDetector(
|
||||||
children: [
|
onTap: () {
|
||||||
Row(
|
GoRouter.of(context).push(RouteConstants.aboutDietScreen, extra: {'id': dietId, 'navigateToComments': false});
|
||||||
children: [
|
},
|
||||||
SizedBox(
|
child: Column(
|
||||||
width: size.width * 0.4,
|
children: [
|
||||||
child: Text(dietName, style: TextStyles.textLMedium.copyWith(color: appTheme.black)),
|
Row(
|
||||||
),
|
children: [
|
||||||
const Spacer(),
|
SizedBox(
|
||||||
Container(
|
width: size.width * 0.4,
|
||||||
decoration: BoxDecoration(color: appTheme.dividerColor, borderRadius: BorderRadius.circular(12)),
|
child: Text(
|
||||||
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 12),
|
dietName,
|
||||||
child: Text('${s.day} $currentDietDay из $dietDuration', style: TextStyles.textMSemibold.copyWith(color: appTheme.gray)),
|
style: TextStyles.textLMedium.copyWith(color: appTheme.black, decoration: TextDecoration.underline),
|
||||||
)
|
),
|
||||||
],
|
),
|
||||||
),
|
const Spacer(),
|
||||||
const SizedBox(
|
Container(
|
||||||
height: 16,
|
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),
|
||||||
|
],
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,9 +19,14 @@ class AboutDietCubit extends Cubit<AboutDietState> {
|
|||||||
String? userStartedDietName;
|
String? userStartedDietName;
|
||||||
List<int> _selectedIndexes = [];
|
List<int> _selectedIndexes = [];
|
||||||
|
|
||||||
Future<void> getDiet(String slug, {int? index}) async {
|
Future<void> getDiet({String? slug, int? id, int? index}) async {
|
||||||
try {
|
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) {
|
if (index != null) {
|
||||||
dietsRepository.emitCommentsStateToFeed(CommentsState(index: index, totalComments: diet.totalComments));
|
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 {
|
try {
|
||||||
emit(const AboutDietState.loading());
|
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 chosenDiets = await profileRepository.getChosenDiets();
|
||||||
final lastChosenDiet = chosenDiets.firstOrNull;
|
final lastChosenDiet = chosenDiets.firstOrNull;
|
||||||
if (lastChosenDiet != null && ['inited', 'started'].contains(lastChosenDiet.state)) {
|
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);
|
_selectedIndexes = List.generate(diet.dailySchedule.length, (index) => 0);
|
||||||
emit(AboutDietState.loaded(
|
emit(AboutDietState.loaded(diet: diet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet, selectedIndexes: _selectedIndexes));
|
||||||
diet: diet,
|
|
||||||
isStarted: isCurrentDietStarted,
|
|
||||||
hasStartedDiet: hasStartedDiet,
|
|
||||||
selectedIndexes: _selectedIndexes,
|
|
||||||
));
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log(e.toString());
|
log(e.toString());
|
||||||
emit(AboutDietState.error(message: e.toString()));
|
emit(AboutDietState.error(message: e.toString()));
|
||||||
@@ -68,41 +74,30 @@ class AboutDietCubit extends Cubit<AboutDietState> {
|
|||||||
final currentDiet = (state as DietStateLoaded).diet;
|
final currentDiet = (state as DietStateLoaded).diet;
|
||||||
|
|
||||||
if (currentDiet.wasLikedByMe) {
|
if (currentDiet.wasLikedByMe) {
|
||||||
final updatedDiet = currentDiet.copyWith(
|
final updatedDiet = currentDiet.copyWith(totalLikes: currentDiet.totalLikes - 1, wasLikedByMe: false);
|
||||||
totalLikes: currentDiet.totalLikes - 1,
|
|
||||||
wasLikedByMe: false,
|
|
||||||
);
|
|
||||||
if (dietIndexInFeed != null) {
|
if (dietIndexInFeed != null) {
|
||||||
dietsRepository.emitLikesStateToFeed(LikesState(wasLikedByMe: updatedDiet.wasLikedByMe, totalLikes: updatedDiet.totalLikes, index: dietIndexInFeed));
|
dietsRepository.emitLikesStateToFeed(LikesState(wasLikedByMe: updatedDiet.wasLikedByMe, totalLikes: updatedDiet.totalLikes, index: dietIndexInFeed));
|
||||||
}
|
}
|
||||||
emit(AboutDietState.loaded(diet: updatedDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet, selectedIndexes: _selectedIndexes));
|
emit(AboutDietState.loaded(diet: updatedDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet, selectedIndexes: _selectedIndexes));
|
||||||
} else {
|
} else {
|
||||||
final updatedDiet = currentDiet.copyWith(
|
final updatedDiet = currentDiet.copyWith(totalLikes: currentDiet.totalLikes + 1, wasLikedByMe: true);
|
||||||
totalLikes: currentDiet.totalLikes + 1,
|
|
||||||
wasLikedByMe: true,
|
|
||||||
);
|
|
||||||
if (dietIndexInFeed != null) {
|
if (dietIndexInFeed != null) {
|
||||||
dietsRepository.emitLikesStateToFeed(LikesState(wasLikedByMe: updatedDiet.wasLikedByMe, totalLikes: updatedDiet.totalLikes, index: dietIndexInFeed));
|
dietsRepository.emitLikesStateToFeed(LikesState(wasLikedByMe: updatedDiet.wasLikedByMe, totalLikes: updatedDiet.totalLikes, index: dietIndexInFeed));
|
||||||
}
|
}
|
||||||
emit(AboutDietState.loaded(diet: updatedDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet, selectedIndexes: _selectedIndexes));
|
emit(AboutDietState.loaded(diet: updatedDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet, selectedIndexes: _selectedIndexes));
|
||||||
}
|
}
|
||||||
|
|
||||||
EasyDebounce.debounce(
|
EasyDebounce.debounce('like_diet', const Duration(seconds: 1), () async {
|
||||||
'like_diet',
|
try {
|
||||||
const Duration(seconds: 1),
|
await dietsRepository.likeDiet(id);
|
||||||
() async {
|
} catch (e) {
|
||||||
try {
|
log(e.toString());
|
||||||
await dietsRepository.likeDiet(id);
|
if (dietIndexInFeed != null) {
|
||||||
} catch (e) {
|
dietsRepository.emitLikesStateToFeed(LikesState(wasLikedByMe: currentDiet.wasLikedByMe, totalLikes: currentDiet.totalLikes, index: dietIndexInFeed));
|
||||||
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));
|
|
||||||
}
|
}
|
||||||
},
|
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes, diet: currentDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet));
|
||||||
);
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> addToFavorite(int id, int? dietIndex) async {
|
Future<void> addToFavorite(int id, int? dietIndex) async {
|
||||||
@@ -110,30 +105,24 @@ class AboutDietCubit extends Cubit<AboutDietState> {
|
|||||||
|
|
||||||
final currentDiet = (state as DietStateLoaded).diet;
|
final currentDiet = (state as DietStateLoaded).diet;
|
||||||
|
|
||||||
final updatedDiet = currentDiet.copyWith(
|
final updatedDiet = currentDiet.copyWith(isFavorite: true);
|
||||||
isFavorite: true,
|
|
||||||
);
|
|
||||||
if (dietIndex != null) {
|
if (dietIndex != null) {
|
||||||
dietsRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: updatedDiet.isFavorite, index: dietIndex));
|
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(
|
EasyDebounce.debounce('add_or_remove_diet_to_favorites', const Duration(seconds: 1), () async {
|
||||||
'add_or_remove_diet_to_favorites',
|
try {
|
||||||
const Duration(seconds: 1),
|
await dietsRepository.addToFavorite(id);
|
||||||
() async {
|
} catch (e) {
|
||||||
try {
|
log(e.toString());
|
||||||
await dietsRepository.addToFavorite(id);
|
showErrorToast('Произошла ошибка. Попробуйте ещё раз через некоторое время');
|
||||||
} catch (e) {
|
if (dietIndex != null) {
|
||||||
log(e.toString());
|
dietsRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: currentDiet.isFavorite, index: dietIndex));
|
||||||
showErrorToast('Произошла ошибка. Попробуйте ещё раз через некоторое время');
|
|
||||||
if (dietIndex != null) {
|
|
||||||
dietsRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: currentDiet.isFavorite, index: dietIndex));
|
|
||||||
}
|
|
||||||
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes,diet: currentDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet));
|
|
||||||
}
|
}
|
||||||
},
|
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes, diet: currentDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet));
|
||||||
);
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> removeFromFavorite(int id, int? dietIndex) async {
|
Future<void> removeFromFavorite(int id, int? dietIndex) async {
|
||||||
@@ -141,30 +130,24 @@ class AboutDietCubit extends Cubit<AboutDietState> {
|
|||||||
|
|
||||||
final currentDiet = (state as DietStateLoaded).diet;
|
final currentDiet = (state as DietStateLoaded).diet;
|
||||||
|
|
||||||
final updatedDiet = currentDiet.copyWith(
|
final updatedDiet = currentDiet.copyWith(isFavorite: false);
|
||||||
isFavorite: false,
|
|
||||||
);
|
|
||||||
if (dietIndex != null) {
|
if (dietIndex != null) {
|
||||||
dietsRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: updatedDiet.isFavorite, index: dietIndex));
|
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(
|
EasyDebounce.debounce('add_or_remove_diet_to_favorites', const Duration(seconds: 1), () async {
|
||||||
'add_or_remove_diet_to_favorites',
|
try {
|
||||||
const Duration(seconds: 1),
|
await dietsRepository.removeFromFavorite(id);
|
||||||
() async {
|
} catch (e) {
|
||||||
try {
|
log(e.toString());
|
||||||
await dietsRepository.removeFromFavorite(id);
|
showErrorToast('Произошла ошибка. Попробуйте ещё раз через некоторое время');
|
||||||
} catch (e) {
|
if (dietIndex != null) {
|
||||||
log(e.toString());
|
dietsRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: currentDiet.isFavorite, index: dietIndex));
|
||||||
showErrorToast('Произошла ошибка. Попробуйте ещё раз через некоторое время');
|
|
||||||
if (dietIndex != null) {
|
|
||||||
dietsRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: currentDiet.isFavorite, index: dietIndex));
|
|
||||||
}
|
|
||||||
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes,diet: currentDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet));
|
|
||||||
}
|
}
|
||||||
},
|
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes, diet: currentDiet, isStarted: isCurrentDietStarted, hasStartedDiet: hasStartedDiet));
|
||||||
);
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<bool> startDiet(DateTime date) async {
|
Future<bool> startDiet(DateTime date) async {
|
||||||
@@ -199,13 +182,13 @@ class AboutDietCubit extends Cubit<AboutDietState> {
|
|||||||
void clearStartedDietsState() {
|
void clearStartedDietsState() {
|
||||||
if (state is! DietStateLoaded) return;
|
if (state is! DietStateLoaded) return;
|
||||||
final diet = (state as DietStateLoaded).diet;
|
final diet = (state as DietStateLoaded).diet;
|
||||||
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes,diet: diet));
|
emit(AboutDietState.loaded(selectedIndexes: _selectedIndexes, diet: diet));
|
||||||
}
|
}
|
||||||
|
|
||||||
void emitCurrentStartedDietsState() {
|
void emitCurrentStartedDietsState() {
|
||||||
if (state is! DietStateLoaded) return;
|
if (state is! DietStateLoaded) return;
|
||||||
final diet = (state as DietStateLoaded).diet;
|
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 {
|
Future<Diet?> getDietBySlug(String slug) async {
|
||||||
|
|||||||
@@ -35,11 +35,12 @@ import 'package:flutter_svg/svg.dart';
|
|||||||
import 'package:go_router/go_router.dart';
|
import 'package:go_router/go_router.dart';
|
||||||
|
|
||||||
class AboutDietScreen extends StatefulWidget {
|
class AboutDietScreen extends StatefulWidget {
|
||||||
final String slug;
|
final String? slug;
|
||||||
|
final int? id;
|
||||||
final int? index;
|
final int? index;
|
||||||
final bool navigateToComments;
|
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
|
@override
|
||||||
State<AboutDietScreen> createState() => _AboutDietScreenState();
|
State<AboutDietScreen> createState() => _AboutDietScreenState();
|
||||||
@@ -79,7 +80,7 @@ class _AboutDietScreenState extends State<AboutDietScreen> {
|
|||||||
final s = S.of(context);
|
final s = S.of(context);
|
||||||
|
|
||||||
return BlocProvider(
|
return BlocProvider(
|
||||||
create: (context) => dietsCubit..initDietPage(widget.slug),
|
create: (context) => dietsCubit..initDietPage(slug: widget.slug, id: widget.id),
|
||||||
child: BlocProvider<CommentsCubit>(
|
child: BlocProvider<CommentsCubit>(
|
||||||
create: (BuildContext context) => commentsCubit,
|
create: (BuildContext context) => commentsCubit,
|
||||||
child: BlocConsumer<CommentsCubit, CommentsState>(
|
child: BlocConsumer<CommentsCubit, CommentsState>(
|
||||||
@@ -283,7 +284,7 @@ class _AboutDietScreenState extends State<AboutDietScreen> {
|
|||||||
replyId = null;
|
replyId = null;
|
||||||
});
|
});
|
||||||
Future.delayed(const Duration(milliseconds: 500), () {
|
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();
|
FocusManager.instance.primaryFocus?.unfocus();
|
||||||
}
|
}
|
||||||
@@ -526,7 +527,7 @@ class _AboutDietScreenState extends State<AboutDietScreen> {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
body: DataErrorWidget(
|
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),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,45 +38,25 @@ class AuthorCard extends StatelessWidget {
|
|||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
shape: BoxShape.circle,
|
shape: BoxShape.circle,
|
||||||
image: DecorationImage(
|
image: DecorationImage(
|
||||||
image: NetworkImage(sl<AppConfig>().baseUrl + author.authorProfileIcon),
|
image: NetworkImage(
|
||||||
|
author.authorProfileIcon.contains('https') ? author.authorProfileIcon : sl<AppConfig>().baseUrl + author.authorProfileIcon,
|
||||||
|
),
|
||||||
fit: BoxFit.cover,
|
fit: BoxFit.cover,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
subtitle: Text(
|
subtitle: Text(author.authorName, style: TextStyles.textLSemibold.copyWith(color: appTheme.black)),
|
||||||
author.authorName,
|
title: Text(title, style: titleStyle ?? TextStyles.textSSemibold.copyWith(color: appTheme.gray)),
|
||||||
style: TextStyles.textLSemibold.copyWith(
|
|
||||||
color: appTheme.black,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
title: Text(
|
|
||||||
title,
|
|
||||||
style: titleStyle ?? TextStyles.textSSemibold.copyWith(
|
|
||||||
color: appTheme.gray,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
Row(
|
Row(
|
||||||
children: [
|
children: [
|
||||||
Text(
|
Text('Консультант', style: TextStyles.textMMedium.copyWith(color: appTheme.black)),
|
||||||
'Консультант',
|
|
||||||
style: TextStyles.textMMedium.copyWith(
|
|
||||||
color: appTheme.black,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 10),
|
const SizedBox(width: 10),
|
||||||
if (author.authorPlaceInRating != null)
|
if (author.authorPlaceInRating != null)
|
||||||
InfoBouble(
|
InfoBouble(
|
||||||
radius: 12,
|
radius: 12,
|
||||||
backgroundColor: appTheme.whiteA700,
|
backgroundColor: appTheme.whiteA700,
|
||||||
children: [
|
children: [Text('${author.authorPlaceInRating}-й в рейтинге', style: TextStyles.textMMediumAuto.copyWith(color: appTheme.blueA400))],
|
||||||
Text(
|
|
||||||
'${author.authorPlaceInRating}-й в рейтинге',
|
|
||||||
style: TextStyles.textMMediumAuto.copyWith(
|
|
||||||
color: appTheme.blueA400,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -89,18 +69,8 @@ class AuthorCard extends StatelessWidget {
|
|||||||
child: Container(
|
child: Container(
|
||||||
width: 28,
|
width: 28,
|
||||||
height: 28,
|
height: 28,
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(color: appTheme.whiteA700, borderRadius: BorderRadius.circular(8)),
|
||||||
color: appTheme.whiteA700,
|
child: Center(child: SvgPicture.asset('assets/icons/arrow.svg', width: 12, height: 12, fit: BoxFit.none)),
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
),
|
|
||||||
child: Center(
|
|
||||||
child: SvgPicture.asset(
|
|
||||||
'assets/icons/arrow.svg',
|
|
||||||
width: 12,
|
|
||||||
height: 12,
|
|
||||||
fit: BoxFit.none,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -28,10 +28,9 @@ class S {
|
|||||||
static const AppLocalizationDelegate delegate = AppLocalizationDelegate();
|
static const AppLocalizationDelegate delegate = AppLocalizationDelegate();
|
||||||
|
|
||||||
static Future<S> load(Locale locale) {
|
static Future<S> load(Locale locale) {
|
||||||
final name =
|
final name = (locale.countryCode?.isEmpty ?? false)
|
||||||
(locale.countryCode?.isEmpty ?? false)
|
? locale.languageCode
|
||||||
? locale.languageCode
|
: locale.toString();
|
||||||
: locale.toString();
|
|
||||||
final localeName = Intl.canonicalizedLocale(name);
|
final localeName = Intl.canonicalizedLocale(name);
|
||||||
return initializeMessages(localeName).then((_) {
|
return initializeMessages(localeName).then((_) {
|
||||||
Intl.defaultLocale = localeName;
|
Intl.defaultLocale = localeName;
|
||||||
|
|||||||
Reference in New Issue
Block a user