From 79a6fcbd889d8a5f3e8e8ddd6da03abb39134676 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 4 Apr 2024 13:01:08 +0300 Subject: [PATCH 01/11] feat(chat): Initial directories for chat + BloC state manager stump --- lib/presentation/chat/chat_screen/bloc/chat_bloc.dart | 0 lib/presentation/chat/chat_screen/bloc/chat_event.dart | 0 lib/presentation/chat/chat_screen/bloc/chat_state.dart | 0 lib/presentation/chat/chat_screen/chat_screen.dart | 0 lib/presentation/chat/chat_screen/models/chat_model.dart | 0 .../chat/chat_select_screen/bloc/chat_select_bloc.dart | 0 .../chat/chat_select_screen/bloc/chat_select_event.dart | 0 .../chat/chat_select_screen/bloc/chat_select_state.dart | 0 lib/presentation/chat/chat_select_screen/chat_select_screen.dart | 0 .../chat/chat_select_screen/models/chat_select_model.dart | 0 10 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 lib/presentation/chat/chat_screen/bloc/chat_bloc.dart create mode 100644 lib/presentation/chat/chat_screen/bloc/chat_event.dart create mode 100644 lib/presentation/chat/chat_screen/bloc/chat_state.dart create mode 100644 lib/presentation/chat/chat_screen/chat_screen.dart create mode 100644 lib/presentation/chat/chat_screen/models/chat_model.dart create mode 100644 lib/presentation/chat/chat_select_screen/bloc/chat_select_bloc.dart create mode 100644 lib/presentation/chat/chat_select_screen/bloc/chat_select_event.dart create mode 100644 lib/presentation/chat/chat_select_screen/bloc/chat_select_state.dart create mode 100644 lib/presentation/chat/chat_select_screen/chat_select_screen.dart create mode 100644 lib/presentation/chat/chat_select_screen/models/chat_select_model.dart diff --git a/lib/presentation/chat/chat_screen/bloc/chat_bloc.dart b/lib/presentation/chat/chat_screen/bloc/chat_bloc.dart new file mode 100644 index 00000000..e69de29b diff --git a/lib/presentation/chat/chat_screen/bloc/chat_event.dart b/lib/presentation/chat/chat_screen/bloc/chat_event.dart new file mode 100644 index 00000000..e69de29b diff --git a/lib/presentation/chat/chat_screen/bloc/chat_state.dart b/lib/presentation/chat/chat_screen/bloc/chat_state.dart new file mode 100644 index 00000000..e69de29b diff --git a/lib/presentation/chat/chat_screen/chat_screen.dart b/lib/presentation/chat/chat_screen/chat_screen.dart new file mode 100644 index 00000000..e69de29b diff --git a/lib/presentation/chat/chat_screen/models/chat_model.dart b/lib/presentation/chat/chat_screen/models/chat_model.dart new file mode 100644 index 00000000..e69de29b diff --git a/lib/presentation/chat/chat_select_screen/bloc/chat_select_bloc.dart b/lib/presentation/chat/chat_select_screen/bloc/chat_select_bloc.dart new file mode 100644 index 00000000..e69de29b diff --git a/lib/presentation/chat/chat_select_screen/bloc/chat_select_event.dart b/lib/presentation/chat/chat_select_screen/bloc/chat_select_event.dart new file mode 100644 index 00000000..e69de29b diff --git a/lib/presentation/chat/chat_select_screen/bloc/chat_select_state.dart b/lib/presentation/chat/chat_select_screen/bloc/chat_select_state.dart new file mode 100644 index 00000000..e69de29b diff --git a/lib/presentation/chat/chat_select_screen/chat_select_screen.dart b/lib/presentation/chat/chat_select_screen/chat_select_screen.dart new file mode 100644 index 00000000..e69de29b diff --git a/lib/presentation/chat/chat_select_screen/models/chat_select_model.dart b/lib/presentation/chat/chat_select_screen/models/chat_select_model.dart new file mode 100644 index 00000000..e69de29b From 28d6525c7890a202fcb5b2f5ba5acfeadfb41281 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 4 Apr 2024 13:26:17 +0300 Subject: [PATCH 02/11] feat(chat): Classes added to chat select --- .../bloc/chat_select_bloc.dart | 21 +++++++++++++ .../bloc/chat_select_event.dart | 28 +++++++++++++++++ .../bloc/chat_select_state.dart | 31 +++++++++++++++++++ .../chat_select_screen.dart | 21 +++++++++++++ .../models/chat_select_model.dart | 16 ++++++++++ 5 files changed, 117 insertions(+) diff --git a/lib/presentation/chat/chat_select_screen/bloc/chat_select_bloc.dart b/lib/presentation/chat/chat_select_screen/bloc/chat_select_bloc.dart index e69de29b..1fbde95f 100644 --- a/lib/presentation/chat/chat_select_screen/bloc/chat_select_bloc.dart +++ b/lib/presentation/chat/chat_select_screen/bloc/chat_select_bloc.dart @@ -0,0 +1,21 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter/material.dart'; +import '/core/app_export.dart'; +import 'package:eatvio_app/presentation/chat/chat_select_screen/models/chat_select_model.dart'; +part 'chat_select_event.dart'; +part 'chat_select_state.dart'; + +/// A bloc that manages the state of a ChatSelect according to the event that is dispatched to it. +class ChatSelectBloc extends Bloc { + ChatSelectBloc(ChatSelectState initialState) : super(initialState) { + on(_onInitialize); + } + + _onInitialize( + ChatSelectInitialEvent event, + Emitter emit, + ) async { + emit(state.copyWith( + chatSelectModelObj: state.chatSelectModelObj?.copyWith())); + } +} diff --git a/lib/presentation/chat/chat_select_screen/bloc/chat_select_event.dart b/lib/presentation/chat/chat_select_screen/bloc/chat_select_event.dart index e69de29b..681736b1 100644 --- a/lib/presentation/chat/chat_select_screen/bloc/chat_select_event.dart +++ b/lib/presentation/chat/chat_select_screen/bloc/chat_select_event.dart @@ -0,0 +1,28 @@ +// ignore_for_file: must_be_immutable + +part of 'chat_select_bloc.dart'; + +/// Abstract class for all events that can be dispatched from the +///ChatSelect widget. +/// +/// Events must be immutable and implement the [Equatable] interface. +@immutable +abstract class ChatSelectEvent extends Equatable {} + +/// Event that is dispatched when the ChatSelect widget is first created. +class ChatSelectInitialEvent extends ChatSelectEvent { + @override + List get props => []; +} + +///event for dropdown selection +class ChangeDropDownEvent extends ChatSelectEvent { + ChangeDropDownEvent({required this.value}); + + SelectionPopupModel value; + + @override + List get props => [ + value, + ]; +} diff --git a/lib/presentation/chat/chat_select_screen/bloc/chat_select_state.dart b/lib/presentation/chat/chat_select_screen/bloc/chat_select_state.dart index e69de29b..7f56519e 100644 --- a/lib/presentation/chat/chat_select_screen/bloc/chat_select_state.dart +++ b/lib/presentation/chat/chat_select_screen/bloc/chat_select_state.dart @@ -0,0 +1,31 @@ +// ignore_for_file: must_be_immutable + +part of 'chat_select_bloc.dart'; + +/// Represents the state of ChatSelect in the application. +class ChatSelectState extends Equatable { + ChatSelectState({ + this.selectedDropDownValue, + this.chatSelectModelObj, + }); + + SelectionPopupModel? selectedDropDownValue; + + ChatSelectModel? chatSelectModelObj; + + @override + List get props => [ + selectedDropDownValue, + chatSelectModelObj, + ]; + ChatSelectState copyWith({ + SelectionPopupModel? selectedDropDownValue, + ChatSelectModel? chatSelectModelObj, + }) { + return ChatSelectState( + selectedDropDownValue: + selectedDropDownValue ?? this.selectedDropDownValue, + chatSelectModelObj: chatSelectModelObj ?? this.chatSelectModelObj, + ); + } +} diff --git a/lib/presentation/chat/chat_select_screen/chat_select_screen.dart b/lib/presentation/chat/chat_select_screen/chat_select_screen.dart index e69de29b..1959b70c 100644 --- a/lib/presentation/chat/chat_select_screen/chat_select_screen.dart +++ b/lib/presentation/chat/chat_select_screen/chat_select_screen.dart @@ -0,0 +1,21 @@ +import 'bloc/chat_select_bloc.dart'; +import 'models/chat_select_model.dart'; +import 'package:eatvio_app/core/app_export.dart'; +import 'package:flutter/material.dart'; + +class ChatSelectScreen extends StatelessWidget { + const ChatSelectScreen({Key? key}) : super(key: key); + static Widget builder(BuildContext context) { + return BlocProvider( + create: (context) => ChatSelectBloc( + ChatSelectState(chatSelectModelObj: ChatSelectModel())) + ..add(ChatSelectInitialEvent()), + child: ChatSelectScreen()); + } + + @override + Widget build(BuildContext context) { + mediaQueryData = MediaQuery.of(context); + return Container(); + } +} diff --git a/lib/presentation/chat/chat_select_screen/models/chat_select_model.dart b/lib/presentation/chat/chat_select_screen/models/chat_select_model.dart index e69de29b..e77aa4fe 100644 --- a/lib/presentation/chat/chat_select_screen/models/chat_select_model.dart +++ b/lib/presentation/chat/chat_select_screen/models/chat_select_model.dart @@ -0,0 +1,16 @@ +// ignore_for_file: must_be_immutable + +import 'package:equatable/equatable.dart'; + +/// This class defines the variables used in the [chat_select_screen], +/// and is typically used to hold data that is passed between different parts of the application. +class ChatSelectModel extends Equatable { + ChatSelectModel(); + + ChatSelectModel copyWith() { + return ChatSelectModel(); + } + + @override + List get props => []; +} From 8386bcf137552c4d4a485e8af03f2e9b9092a2d4 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 4 Apr 2024 13:28:15 +0300 Subject: [PATCH 03/11] feat(chat): Classes added to chat screen --- .../chat/chat_screen/bloc/chat_bloc.dart | 20 ++++++++++++ .../chat/chat_screen/bloc/chat_event.dart | 28 +++++++++++++++++ .../chat/chat_screen/bloc/chat_state.dart | 31 +++++++++++++++++++ .../chat/chat_screen/chat_screen.dart | 20 ++++++++++++ .../chat/chat_screen/models/chat_model.dart | 16 ++++++++++ 5 files changed, 115 insertions(+) diff --git a/lib/presentation/chat/chat_screen/bloc/chat_bloc.dart b/lib/presentation/chat/chat_screen/bloc/chat_bloc.dart index e69de29b..47ed9dec 100644 --- a/lib/presentation/chat/chat_screen/bloc/chat_bloc.dart +++ b/lib/presentation/chat/chat_screen/bloc/chat_bloc.dart @@ -0,0 +1,20 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter/material.dart'; +import '/core/app_export.dart'; +import 'package:eatvio_app/presentation/chat/chat_screen/models/chat_model.dart'; +part 'chat_event.dart'; +part 'chat_state.dart'; + +/// A bloc that manages the state of a Chat according to the event that is dispatched to it. +class ChatBloc extends Bloc { + ChatBloc(ChatState initialState) : super(initialState) { + on(_onInitialize); + } + + _onInitialize( + ChatInitialEvent event, + Emitter emit, + ) async { + emit(state.copyWith(chatModelObj: state.chatModelObj?.copyWith())); + } +} diff --git a/lib/presentation/chat/chat_screen/bloc/chat_event.dart b/lib/presentation/chat/chat_screen/bloc/chat_event.dart index e69de29b..a3778f98 100644 --- a/lib/presentation/chat/chat_screen/bloc/chat_event.dart +++ b/lib/presentation/chat/chat_screen/bloc/chat_event.dart @@ -0,0 +1,28 @@ +// ignore_for_file: must_be_immutable + +part of 'chat_bloc.dart'; + +/// Abstract class for all events that can be dispatched from the +///Chat widget. +/// +/// Events must be immutable and implement the [Equatable] interface. +@immutable +abstract class ChatEvent extends Equatable {} + +/// Event that is dispatched when the Chat widget is first created. +class ChatInitialEvent extends ChatEvent { + @override + List get props => []; +} + +///event for dropdown selection +class ChangeDropDownEvent extends ChatEvent { + ChangeDropDownEvent({required this.value}); + + SelectionPopupModel value; + + @override + List get props => [ + value, + ]; +} diff --git a/lib/presentation/chat/chat_screen/bloc/chat_state.dart b/lib/presentation/chat/chat_screen/bloc/chat_state.dart index e69de29b..20be159f 100644 --- a/lib/presentation/chat/chat_screen/bloc/chat_state.dart +++ b/lib/presentation/chat/chat_screen/bloc/chat_state.dart @@ -0,0 +1,31 @@ +// ignore_for_file: must_be_immutable + +part of 'chat_bloc.dart'; + +/// Represents the state of Chat in the application. +class ChatState extends Equatable { + ChatState({ + this.selectedDropDownValue, + this.chatModelObj, + }); + + SelectionPopupModel? selectedDropDownValue; + + ChatModel? chatModelObj; + + @override + List get props => [ + selectedDropDownValue, + chatModelObj, + ]; + ChatState copyWith({ + SelectionPopupModel? selectedDropDownValue, + ChatModel? chatModelObj, + }) { + return ChatState( + selectedDropDownValue: + selectedDropDownValue ?? this.selectedDropDownValue, + chatModelObj: chatModelObj ?? this.chatModelObj, + ); + } +} diff --git a/lib/presentation/chat/chat_screen/chat_screen.dart b/lib/presentation/chat/chat_screen/chat_screen.dart index e69de29b..e78a8f38 100644 --- a/lib/presentation/chat/chat_screen/chat_screen.dart +++ b/lib/presentation/chat/chat_screen/chat_screen.dart @@ -0,0 +1,20 @@ +import 'bloc/chat_bloc.dart'; +import 'models/chat_model.dart'; +import 'package:eatvio_app/core/app_export.dart'; +import 'package:flutter/material.dart'; + +class ChatScreen extends StatelessWidget { + const ChatScreen({Key? key}) : super(key: key); + static Widget builder(BuildContext context) { + return BlocProvider( + create: (context) => ChatBloc(ChatState(chatModelObj: ChatModel())) + ..add(ChatInitialEvent()), + child: ChatScreen()); + } + + @override + Widget build(BuildContext context) { + mediaQueryData = MediaQuery.of(context); + return Container(); + } +} diff --git a/lib/presentation/chat/chat_screen/models/chat_model.dart b/lib/presentation/chat/chat_screen/models/chat_model.dart index e69de29b..0e74b3ee 100644 --- a/lib/presentation/chat/chat_screen/models/chat_model.dart +++ b/lib/presentation/chat/chat_screen/models/chat_model.dart @@ -0,0 +1,16 @@ +// ignore_for_file: must_be_immutable + +import 'package:equatable/equatable.dart'; + +/// This class defines the variables used in the [chat_screen], +/// and is typically used to hold data that is passed between different parts of the application. +class ChatModel extends Equatable { + ChatModel(); + + ChatModel copyWith() { + return ChatModel(); + } + + @override + List get props => []; +} From c951558f2a09dc34338f3726399828511a97ff0e Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 5 Apr 2024 14:47:43 +0300 Subject: [PATCH 04/11] refactor(metrics): Refactoring cyclomatic complexity for code metrics --- .../bloc/diary_edit_bloc.dart | 276 +++++++++--------- 1 file changed, 145 insertions(+), 131 deletions(-) diff --git a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart index d3d9d29c..425515ed 100644 --- a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart +++ b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart @@ -46,140 +46,85 @@ class DiaryEditBloc extends Bloc { try { final token = "9|laravel_sanctum_KFXbccDcWEvTPfJmV99EQv1neAggmpR2TidVGDPN34fa201a"; - final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/index'), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - ); - if (response.statusCode == 200) { - final data = jsonDecode(response.body); - if (data is Map && data.containsKey('id')) { - final int diaryId = data['id']; - try { - final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/$diaryId/show/'), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - ); - final diary = jsonDecode(response.body)['diary']; - print("Screen load success"); - if (diary is Map) { - final String diaryDate = - diary['date'] ?? DateTime.now().toString(); - final responseChart = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + - '/diary/$diaryId/dailyNutritionData/'), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - ); - if (responseChart.statusCode == 200) { - final recommendedChartValues = jsonDecode( - responseChart.body)['dailyNutritionRecommendation']; - final consumedChartValues = - jsonDecode(responseChart.body)['dailyNutritionIntake']; - if (state is DiaryEditLoadedState) { - // Если текущее состояние уже загружено, обновляем его - var currentState = state as DiaryEditLoadedState; - emit((currentState).copyWith( - currentMeal: currentState.currentMeal, - wakeupExpanded: currentState.wakeupExpanded, - moodExpanded: currentState.moodExpanded, - moderationExpanded: currentState.moderationExpanded, - token: currentState.token, - meals: currentState.meals, - portions: currentState.portions, - photos: currentState.photos, - wakeupController: currentState.wakeupController, - retireController: currentState.retireController, - commentController: currentState.commentController, - mealTimeController: currentState.mealTimeController, - productNameController: currentState.productNameController, - caloriesController: currentState.caloriesController, - proteinsController: currentState.proteinsController, - fatsController: currentState.fatsController, - carbsController: currentState.carbsController, - selectedSatiety: currentState.selectedSatiety, - selectedMood: currentState.selectedMood, - diaryDate: currentState.diaryDate, - diaryId: currentState.diaryId, - productQuantityController: - currentState.productQuantityController, - recommendedChartValues: - currentState.recommendedChartValues, - consumedChartValues: currentState.consumedChartValues, - autocompleteList: currentState.autocompleteList, - diaryEditModelObj: currentState.diaryEditModelObj)); - } else { - // Если текущее состояние - начальное, создаем новое загруженное состояние - emit(DiaryEditLoadedState( - currentMeal: SelectionPopupModel( - id: 1, title: "Прием пищи 1", isSelected: true), - portionController: SelectionPopupModel( - id: 0, title: "порций", isSelected: true), - wakeupExpanded: true, - moodExpanded: true, - moderationExpanded: false, - token: token, - recommendedChartValues: recommendedChartValues.values - .map((value) => value as int) - .toList(), - consumedChartValues: consumedChartValues.values - .map((value) => value as int) - .toList() ?? - [0, 0, 0, 0], - meals: diary['meals'], - portions: diary['meals'][0]['portions'], - photos: diary['meals'][0]['photos'], - wakeupController: toTime(diary['wakeup'] ?? "09:00"), - retireController: toTime(diary['retire'] ?? "23:00"), - mealTimeController: - toTime(diary['meals'][0]['time'] ?? "10:00"), - selectedSatiety: diary['meals'][0]['satiety'], - selectedMood: diary['meals'][0]['mood'], - commentController: - TextEditingController(text: diary['comment']), - productNameController: TextEditingController(), - productQuantityController: TextEditingController(), - caloriesController: TextEditingController(), - proteinsController: TextEditingController(), - fatsController: TextEditingController(), - carbsController: TextEditingController(), - diaryId: diaryId, - diaryDate: diaryDate, - autocompleteList: [], - diaryEditModelObj: state.diaryEditModelObj?.copyWith( - mealList: fillMealList(), - portionList: fillPortions()))); - } - } else { - emit(DiaryEditErrorState( - 'Ошибка при декодировании данных КБЖУ')); - } - } else { - // Ошибка при декодировании JSON - emit(DiaryEditErrorState( - 'Ошибка при декодировании данных дневника')); - } - } catch (e) { - // Ошибка при получении данных дневника - emit(DiaryEditErrorState( - 'Ошибка при получении данных дневника: $e')); + final int diaryId = fetchDiaryId(token); + try { + final diary = fetchDiaryData(token, diaryId); + print("Screen load success"); + if (diary is Map) { + //final String diaryDate = diary['date'] ?? DateTime.now().toString(); + final chartValues = fetchChartValues(token, diaryId); + if (state is DiaryEditLoadedState) { + // Если текущее состояние уже загружено, обновляем его + var currentState = state as DiaryEditLoadedState; + emit((currentState).copyWith( + currentMeal: currentState.currentMeal, + wakeupExpanded: currentState.wakeupExpanded, + moodExpanded: currentState.moodExpanded, + moderationExpanded: currentState.moderationExpanded, + token: currentState.token, + meals: currentState.meals, + portions: currentState.portions, + photos: currentState.photos, + wakeupController: currentState.wakeupController, + retireController: currentState.retireController, + commentController: currentState.commentController, + mealTimeController: currentState.mealTimeController, + productNameController: currentState.productNameController, + caloriesController: currentState.caloriesController, + proteinsController: currentState.proteinsController, + fatsController: currentState.fatsController, + carbsController: currentState.carbsController, + selectedSatiety: currentState.selectedSatiety, + selectedMood: currentState.selectedMood, + diaryDate: currentState.diaryDate, + diaryId: currentState.diaryId, + productQuantityController: + currentState.productQuantityController, + recommendedChartValues: currentState.recommendedChartValues, + consumedChartValues: currentState.consumedChartValues, + autocompleteList: currentState.autocompleteList, + diaryEditModelObj: currentState.diaryEditModelObj)); + } else { + // Если текущее состояние - начальное, создаем новое загруженное состояние + emit(DiaryEditLoadedState( + currentMeal: SelectionPopupModel( + id: 1, title: "Прием пищи 1", isSelected: true), + portionController: SelectionPopupModel( + id: 0, title: "порций", isSelected: true), + wakeupExpanded: true, + moodExpanded: true, + moderationExpanded: false, + token: token, + recommendedChartValues: chartValues[0], + consumedChartValues: chartValues[1], + meals: diary['meals'], + portions: diary['meals'][0]['portions'], + photos: diary['meals'][0]['photos'], + wakeupController: toTime(diary['wakeup'] ?? "09:00"), + retireController: toTime(diary['retire'] ?? "23:00"), + mealTimeController: + toTime(diary['meals'][0]['time'] ?? "10:00"), + selectedSatiety: diary['meals'][0]['satiety'], + selectedMood: diary['meals'][0]['mood'], + commentController: + TextEditingController(text: diary['comment']), + productNameController: TextEditingController(), + productQuantityController: TextEditingController(), + caloriesController: TextEditingController(), + proteinsController: TextEditingController(), + fatsController: TextEditingController(), + carbsController: TextEditingController(), + diaryId: diaryId, + //diaryDate: diaryDate, + autocompleteList: [], + diaryEditModelObj: state.diaryEditModelObj?.copyWith( + mealList: fillMealList(), portionList: fillPortions()))); } - } else { - // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку - emit( - DiaryEditErrorState('Некоторые необходимые данные отсутствуют.')); } - } else { - // Статус ответа не равен 200, обрабатываем ошибку - emit(DiaryEditErrorState('Ошибка сервера: ${response.statusCode}')); + } catch (e) { + // Ошибка при получении данных дневника + emit(DiaryEditErrorState('Ошибка при получении данных дневника: $e')); } } catch (e) { // Ошибка при получении данных дневника @@ -187,6 +132,75 @@ class DiaryEditBloc extends Bloc { } } + fetchDiaryId(String token) async { + final response = await http.get( + Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/index'), + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer $token', + }, + ); + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + if (data is Map && data.containsKey('id')) { + final int diaryId = data['id']; + print("id"); + return diaryId; + } else { + emit(DiaryEditErrorState('Некоторые необходимые данные отсутствуют.')); + print('fail'); + return -1; + } + } else { + emit(DiaryEditErrorState('Ошибка сервера: ${response.statusCode}')); + print('fail'); + return -1; + } + } + + fetchDiaryData(String token, int diaryId) async { + final response = await http.get( + Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/$diaryId/show/'), + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer $token', + }, + ); + final diary = jsonDecode(response.body)['diary']; + print("data"); + + return diary; + } + + fetchChartValues(String token, int diaryID) async { + final responseChart = await http.get( + Uri.parse( + dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/dailyNutritionData/'), + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer $token', + }, + ); + if (responseChart.statusCode == 200) { + final recommendedChartValues = + jsonDecode(responseChart.body)['dailyNutritionRecommendation'] + .values + .map((value) => value as int) + .toList(); + final consumedChartValues = + jsonDecode(responseChart.body)['dailyNutritionIntake'] + .values + .map((value) => value as int) + .toList(); + print('chart'); + return [recommendedChartValues, consumedChartValues]; + } else { + emit(DiaryEditErrorState('Ошибка при декодировании данных КБЖУ')); + print('fail'); + return -1; + } + } + reloadScreen(DiaryEditEvent event, Emitter emit) async { print("Reloading..."); try { From f4ddb7285ce41e6ec6c7ef53d4c36fe47982c620 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Mon, 8 Apr 2024 16:45:20 +0300 Subject: [PATCH 05/11] refactor(diary): New apk compile --- .../auth/auth_screen/auth_screen.dart | 2 +- .../bloc/diary_edit_bloc.dart | 19 ++++++++++--------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/lib/presentation/auth/auth_screen/auth_screen.dart b/lib/presentation/auth/auth_screen/auth_screen.dart index 1ac19724..66ba2aa8 100644 --- a/lib/presentation/auth/auth_screen/auth_screen.dart +++ b/lib/presentation/auth/auth_screen/auth_screen.dart @@ -72,7 +72,7 @@ class AuthScreen extends StatelessWidget { buttonStyle: CustomButtonStyles.outlinePrimaryTL15, onPressed: onTapDiaryTest(context)), NextStepButton( - text: "Тест профиля".toUpperCase(), + text: "Тест чата".toUpperCase(), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, diff --git a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart index 425515ed..0e4a3e1b 100644 --- a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart +++ b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart @@ -47,13 +47,15 @@ class DiaryEditBloc extends Bloc { final token = "9|laravel_sanctum_KFXbccDcWEvTPfJmV99EQv1neAggmpR2TidVGDPN34fa201a"; - final int diaryId = fetchDiaryId(token); + //print(await fetchDiaryId(token)); + final int diaryId = await fetchDiaryId(token); try { - final diary = fetchDiaryData(token, diaryId); + print("Diary ID fetched"); + final diary = await fetchDiaryData(token, diaryId); print("Screen load success"); if (diary is Map) { - //final String diaryDate = diary['date'] ?? DateTime.now().toString(); - final chartValues = fetchChartValues(token, diaryId); + final String diaryDate = diary['date'] ?? DateTime.now().toString(); + final chartValues = await fetchChartValues(token, diaryId); if (state is DiaryEditLoadedState) { // Если текущее состояние уже загружено, обновляем его var currentState = state as DiaryEditLoadedState; @@ -116,7 +118,7 @@ class DiaryEditBloc extends Bloc { fatsController: TextEditingController(), carbsController: TextEditingController(), diaryId: diaryId, - //diaryDate: diaryDate, + diaryDate: diaryDate, autocompleteList: [], diaryEditModelObj: state.diaryEditModelObj?.copyWith( mealList: fillMealList(), portionList: fillPortions()))); @@ -144,7 +146,6 @@ class DiaryEditBloc extends Bloc { final data = jsonDecode(response.body); if (data is Map && data.containsKey('id')) { final int diaryId = data['id']; - print("id"); return diaryId; } else { emit(DiaryEditErrorState('Некоторые необходимые данные отсутствуют.')); @@ -167,7 +168,6 @@ class DiaryEditBloc extends Bloc { }, ); final diary = jsonDecode(response.body)['diary']; - print("data"); return diary; } @@ -192,7 +192,6 @@ class DiaryEditBloc extends Bloc { .values .map((value) => value as int) .toList(); - print('chart'); return [recommendedChartValues, consumedChartValues]; } else { emit(DiaryEditErrorState('Ошибка при декодировании данных КБЖУ')); @@ -401,6 +400,7 @@ class DiaryEditBloc extends Bloc { var response = await sendWakeupData( currentState.token, event.selectedTime, currentState.diaryId); if (response.statusCode == 200) { + await reloadScreen(event, emit); var updatedState = currentState.copyWith(wakeupController: event.selectedTime); print("Wakeup time changed to ${event.selectedTime}"); @@ -417,6 +417,7 @@ class DiaryEditBloc extends Bloc { var response = await sendRetireData( currentState.token, event.selectedTime, currentState.diaryId); if (response.statusCode == 200) { + await reloadScreen(event, emit); var updatedState = currentState.copyWith(retireController: event.selectedTime); print("Retire time changed to ${event.selectedTime}"); @@ -741,7 +742,7 @@ class DiaryEditBloc extends Bloc { ); if (response.statusCode == 200) { - print("finished"); + await reloadScreen(event, emit); } } } From bbbc20a15a55afa182b762cacae460bbdc3af5fa Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 10 Apr 2024 17:07:56 +0300 Subject: [PATCH 06/11] refactor(diary): Compiled version apk: profile, settings, diarym registration, auth, navigation bar --- .../user_registration_model.dart | 1 + .../auth/auth_screen/auth_screen.dart | 7 +- .../bloc/diary_edit_bloc.dart | 124 ++++++++++-------- .../bloc/diary_edit_state.dart | 1 + .../diary_edit_screen/diary_edit_screen.dart | 48 ++++--- .../bloc/my_profile_bloc.dart | 40 +----- .../my_profile_screen/my_profile_screen.dart | 10 +- .../additional_information_screen.dart | 12 +- lib/widgets/custom_bottom_bar.dart | 44 +++++-- lib/widgets/custom_edit_text_form_field.dart | 4 + lib/widgets/custom_expandable_list.dart | 6 +- 11 files changed, 164 insertions(+), 133 deletions(-) diff --git a/lib/data/models/userRegistrationModel/user_registration_model.dart b/lib/data/models/userRegistrationModel/user_registration_model.dart index 0001f9ec..baeb3a16 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.dart @@ -86,6 +86,7 @@ class UserRegistrationSheet { 'favorite_foods': favoriteFoods, 'unfavorite_foods': unfavoriteFoods, 'additional_info': additionalInfo, + 'activity_coefficient': '1.2', }; } } diff --git a/lib/presentation/auth/auth_screen/auth_screen.dart b/lib/presentation/auth/auth_screen/auth_screen.dart index 66ba2aa8..b6a3e588 100644 --- a/lib/presentation/auth/auth_screen/auth_screen.dart +++ b/lib/presentation/auth/auth_screen/auth_screen.dart @@ -65,7 +65,7 @@ class AuthScreen extends StatelessWidget { EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, onPressed: onTapNoAccount(context)), - NextStepButton( + /*NextStepButton( text: "Тест дневника".toUpperCase(), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), @@ -76,14 +76,14 @@ class AuthScreen extends StatelessWidget { margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapProfileTest(context)), + onPressed: onTapProfileTest(context)),*/ BlocBuilder(builder: (context, state) { return NextStepButton( text: "authentificate".tr.toUpperCase(), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: () => onTapAuth(state, context)); + onPressed: onTapAuth(state, context)); }), ]))); } @@ -102,6 +102,7 @@ class AuthScreen extends StatelessWidget { headers: {'Content-Type': 'application/json'}, body: json.encode(credentials), encoding: utf8); + print(response.statusCode); if (response.statusCode == 200) { var res = await jsonDecode(response.body); final box = await Hive.openBox('token'); diff --git a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart index 0e4a3e1b..67bfa95b 100644 --- a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart +++ b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart @@ -89,9 +89,10 @@ class DiaryEditBloc extends Bloc { diaryEditModelObj: currentState.diaryEditModelObj)); } else { // Если текущее состояние - начальное, создаем новое загруженное состояние + final List meals = + fillMealList(diary['meals']); emit(DiaryEditLoadedState( - currentMeal: SelectionPopupModel( - id: 1, title: "Прием пищи 1", isSelected: true), + currentMeal: meals[0], portionController: SelectionPopupModel( id: 0, title: "порций", isSelected: true), wakeupExpanded: true, @@ -120,8 +121,8 @@ class DiaryEditBloc extends Bloc { diaryId: diaryId, diaryDate: diaryDate, autocompleteList: [], - diaryEditModelObj: state.diaryEditModelObj?.copyWith( - mealList: fillMealList(), portionList: fillPortions()))); + diaryEditModelObj: state.diaryEditModelObj + ?.copyWith(mealList: meals, portionList: fillPortions()))); } } } catch (e) { @@ -200,7 +201,18 @@ class DiaryEditBloc extends Bloc { } } - reloadScreen(DiaryEditEvent event, Emitter emit) async { + refreshScreen( + int mealID, + DiaryEditEvent event, + Emitter emit, + ) async { + await reloadScreen(event, emit); + } + + reloadScreen( + DiaryEditEvent event, + Emitter emit, + ) async { print("Reloading..."); try { final token = @@ -244,45 +256,46 @@ class DiaryEditBloc extends Bloc { responseChart.body)['dailyNutritionRecommendation']; final consumedChartValues = jsonDecode(responseChart.body)['dailyNutritionIntake']; + final List meals = + fillMealList(diary['meals']); try { await Future(() => emit(DiaryEditLoadedState( - currentMeal: SelectionPopupModel( - id: 1, title: "Прием пищи 1", isSelected: true), - portionController: SelectionPopupModel( - id: 0, title: "порций", isSelected: true), - wakeupExpanded: true, - moodExpanded: true, - moderationExpanded: false, - token: token, - recommendedChartValues: recommendedChartValues.values - .map((value) => value as int) - .toList(), - consumedChartValues: consumedChartValues.values - .map((value) => value as int) - .toList(), - meals: diary['meals'], - portions: diary['meals'][0]['portions'], - photos: diary['meals'][0]['photos'], - wakeupController: toTime(diary['wakeup'] ?? "09:00"), - retireController: toTime(diary['retire'] ?? "23:00"), - mealTimeController: - toTime(diary['meals'][0]['time'] ?? "10:00"), - selectedSatiety: diary['meals'][0]['satiety'], - selectedMood: diary['meals'][0]['mood'], - commentController: - TextEditingController(text: diary['comment']), - productNameController: TextEditingController(), - productQuantityController: TextEditingController(), - caloriesController: TextEditingController(), - proteinsController: TextEditingController(), - fatsController: TextEditingController(), - carbsController: TextEditingController(), - diaryId: diaryId, - diaryDate: diaryDate, - autocompleteList: [], - diaryEditModelObj: state.diaryEditModelObj?.copyWith( - mealList: fillMealList(), - portionList: fillPortions())))); + diaryEditModelObj: state.diaryEditModelObj?.copyWith( + mealList: meals, portionList: fillPortions()), + currentMeal: meals[0], + portionController: SelectionPopupModel( + id: 0, title: "порций", isSelected: true), + wakeupExpanded: true, + moodExpanded: true, + moderationExpanded: false, + token: token, + recommendedChartValues: recommendedChartValues.values + .map((value) => value as int) + .toList(), + consumedChartValues: consumedChartValues.values + .map((value) => value as int) + .toList(), + meals: diary['meals'], + portions: diary['meals'][0]['portions'], + photos: diary['meals'][0]['photos'], + wakeupController: toTime(diary['wakeup'] ?? "09:00"), + retireController: toTime(diary['retire'] ?? "23:00"), + mealTimeController: + toTime(diary['meals'][0]['time'] ?? "10:00"), + selectedSatiety: diary['meals'][0]['satiety'], + selectedMood: diary['meals'][0]['mood'], + commentController: + TextEditingController(text: diary['comment']), + productNameController: TextEditingController(), + productQuantityController: TextEditingController(), + caloriesController: TextEditingController(), + proteinsController: TextEditingController(), + fatsController: TextEditingController(), + carbsController: TextEditingController(), + diaryId: diaryId, + diaryDate: diaryDate, + autocompleteList: [], + ))); print("Updated"); } catch (e) { @@ -364,6 +377,8 @@ class DiaryEditBloc extends Bloc { currentState.diaryId); if (response.statusCode == 200) { + print( + 'Mood change success! meal_id: ${currentState.currentMeal?.id}, mood: ${event.selectedElement}'); updatedState.selectedMood = event.selectedElement; emit(updatedState); // Передаем обновленное состояние в emit } @@ -511,11 +526,10 @@ class DiaryEditBloc extends Bloc { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; final meal = currentState.meals?.firstWhere( - (meal) => meal['type'] == event.value.id, + (meal) => meal['id'] == event.value.id, orElse: () => null); - - print(meal); int? id = event.value.id; + print(meal['photos']); DiaryEditLoadedState updatedState = currentState.copyWith( currentMeal: event.value, portions: meal['portions'], @@ -523,6 +537,7 @@ class DiaryEditBloc extends Bloc { mealTimeController: toTime(meal['time'] ?? "1$id:00"), selectedMood: meal['mood'], selectedSatiety: meal['satiety']); + print(updatedState.photos); emit(updatedState); } } @@ -916,15 +931,16 @@ class DiaryEditBloc extends Bloc { return timeOfDay; } - List fillMealList() { - return [ - SelectionPopupModel(id: 1, title: "Прием пищи 1", isSelected: true), - SelectionPopupModel(id: 2, title: "Прием пищи 2"), - SelectionPopupModel(id: 3, title: "Прием пищи 3"), - SelectionPopupModel(id: 4, title: "Прием пищи 4"), - SelectionPopupModel(id: 5, title: "Прием пищи 5"), - SelectionPopupModel(id: 6, title: "Прием пищи 6"), - ]; + List fillMealList(List meals) { + meals.sort(compareTypes); + return meals.map((meal) { + String title = "Прием пищи ${meal['type']}"; + return SelectionPopupModel(id: meal['id'], title: title); + }).toList(); + } + + int compareTypes(a, b) { + return a['type'].compareTo(b['type']); } List fillPortions() { diff --git a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart index 58c6fd25..ebed94bd 100644 --- a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart +++ b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart @@ -139,6 +139,7 @@ class DiaryEditLoadedState extends DiaryEditState { diaryDate: diaryDate ?? this.diaryDate, token: token ?? this.token, meals: meals ?? this.meals, + photos: photos ?? this.photos, autocompleteList: autocompleteList ?? this.autocompleteList, portions: portions ?? this.portions, recommendedChartValues: diff --git a/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart b/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart index e2bdbeee..0fcfe9e6 100644 --- a/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart +++ b/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart @@ -13,6 +13,7 @@ import 'package:eatvio_app/widgets/custom_edit_text_form_field.dart'; import 'package:eatvio_app/widgets/custom_edit_drop_down.dart'; import 'package:eatvio_app/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/widgets/custom_scale_element.dart'; +import 'package:eatvio_app/widgets/custom_bottom_bar.dart'; // ignore: must_be_immutable class DiaryEditScreen extends StatelessWidget { @@ -229,7 +230,6 @@ class DiaryEditScreen extends StatelessWidget { state.autocompleteList!.map((dynamic item) => item as String).toList(); //print(_options); FocusNode focusNodeName = FocusNode(); - FocusNode focusNodeQuantity = FocusNode(); return Container( margin: EdgeInsets.symmetric(horizontal: 16.h), padding: EdgeInsets.symmetric( @@ -318,10 +318,7 @@ class DiaryEditScreen extends StatelessWidget { hintText: "Введите название продукта", controller: productEditingController, focusNode: focusNodeName, - onChanged: getAutocomplete(context, focusNodeQuantity), - /*onFieldSubmitted: (String value) { - onFieldSubmitted(); - },*/ + onChanged: getAutocomplete(context, focusNodeName), ); }, optionsViewBuilder: ( @@ -341,7 +338,7 @@ class DiaryEditScreen extends StatelessWidget { itemBuilder: (BuildContext context, int index) { final String option = options.elementAt(index); return GestureDetector( - onTap: selectProduct(onSelected, option), + onTap: selectProduct(onSelected, option, state), child: ListTile( title: Text(option), ), @@ -374,7 +371,7 @@ class DiaryEditScreen extends StatelessWidget { width: 150.h, hintText: "Кол-во", textInputAction: TextInputAction.done, - focusNode: focusNodeQuantity, + // focusNode: focusNodeQuantity, controller: state.productQuantityController, keyboardType: TextInputType.number, inputFormatters: [digitsOnly], @@ -405,10 +402,12 @@ class DiaryEditScreen extends StatelessWidget { .toList(), SizedBox(height: 30.v), ...state.photos != null - ? state.photos! - .map((photo) => _buildPhoto(context, photo)) - .toList() - : [], + ? state.photos!.isEmpty + ? [Text('Фото пока нет')] + : state.photos! + .map((photo) => _buildPhoto(context, photo)) + .toList() + : [Text('Фото нет')], SizedBox(height: 20.v), _buildAddPhoto(context), SizedBox(height: 30.v), @@ -561,7 +560,9 @@ class DiaryEditScreen extends StatelessWidget { }; } - selectProduct(AutocompleteOnSelected onSelected, String option) { + selectProduct(AutocompleteOnSelected onSelected, String option, + DiaryEditLoadedState state) { + state.productNameController?.text = option; return () { onSelected(option); }; @@ -764,25 +765,37 @@ class DiaryEditScreen extends StatelessWidget { BarChartGroupData(x: 0, barRods: [ BarChartRodData( toY: consumedValues[0] / recommendedValues[0] * 100, - color: Colors.blue, + color: checkConsumedValues( + [recommendedValues[0]], [consumedValues[1]]) + ? Colors.red + : Colors.blue, ) ]), BarChartGroupData(x: 1, barRods: [ BarChartRodData( toY: consumedValues[1] / recommendedValues[1] * 100, - color: Colors.red, + color: checkConsumedValues( + [recommendedValues[1]], [consumedValues[1]]) + ? Colors.red + : Colors.blue, ) ]), BarChartGroupData(x: 2, barRods: [ BarChartRodData( toY: consumedValues[2] / recommendedValues[2] * 100, - color: Colors.green, + color: checkConsumedValues( + [recommendedValues[2]], [consumedValues[2]]) + ? Colors.red + : Colors.blue, ) ]), BarChartGroupData(x: 3, barRods: [ BarChartRodData( toY: consumedValues[3] / recommendedValues[3] * 100, - color: Colors.orange, + color: checkConsumedValues( + [recommendedValues[3]], [consumedValues[3]]) + ? Colors.red + : Colors.blue, ) ]), ], @@ -889,7 +902,7 @@ class DiaryEditScreen extends StatelessWidget { SizedBox(height: 19.v), if (checkConsumedValues(recommendedValues, consumedValues)) Text( - "*Превышенная суточная норма углеводов", + "*Превышенная суточная норма", style: theme.textTheme.labelLarge, ) ], @@ -1042,7 +1055,6 @@ class DiaryEditScreen extends StatelessWidget { Function() onFinishDayPressed(BuildContext context) { return () { - print("sad"); showDialog( context: context, builder: (BuildContext dialogContext) { diff --git a/lib/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart b/lib/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart index 69207e24..8aac9e06 100644 --- a/lib/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart +++ b/lib/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart @@ -4,7 +4,7 @@ import '/core/app_export.dart'; import 'package:eatvio_app/presentation/profile/my_profile_screen/models/my_profile_model.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; -//import 'package:hive/hive.dart'; +import 'package:hive/hive.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; part 'my_profile_event.dart'; @@ -21,28 +21,24 @@ class MyProfileBloc extends Bloc { Emitter emit, ) async { try { - /*final box = await Hive.openBox('token'); - final token = box.get('token');*/ - final token = - "9|laravel_sanctum_KFXbccDcWEvTPfJmV99EQv1neAggmpR2TidVGDPN34fa201a"; + final box = await Hive.openBox('token'); + final token = box.get('token'); + //final token = + // "9|laravel_sanctum_KFXbccDcWEvTPfJmV99EQv1neAggmpR2TidVGDPN34fa201a"; final response = await http.get( Uri.parse(dotenv.env['SERVER_ROOT']! + '/profile/index'), headers: { 'Authorization': 'Bearer $token', }, ); - if (response.statusCode == 200) { final data = jsonDecode(response.body); - // Проверка наличия ключевых полей в JSON if (data is Map && data.containsKey('user') && data.containsKey('userDetails') && data.containsKey('chartPoints') && data.containsKey('circumferences')) { - // Все ключевые поля присутствуют, продолжаем обработку if (state is MyProfileLoadedState) { - // Если текущее состояние уже загружено, обновляем его var currentState = state as MyProfileLoadedState; var plans = [] ..addAll(data["finishedPlans"]) @@ -51,9 +47,6 @@ class MyProfileBloc extends Bloc { ..addAll(data["paidPlan"]) ..addAll(data["requestedPlan"]) ..addAll(data["initedPlan"]); - - // Обновляем значения контроллеров только если они уже были созданы - emit((currentState).copyWith( chartPoints: currentState.chartPoints, chartDates: currentState.chartDates, @@ -123,18 +116,6 @@ class MyProfileBloc extends Bloc { }) : data["chartPoints"]; - /*List weights = [0.0, 0.0, 0.0, 0.0]; - List dates = [ - "0000-00-00 00:00:00", - "0000-00-00 00:00:00", - "0000-00-00 00:00:00", - "0000-00-00 00:00:00" - ]; - for (int i = 0; i < data["chartPoints"].length; i++) { - weights[i] = data["chartPoints"][i]["weight"].toDouble(); - dates[i] = data["chartPoints"][i]["created_at"].toString(); - } - print(data);*/ List dates = [ "0000-00-00 00:00:00", "0000-00-00 00:00:00", @@ -169,14 +150,7 @@ class MyProfileBloc extends Bloc { }; } } - print(data['userDetails']); - /*print(chartPoints); - print(circumferences);*/ - /*print(weights); - print(weights.runtimeType); - print(circumferences); - print(circumferences.runtimeType);*/ - // Если текущее состояние - начальное, создаем новое загруженное состояние + emit(MyProfileLoadedState( chartPoints: chartPoints, chartDates: dates, @@ -231,7 +205,7 @@ class MyProfileBloc extends Bloc { selectedCity: data['userDetails']['city'], selectedCountry: data['userDetails']['country'], selectedActivity: determineActivityLevel( - double.parse(data['userDetails']['activity_coefficient'])), + data['userDetails']['activity_coefficient']), )); } } else { diff --git a/lib/presentation/profile/my_profile_screen/my_profile_screen.dart b/lib/presentation/profile/my_profile_screen/my_profile_screen.dart index 77929fd5..0a387801 100644 --- a/lib/presentation/profile/my_profile_screen/my_profile_screen.dart +++ b/lib/presentation/profile/my_profile_screen/my_profile_screen.dart @@ -182,7 +182,7 @@ class MyProfileScreen extends StatelessWidget { switch (chartType) { case 1: // График веса return GestureDetector( - onTap: _editWeight(context, state), + onTap: () => _editWeight(context, state), child: Column(children: [ Text( "weight_chart".tr, @@ -225,7 +225,7 @@ class MyProfileScreen extends StatelessWidget { ]); case 3: //График обхватов return GestureDetector( - onTap: _editCircumference(context, state), + onTap: () => _editCircumference(context, state), child: Column(children: [ Text( "circumferences_chart".tr, @@ -279,10 +279,8 @@ class MyProfileScreen extends StatelessWidget { ); } - /// Section Widget _buildChart( BuildContext context, List chartPoints, List? dates) { -// Определение осей графика List spots = []; for (int i = 0; i < 4; i++) { spots.add( @@ -428,7 +426,7 @@ class MyProfileScreen extends StatelessWidget { }; } - mapSpots() { + List Function(List) mapSpots() { return (touchedSpots) { return touchedSpots.map((LineBarSpot touchedSpot) { final textStyle = TextStyle( @@ -635,7 +633,7 @@ class MyProfileScreen extends StatelessWidget { ); } - mapTouchedSpots() { + List Function(List) mapTouchedSpots() { return (touchedSpots) { return touchedSpots.map((LineBarSpot touchedSpot) { final textStyle = TextStyle( diff --git a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart index 08ad6dd6..7f632e21 100644 --- a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart +++ b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart @@ -78,12 +78,12 @@ class AdditionalInformationScreen extends StatelessWidget { sheet.additionalInfo = state.editTextController!.text; //print(json.encode(sheet.toJson())); final response = await http.post( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/register'), - headers: {'Content-Type': 'application/json'}, - body: jsonEncode(sheet.toJson()), - ); - print(response.statusCode); - print(response.body); + Uri.parse(dotenv.env['SERVER_ROOT']! + '/register'), + headers: {'Content-Type': 'application/json'}, + body: jsonEncode(sheet), + encoding: utf8); + print(jsonEncode(sheet.toJson())); + print(Uri.parse(dotenv.env['SERVER_ROOT']! + '/register')); if (response.statusCode == 200) { var res = await jsonDecode(response.body); final box = await Hive.openBox('token'); diff --git a/lib/widgets/custom_bottom_bar.dart b/lib/widgets/custom_bottom_bar.dart index 45928ebd..71ee1bfb 100644 --- a/lib/widgets/custom_bottom_bar.dart +++ b/lib/widgets/custom_bottom_bar.dart @@ -21,12 +21,12 @@ class CustomBottomBarState extends State { title: "diary".tr, type: BottomBarEnum.tf, ), - BottomMenuModel( + /*BottomMenuModel( icon: ImageConstant.imgNavBlueGray400, activeIcon: ImageConstant.imgNavBlueGray400, title: "my_blog".tr, type: BottomBarEnum.tf, - ), + ),*/ BottomMenuModel( icon: ImageConstant.imgNavBlueGray40024x23, activeIcon: ImageConstant.imgNavBlueGray40024x23, @@ -34,9 +34,9 @@ class CustomBottomBarState extends State { type: BottomBarEnum.tf, ), BottomMenuModel( - icon: ImageConstant.imgNavPrimary, - activeIcon: ImageConstant.imgNavPrimary, - title: "admin".tr, + icon: ImageConstant.imgNavBlueGray40024x23, + activeIcon: ImageConstant.imgNavBlueGray40024x23, + title: "Настройки", type: BottomBarEnum.tf, ), BottomMenuModel( @@ -72,12 +72,33 @@ class CustomBottomBarState extends State { } void changeMeny(index) { - selectedIndex = index; - widget.onChanged?.call(bottomMenuList[index].type); - setState(() {}); + setState(() { + selectedIndex = index; + }); + + switch (index) { + case 0: + Navigator.pushNamed(context, AppRoutes.diaryEdit); + break; + /*case 1: + Navigator.pushNamed(context, '/my_blog'); + break;*/ + case 1: + Navigator.pushNamed(context, AppRoutes.myProfile); + break; + case 2: + Navigator.pushNamed(context, AppRoutes.mySettings); + break; + case 3: + Navigator.pushNamed(context, '/chat'); + break; + default: + } } BottomNavigationBarItem bottomMenu(index) { + bool isSelected = selectedIndex == index; + return BottomNavigationBarItem( icon: Column( crossAxisAlignment: CrossAxisAlignment.center, @@ -86,14 +107,17 @@ class CustomBottomBarState extends State { imagePath: bottomMenuList[index].icon, height: 24.v, width: 19.h, - color: appTheme.blueGray400, + color: + isSelected ? theme.colorScheme.primary : appTheme.blueGray400, ), Padding( padding: EdgeInsets.only(top: 8.v), child: Text( bottomMenuList[index].title ?? "", style: CustomTextStyles.bodySmallMulishBluegray80012.copyWith( - color: appTheme.blueGray800, + color: isSelected + ? theme.colorScheme.primary + : appTheme.blueGray800, ), ), ), diff --git a/lib/widgets/custom_edit_text_form_field.dart b/lib/widgets/custom_edit_text_form_field.dart index aeeb19e7..0853d3e5 100644 --- a/lib/widgets/custom_edit_text_form_field.dart +++ b/lib/widgets/custom_edit_text_form_field.dart @@ -20,6 +20,7 @@ class CustomTextFormField extends StatelessWidget { this.prefixConstraints, this.suffix, this.suffixConstraints, + this.onFieldSubmitted, this.initialValue, this.contentPadding, this.inputFormatters, @@ -66,6 +67,8 @@ class CustomTextFormField extends StatelessWidget { final Widget? suffix; + final Function(String)? onFieldSubmitted; + final BoxConstraints? suffixConstraints; final EdgeInsets? contentPadding; @@ -112,6 +115,7 @@ class CustomTextFormField extends StatelessWidget { keyboardType: keyboardType, onSaved: onSaved, onChanged: onChanged, + onFieldSubmitted: onFieldSubmitted, inputFormatters: inputFormatters, initialValue: initialValue, ), diff --git a/lib/widgets/custom_expandable_list.dart b/lib/widgets/custom_expandable_list.dart index 3d2190a5..007a8156 100644 --- a/lib/widgets/custom_expandable_list.dart +++ b/lib/widgets/custom_expandable_list.dart @@ -255,7 +255,7 @@ class _ExpandableListState extends State { ], ), NextStepButton( - onPressed: sendData(state), + onPressed: () => sendProfileData(state), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, text: "save".tr.toUpperCase(), margin: EdgeInsets.only(top: 20.h, bottom: 20.h)), @@ -326,6 +326,7 @@ class _ExpandableListState extends State { } Future sendProfileData(MyProfileLoadedState? state) async { + print("asd"); try { // Создаем JSON объект с данными профиля Map profileData = { @@ -350,8 +351,7 @@ class _ExpandableListState extends State { 'has_hypo': state?.hypoFormController, 'has_hyper': state?.hyperFormController, 'activity_coefficient': - determineActivityFactor(state?.selectedActivity ?? 'сидячий') - .toString, + determineActivityFactor(state?.selectedActivity ?? 'сидячий'), }; final box = await Hive.openBox('token'); final token = box.get('token'); From 51226653704eb0dedbca91c0c581765e015decdf Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 11 Apr 2024 16:24:10 +0300 Subject: [PATCH 07/11] refactor(app): Assemble release --- .../bloc/diary_edit_bloc.dart | 15 ++++++++----- .../diary_edit_screen/diary_edit_screen.dart | 20 +++++++++++++++-- .../additional_information_screen.dart | 22 +++++++++++-------- lib/widgets/custom_bottom_bar.dart | 2 +- lib/widgets/custom_expandable_list.dart | 6 +++-- 5 files changed, 45 insertions(+), 20 deletions(-) diff --git a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart index 67bfa95b..5a04a681 100644 --- a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart +++ b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart @@ -7,6 +7,7 @@ import 'package:image_picker/image_picker.dart'; import 'package:eatvio_app/presentation/diary/diary_edit_screen/models/diary_edit_model.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; +import 'package:hive/hive.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; part 'diary_edit_event.dart'; @@ -44,9 +45,10 @@ class DiaryEditBloc extends Bloc { Emitter emit, ) async { try { - final token = - "9|laravel_sanctum_KFXbccDcWEvTPfJmV99EQv1neAggmpR2TidVGDPN34fa201a"; - + // final token = + // "9|laravel_sanctum_KFXbccDcWEvTPfJmV99EQv1neAggmpR2TidVGDPN34fa201a"; + final box = await Hive.openBox('token'); + final token = box.get('token'); //print(await fetchDiaryId(token)); final int diaryId = await fetchDiaryId(token); try { @@ -215,9 +217,10 @@ class DiaryEditBloc extends Bloc { ) async { print("Reloading..."); try { - final token = - "9|laravel_sanctum_KFXbccDcWEvTPfJmV99EQv1neAggmpR2TidVGDPN34fa201a"; - + //final token = + // "9|laravel_sanctum_KFXbccDcWEvTPfJmV99EQv1neAggmpR2TidVGDPN34fa201a"; final box = await Hive.openBox('token'); + final box = await Hive.openBox('token'); + final token = box.get('token'); final response = await http.get( Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/index'), headers: { diff --git a/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart b/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart index 0fcfe9e6..d03631be 100644 --- a/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart +++ b/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart @@ -14,6 +14,7 @@ import 'package:eatvio_app/widgets/custom_edit_drop_down.dart'; import 'package:eatvio_app/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/widgets/custom_scale_element.dart'; import 'package:eatvio_app/widgets/custom_bottom_bar.dart'; +import 'package:carousel_slider/carousel_slider.dart'; // ignore: must_be_immutable class DiaryEditScreen extends StatelessWidget { @@ -401,13 +402,14 @@ class DiaryEditScreen extends StatelessWidget { .map((portion) => _buildProduct(context, portion)) .toList(), SizedBox(height: 30.v), - ...state.photos != null + /*...state.photos != null ? state.photos!.isEmpty ? [Text('Фото пока нет')] : state.photos! .map((photo) => _buildPhoto(context, photo)) .toList() - : [Text('Фото нет')], + : [Text('Фото нет')],*/ + _buildCarousel(context, state), SizedBox(height: 20.v), _buildAddPhoto(context), SizedBox(height: 30.v), @@ -601,6 +603,20 @@ class DiaryEditScreen extends StatelessWidget { }; } + _buildCarousel(BuildContext context, DiaryEditLoadedState state) { + if (state.photos!.isEmpty) { + return Text("Фото нет"); + } else { + return CarouselSlider( + options: CarouselOptions(height: 340.0), + items: state.photos!.map((photo) { + return _buildPhoto( + context, photo); // Assuming photos are stored as strings + }).toList(), + ); + } + } + _buildProduct(BuildContext context, Map portion) { return Container( margin: EdgeInsets.symmetric(horizontal: 10.h), diff --git a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart index 7f632e21..0ea7e7dd 100644 --- a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart +++ b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart @@ -76,16 +76,18 @@ class AdditionalInformationScreen extends StatelessWidget { UserRegistrationSheet sheet = state.additionalInformationModelObj!.userRegistrationSheet; sheet.additionalInfo = state.editTextController!.text; - //print(json.encode(sheet.toJson())); + final response = await http.post( Uri.parse(dotenv.env['SERVER_ROOT']! + '/register'), - headers: {'Content-Type': 'application/json'}, - body: jsonEncode(sheet), + headers: { + 'Content-Type': 'application/json', + 'Accept': 'application/json' + }, + body: jsonEncode(sheet.toJson()), encoding: utf8); - print(jsonEncode(sheet.toJson())); - print(Uri.parse(dotenv.env['SERVER_ROOT']! + '/register')); + + var res = await jsonDecode(response.body); if (response.statusCode == 200) { - var res = await jsonDecode(response.body); final box = await Hive.openBox('token'); final token = res['token']; box.put('token', token); @@ -93,6 +95,8 @@ class AdditionalInformationScreen extends StatelessWidget { context, AppRoutes.myProfile, ); + } else { + showErrorMessage(context, res['message']); } }; } @@ -152,12 +156,12 @@ class AdditionalInformationScreen extends StatelessWidget { /// Displays an alert dialog when the action is triggered. /// The dialog box contains a title and a message with the `Теперь вы можете пользоваться полным функционалом приложения` - showSuccessMessage(BuildContext context, String text) { + showErrorMessage(BuildContext context, String text) { showDialog( context: context, builder: (_) => AlertDialog( - title: const Text('Регистрация завершена!'), - content: const Text('1'), + title: const Text('Ошибка'), + content: Text(text), actions: [ TextButton(onPressed: onTapOk(context), child: const Text('Ok')) ], diff --git a/lib/widgets/custom_bottom_bar.dart b/lib/widgets/custom_bottom_bar.dart index 71ee1bfb..cf1ecba6 100644 --- a/lib/widgets/custom_bottom_bar.dart +++ b/lib/widgets/custom_bottom_bar.dart @@ -34,7 +34,7 @@ class CustomBottomBarState extends State { type: BottomBarEnum.tf, ), BottomMenuModel( - icon: ImageConstant.imgNavBlueGray40024x23, + icon: ImageConstant.imgNavPrimary, activeIcon: ImageConstant.imgNavBlueGray40024x23, title: "Настройки", type: BottomBarEnum.tf, diff --git a/lib/widgets/custom_expandable_list.dart b/lib/widgets/custom_expandable_list.dart index 007a8156..b8b8edf0 100644 --- a/lib/widgets/custom_expandable_list.dart +++ b/lib/widgets/custom_expandable_list.dart @@ -340,7 +340,7 @@ class _ExpandableListState extends State { 'weight': state?.weightFormController?.text, 'blood_pressure_up': state?.upPressureFormController?.text, 'blood_pressure_down': state?.downPressureFormController?.text, - 'about_alergy': state?.allergiesFormController?.text, + 'about_alergy': state?.allergiesFormController?.text ?? 'Нет аллергий', 'about_taking_pils': state?.pillsFormController?.text, 'about_sport_hobbies': state?.sportsFormController?.text, 'favorite_foods': state?.favoriteFormController?.text, @@ -362,6 +362,7 @@ class _ExpandableListState extends State { encoding: utf8, headers: { 'Content-Type': 'application/json', + 'Accept': 'application/json', 'Authorization': 'Bearer $token', }, ); @@ -373,11 +374,12 @@ class _ExpandableListState extends State { AppRoutes.myProfile, ); } else { + var res = await jsonDecode(response.body); showDialog( context: context, builder: (context) => AlertDialog( title: Text('Ошибка'), - content: Text('Ошибка при отправке данных профиля'.tr), + content: Text(res['message']), actions: [ TextButton( onPressed: onTapOk(context), From ab9227de428f602b885d122e94b71da3ad26cbe2 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 12 Apr 2024 15:09:49 +0300 Subject: [PATCH 08/11] refactor(profile): Refactoring --- lib/widgets/custom_expandable_list.dart | 143 ++++++++++++++---------- 1 file changed, 85 insertions(+), 58 deletions(-) diff --git a/lib/widgets/custom_expandable_list.dart b/lib/widgets/custom_expandable_list.dart index b8b8edf0..00d66cea 100644 --- a/lib/widgets/custom_expandable_list.dart +++ b/lib/widgets/custom_expandable_list.dart @@ -326,68 +326,17 @@ class _ExpandableListState extends State { } Future sendProfileData(MyProfileLoadedState? state) async { - print("asd"); try { - // Создаем JSON объект с данными профиля - Map profileData = { - 'first_name': state?.firstNameFormController?.text, - 'last_name': state?.lastNameFormController?.text, - 'chest_circumference': state?.chestCircumferenceFormController?.text, - 'waist_circumference': state?.waistCircumferenceFormController?.text, - 'hip_circumference': state?.hipCircumferenceFormController?.text, - 'birthdate': state?.dateFormController?.text, - 'height': state?.heightFormController?.text, - 'weight': state?.weightFormController?.text, - 'blood_pressure_up': state?.upPressureFormController?.text, - 'blood_pressure_down': state?.downPressureFormController?.text, - 'about_alergy': state?.allergiesFormController?.text ?? 'Нет аллергий', - 'about_taking_pils': state?.pillsFormController?.text, - 'about_sport_hobbies': state?.sportsFormController?.text, - 'favorite_foods': state?.favoriteFormController?.text, - 'unfavorite_foods': state?.unfavoriteFormController?.text, - 'additional_info': state?.additionalFormController?.text, - 'country': state?.selectedCountry ?? 'Россия', - 'city': state?.selectedCity ?? 'Москва', - 'has_hypo': state?.hypoFormController, - 'has_hyper': state?.hyperFormController, - 'activity_coefficient': - determineActivityFactor(state?.selectedActivity ?? 'сидячий'), - }; - final box = await Hive.openBox('token'); - final token = box.get('token'); - String apiUrl = dotenv.env['SERVER_ROOT']! + '/profile/update'; - http.Response response = await http.post( - Uri.parse(apiUrl), - body: json.encode(profileData), - encoding: utf8, - headers: { - 'Content-Type': 'application/json', - 'Accept': 'application/json', - 'Authorization': 'Bearer $token', - }, - ); + final profileData = _createProfileData(state); + final token = await _getTokenFromBox(); + final apiUrl = _buildApiUrl(); + final response = await _sendHttpRequest(profileData, apiUrl, token); - print(response.body); if (response.statusCode == 200) { - Navigator.pushNamed( - context, - AppRoutes.myProfile, - ); + _navigateToProfilePage(); } else { - var res = await jsonDecode(response.body); - showDialog( - context: context, - builder: (context) => AlertDialog( - title: Text('Ошибка'), - content: Text(res['message']), - actions: [ - TextButton( - onPressed: onTapOk(context), - child: Text('OK'), - ), - ], - ), - ); + final errorMessage = _getErrorMessage(response); + _showErrorDialog(errorMessage); throw Exception('Ошибка при отправке данных профиля'); } } catch (error) { @@ -395,6 +344,84 @@ class _ExpandableListState extends State { } } + Map _createProfileData(MyProfileLoadedState? state) { + return { + 'first_name': state?.firstNameFormController?.text, + 'last_name': state?.lastNameFormController?.text, + 'chest_circumference': state?.chestCircumferenceFormController?.text, + 'waist_circumference': state?.waistCircumferenceFormController?.text, + 'hip_circumference': state?.hipCircumferenceFormController?.text, + 'birthdate': state?.dateFormController?.text, + 'height': state?.heightFormController?.text, + 'weight': state?.weightFormController?.text, + 'blood_pressure_up': state?.upPressureFormController?.text, + 'blood_pressure_down': state?.downPressureFormController?.text, + 'about_alergy': state?.allergiesFormController?.text ?? 'Нет аллергий', + 'about_taking_pils': state?.pillsFormController?.text, + 'about_sport_hobbies': state?.sportsFormController?.text, + 'favorite_foods': state?.favoriteFormController?.text, + 'unfavorite_foods': state?.unfavoriteFormController?.text, + 'additional_info': state?.additionalFormController?.text, + 'country': state?.selectedCountry ?? 'Россия', + 'city': state?.selectedCity ?? 'Москва', + 'has_hypo': state?.hypoFormController, + 'has_hyper': state?.hyperFormController, + 'activity_coefficient': + determineActivityFactor(state?.selectedActivity ?? 'сидячий'), + }; + } + + Future _getTokenFromBox() async { + final box = await Hive.openBox('token'); + return box.get('token'); + } + + String _buildApiUrl() { + return dotenv.env['SERVER_ROOT']! + '/profile/update'; + } + + Future _sendHttpRequest( + Map profileData, String apiUrl, String? token) { + return http.post( + Uri.parse(apiUrl), + body: json.encode(profileData), + encoding: utf8, + headers: { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + 'Authorization': 'Bearer $token', + }, + ); + } + + void _navigateToProfilePage() { + Navigator.pushNamed( + context, + AppRoutes.myProfile, + ); + } + + String _getErrorMessage(http.Response response) { + final res = jsonDecode(response.body); + return res['message']; + } + + void _showErrorDialog(String errorMessage) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text('Ошибка'), + content: Text(errorMessage), + actions: [ + TextButton( + onPressed: onTapOk(context), + child: Text('OK'), + ), + ], + ), + ); + } + onTapOk(BuildContext context) { return () { Navigator.pop(context); From 5ba9c15dd25448975cd41ddfc358e65db812be16 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Mon, 15 Apr 2024 15:14:15 +0300 Subject: [PATCH 09/11] feat(app): Auth token is now saved after app close --- .../diary/diary_edit_screen/diary_edit_screen.dart | 2 +- .../profile/my_profile_screen/bloc/my_profile_bloc.dart | 6 ++++++ .../registration/splash_screen/bloc/splash_bloc.dart | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart b/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart index d03631be..6f37061c 100644 --- a/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart +++ b/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart @@ -13,7 +13,7 @@ import 'package:eatvio_app/widgets/custom_edit_text_form_field.dart'; import 'package:eatvio_app/widgets/custom_edit_drop_down.dart'; import 'package:eatvio_app/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/widgets/custom_scale_element.dart'; -import 'package:eatvio_app/widgets/custom_bottom_bar.dart'; +//import 'package:eatvio_app/widgets/custom_bottom_bar.dart'; import 'package:carousel_slider/carousel_slider.dart'; // ignore: must_be_immutable diff --git a/lib/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart b/lib/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart index 8aac9e06..95f3227a 100644 --- a/lib/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart +++ b/lib/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart @@ -1,3 +1,4 @@ +import 'package:eatvio_app/presentation/auth/auth_screen/auth_screen.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import '/core/app_export.dart'; @@ -23,6 +24,11 @@ class MyProfileBloc extends Bloc { try { final box = await Hive.openBox('token'); final token = box.get('token'); + if (token == null) { + NavigatorService.popAndPushNamed( + AppRoutes.authScreen, + ); // Если токен есть, запускаем приложение + } //final token = // "9|laravel_sanctum_KFXbccDcWEvTPfJmV99EQv1neAggmpR2TidVGDPN34fa201a"; final response = await http.get( diff --git a/lib/presentation/registration/splash_screen/bloc/splash_bloc.dart b/lib/presentation/registration/splash_screen/bloc/splash_bloc.dart index a767f763..9491b451 100644 --- a/lib/presentation/registration/splash_screen/bloc/splash_bloc.dart +++ b/lib/presentation/registration/splash_screen/bloc/splash_bloc.dart @@ -17,7 +17,7 @@ class SplashBloc extends Bloc { ) async { Future.delayed(const Duration(milliseconds: 3000), () { NavigatorService.popAndPushNamed( - AppRoutes.authScreen, + AppRoutes.myProfile, ); }); } From 881c534763f67ce17e5c598ca423cb487ce6d852 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Mon, 15 Apr 2024 16:35:23 +0300 Subject: [PATCH 10/11] refactor(diary): Emitter warnings resolved --- .../diary/diary_edit_screen/bloc/diary_edit_bloc.dart | 9 +++++---- .../profile/my_profile_screen/bloc/my_profile_bloc.dart | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart index 5a04a681..1bf38360 100644 --- a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart +++ b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart @@ -50,14 +50,14 @@ class DiaryEditBloc extends Bloc { final box = await Hive.openBox('token'); final token = box.get('token'); //print(await fetchDiaryId(token)); - final int diaryId = await fetchDiaryId(token); + final int diaryId = await fetchDiaryId(token, emit); try { print("Diary ID fetched"); final diary = await fetchDiaryData(token, diaryId); print("Screen load success"); if (diary is Map) { final String diaryDate = diary['date'] ?? DateTime.now().toString(); - final chartValues = await fetchChartValues(token, diaryId); + final chartValues = await fetchChartValues(token, diaryId, emit); if (state is DiaryEditLoadedState) { // Если текущее состояние уже загружено, обновляем его var currentState = state as DiaryEditLoadedState; @@ -137,7 +137,7 @@ class DiaryEditBloc extends Bloc { } } - fetchDiaryId(String token) async { + fetchDiaryId(String token, Emitter emit) async { final response = await http.get( Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/index'), headers: { @@ -175,7 +175,8 @@ class DiaryEditBloc extends Bloc { return diary; } - fetchChartValues(String token, int diaryID) async { + fetchChartValues( + String token, int diaryID, Emitter emit) async { final responseChart = await http.get( Uri.parse( dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/dailyNutritionData/'), diff --git a/lib/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart b/lib/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart index 95f3227a..29c6c673 100644 --- a/lib/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart +++ b/lib/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart @@ -1,4 +1,4 @@ -import 'package:eatvio_app/presentation/auth/auth_screen/auth_screen.dart'; +//import 'package:eatvio_app/presentation/auth/auth_screen/auth_screen.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import '/core/app_export.dart'; From e815ad9e3d6c3f4ecbbd6713d4b1f6c30e8e82f9 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Mon, 15 Apr 2024 16:46:04 +0300 Subject: [PATCH 11/11] refactor(diary): Emitter warnings resolved --- test/diary_test.dart | 1 + 1 file changed, 1 insertion(+) diff --git a/test/diary_test.dart b/test/diary_test.dart index b539eb33..224b05a3 100644 --- a/test/diary_test.dart +++ b/test/diary_test.dart @@ -24,6 +24,7 @@ void main() { diaryId: 1, selectedSatiety: 4, autocompleteList: [], + photos: [], portions: [], wakeupExpanded: false, moderationExpanded: false,