From 7d0de424882f183c432ddb776a04d1c7d1535ec1 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Mon, 19 Feb 2024 14:27:39 +0300 Subject: [PATCH] feat(diary) API methods added --- .../bloc/diary_edit_bloc.dart | 116 ++++++++++-------- .../bloc/diary_edit_event.dart | 31 +++-- .../bloc/diary_edit_state.dart | 10 ++ .../diary_edit_screen/diary_edit_screen.dart | 99 ++++++++++----- 4 files changed, 166 insertions(+), 90 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 b0b8b18b..37cab2b0 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 @@ -27,17 +27,16 @@ class DiaryEditBloc extends Bloc { on( _removePortion); // пользователь нажимает на крестик около продукта on(_uploadImages); //пользователь нажимает "Добавить фото" + on(_addComment); //пользователь нажимает "Добавить комментарий" } Future _onInitialize( DiaryEditInitialEvent event, Emitter emit, ) async { - /*try { - /*final box = await Hive.openBox('token'); - final token = box.get('token');*/ + try { final token = - "1|laravel_sanctum_JBjDvwoEpmFc7CmzBaktFtZPGfSpXcEVA5YgBQ380d322d92"; + "1|laravel_sanctum_8qeVUwDzs440SoG1pJFdSFtYWjJhZfEQXqStVkFPea8d4092"; final response = await http.get( Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/index'), headers: { @@ -47,42 +46,67 @@ class DiaryEditBloc extends Bloc { if (response.statusCode == 200) { final data = jsonDecode(response.body); - // Проверка наличия ключевых полей в JSON if (data is Map && data.containsKey('id')) { - // Все ключевые поля присутствуют, продолжаем обработку*/ - if (state is DiaryEditLoadedState) { - // Если текущее состояние уже загружено, обновляем его - var currentState = state as DiaryEditLoadedState; - // Обновляем значения контроллеров только если они уже были созданы - emit((currentState).copyWith( - wakeupExpanded: currentState.wakeupExpanded, - moodExpanded: currentState.moodExpanded, - wakeupController: currentState.wakeupController, - retireController: currentState.retireController, - commentController: currentState.commentController, - mealTimeController: currentState.mealTimeController, - mealNameController: currentState.mealNameController, - productNameController: currentState.productNameController, - selectedSatiety: currentState.selectedSatiety, - selectedMood: currentState.selectedMood, - productQuantityController: currentState.productQuantityController)); - } else { - // Если текущее состояние - начальное, создаем новое загруженное состояние - emit(DiaryEditLoadedState( - wakeupExpanded: true, - moodExpanded: true, - wakeupController: TimeOfDay.now(), - retireController: TimeOfDay.now(), - mealTimeController: TimeOfDay.now(), - selectedSatiety: 3, - selectedMood: 3, - mealNameController: TextEditingController(), - commentController: TextEditingController(), - productNameController: TextEditingController(), - productQuantityController: TextEditingController(), - )); - } - /*} else { + final int diaryId = data['id']; + try { + final response = await http.get( + Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/show/$diaryId'), + headers: { + 'Authorization': 'Bearer $token', + }, + ); + final diary = jsonDecode(response.body); + if (diary is Map) { + final String diaryDate = + diary['diary']['date'] ?? DateTime.now().toString(); + // Продолжайте обработку данных дневника + if (state is DiaryEditLoadedState) { + // Если текущее состояние уже загружено, обновляем его + var currentState = state as DiaryEditLoadedState; + emit((currentState).copyWith( + wakeupExpanded: currentState.wakeupExpanded, + moodExpanded: currentState.moodExpanded, + wakeupController: currentState.wakeupController, + retireController: currentState.retireController, + commentController: currentState.commentController, + mealTimeController: currentState.mealTimeController, + mealNameController: currentState.mealNameController, + productNameController: currentState.productNameController, + selectedSatiety: currentState.selectedSatiety, + selectedMood: currentState.selectedMood, + diaryDate: currentState.diaryDate, + productQuantityController: + currentState.productQuantityController, + )); + } else { + // Если текущее состояние - начальное, создаем новое загруженное состояние + emit(DiaryEditLoadedState( + wakeupExpanded: true, + moodExpanded: true, + wakeupController: TimeOfDay.now(), + retireController: TimeOfDay.now(), + mealTimeController: TimeOfDay.now(), + selectedSatiety: 3, + selectedMood: 3, + mealNameController: TextEditingController(), + commentController: TextEditingController(), + productNameController: TextEditingController(), + productQuantityController: TextEditingController(), + diaryId: diaryId, + diaryDate: diaryDate, + )); + } + } else { + // Ошибка при декодировании JSON + emit(DiaryEditErrorState( + 'Ошибка при декодировании данных дневника')); + } + } catch (e) { + // Ошибка при получении данных дневника + emit(DiaryEditErrorState( + 'Ошибка при получении данных дневника: $e')); + } + } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку emit( DiaryEditErrorState('Некоторые необходимые данные отсутствуют.')); @@ -92,9 +116,9 @@ class DiaryEditBloc extends Bloc { emit(DiaryEditErrorState('Ошибка сервера: ${response.statusCode}')); } } catch (e) { - // Ошибка при декодировании JSON или другая ошибка выполнения - emit(DiaryEditErrorState('Ошибка при получении данных профиля: $e')); - }*/ + // Ошибка при получении данных дневника + emit(DiaryEditErrorState('Ошибка при получении данных дневника: $e')); + } } Future _changeSatiety( @@ -130,8 +154,6 @@ class DiaryEditBloc extends Bloc { emit(currentState.copyWith(moodExpanded: !currentState.moodExpanded)); currentState.moodExpanded = !currentState.moodExpanded; - - print(currentState.moodExpanded); } } @@ -142,7 +164,6 @@ class DiaryEditBloc extends Bloc { emit(currentState.copyWith(wakeupExpanded: !currentState.wakeupExpanded)); currentState.wakeupExpanded = !currentState.wakeupExpanded; - print(currentState.wakeupExpanded); } } @@ -153,7 +174,6 @@ class DiaryEditBloc extends Bloc { emit(currentState.copyWith(wakeupController: event.selectedTime)); currentState.wakeupController = event.selectedTime; - print(currentState.wakeupExpanded); } } @@ -164,7 +184,6 @@ class DiaryEditBloc extends Bloc { emit(currentState.copyWith(retireController: event.selectedTime)); currentState.retireController = event.selectedTime; - print(currentState.retireController); } } @@ -177,8 +196,9 @@ class DiaryEditBloc extends Bloc { Future> _uploadImages( UploadImages event, Emitter emit) async { String imageUrl = await uploadImageToServer(event.image.path); - print(imageUrl); } + + FutureOr _addComment(AddComment event, Emitter emit) {} } Future uploadImageToServer(String imagePath) async { diff --git a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_event.dart b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_event.dart index fcc57c64..d010e840 100644 --- a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_event.dart +++ b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_event.dart @@ -16,35 +16,48 @@ class DiaryEditInitialEvent extends DiaryEditEvent { } class ChangeSatiety extends DiaryEditEvent { - ChangeSatiety(this.selectedElement); + ChangeSatiety(this.mealId, this.selectedElement); final int selectedElement; + final int mealId; @override - List get props => [selectedElement]; + List get props => [selectedElement, mealId]; } class ChangeMood extends DiaryEditEvent { - ChangeMood(this.selectedElement); + ChangeMood(this.diaryId, this.selectedElement); final int selectedElement; + final int diaryId; @override - List get props => [selectedElement]; + List get props => [selectedElement, diaryId]; +} + +class AddComment extends DiaryEditEvent { + AddComment(this.diaryId, this.comment); + final String comment; + final int diaryId; + + @override + List get props => [comment, diaryId]; } class WakeupEvent extends DiaryEditEvent { - WakeupEvent(this.selectedTime); + WakeupEvent(this.diaryId, this.selectedTime); final TimeOfDay selectedTime; + final int diaryId; @override - List get props => [selectedTime]; + List get props => [selectedTime, diaryId]; } class RetireEvent extends DiaryEditEvent { - RetireEvent(this.selectedTime); + RetireEvent(this.selectedTime, this.diaryId); final TimeOfDay selectedTime; + final int diaryId; @override - List get props => [selectedTime]; + List get props => [selectedTime, diaryId]; } class ToggleMoodExpandedEvent extends DiaryEditEvent { @@ -64,7 +77,7 @@ class AddPortionEvent extends DiaryEditEvent { final int quantity; final String portion; @override - List get props => [mealId, productId, quantity]; + List get props => [mealId, productId, quantity, portion]; } class RemovePortionEvent extends DiaryEditEvent { 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 457a8f25..96b8a48a 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 @@ -20,6 +20,7 @@ class DiaryEditInitialState extends DiaryEditState { class DiaryEditLoadedState extends DiaryEditState { DiaryEditLoadedState( {this.diaryEditModelObj, + this.diaryDate, this.wakeupController, this.retireController, this.commentController, @@ -28,12 +29,14 @@ class DiaryEditLoadedState extends DiaryEditState { this.productNameController, this.productQuantityController, this.selectedMood, + required this.diaryId, required this.selectedSatiety, required this.wakeupExpanded, required this.moodExpanded}) : super(diaryEditModelObj: null); DiaryEditModel? diaryEditModelObj; + String? diaryDate; TimeOfDay? wakeupController; TimeOfDay? retireController; TimeOfDay? mealTimeController; @@ -43,11 +46,13 @@ class DiaryEditLoadedState extends DiaryEditState { TextEditingController? productQuantityController; int? selectedMood; int selectedSatiety; + int diaryId; bool wakeupExpanded; bool moodExpanded; @override List get props => [ diaryEditModelObj, + diaryDate, wakeupController, retireController, mealNameController, @@ -57,11 +62,13 @@ class DiaryEditLoadedState extends DiaryEditState { productQuantityController, selectedMood, selectedSatiety, + diaryId, wakeupExpanded, moodExpanded ]; DiaryEditLoadedState copyWith({ DiaryEditModel? diaryEditModelObj, + String? diaryDate, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, @@ -71,11 +78,13 @@ class DiaryEditLoadedState extends DiaryEditState { TextEditingController? productQuantityController, int? selectedMood, int? selectedSatiety, + int? diaryId, bool? wakeupExpanded, bool? moodExpanded, }) { return DiaryEditLoadedState( diaryEditModelObj: diaryEditModelObj ?? this.diaryEditModelObj, + diaryDate: diaryDate ?? this.diaryDate, wakeupController: wakeupController ?? this.wakeupController, retireController: retireController ?? this.retireController, mealTimeController: mealTimeController ?? this.mealTimeController, @@ -87,6 +96,7 @@ class DiaryEditLoadedState extends DiaryEditState { productQuantityController ?? this.productQuantityController, selectedMood: selectedMood ?? this.selectedMood, selectedSatiety: selectedSatiety ?? this.selectedSatiety, + diaryId: diaryId ?? this.diaryId, wakeupExpanded: wakeupExpanded ?? this.wakeupExpanded, moodExpanded: moodExpanded ?? this.moodExpanded); } 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 6308623a..7c33df93 100644 --- a/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart +++ b/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart @@ -75,7 +75,7 @@ class DiaryEditScreen extends StatelessWidget { padding: EdgeInsets.only(bottom: 5.v), child: Column( children: [ - _buildHeaderRow(context), + _buildHeaderRow(context, state), SizedBox(height: 30.v), _buildWakupRetire(context, state), SizedBox(height: 30.v), @@ -101,7 +101,7 @@ class DiaryEditScreen extends StatelessWidget { } /// Section Widget - Widget _buildHeaderRow(BuildContext context) { + Widget _buildHeaderRow(BuildContext context, DiaryEditLoadedState state) { return Container( margin: EdgeInsets.symmetric(horizontal: 16.h, vertical: 16.h), padding: EdgeInsets.symmetric( @@ -141,7 +141,7 @@ class DiaryEditScreen extends StatelessWidget { ), SizedBox(height: 2.v), Text( - "03-08-2023", + state.diaryDate.toString(), style: CustomTextStyles.bodyMediumBluegray800, ), ], @@ -244,12 +244,18 @@ class DiaryEditScreen extends StatelessWidget { padding: EdgeInsets.symmetric(horizontal: 10.h), child: ConstrainedBox( constraints: BoxConstraints( - maxWidth: MediaQuery.of(context).size.width - 247, + maxWidth: MediaQuery.of(context).size.width - 260, ), - child: FormBuilderDateTimePicker( - name: 'mealTime', - inputType: InputType.time, - decoration: InputDecoration(), + child: GestureDetector( + onTap: () => _selectTime(context, state), + child: AbsorbPointer( + child: CustomTextFormField( + hintText: state.mealTimeController + ?.format(context) + .toString(), + autofocus: false, + ), + ), ), ), ), @@ -323,42 +329,54 @@ class DiaryEditScreen extends StatelessWidget { color: Colors.red, isSelected: state.selectedSatiety == 0, onTap: () { - context.read().add(ChangeSatiety(0)); + context + .read() + .add(ChangeSatiety(0, state.diaryId)); }, ), ScaleElement( color: Colors.orange, isSelected: state.selectedSatiety == 1, onTap: () { - context.read().add(ChangeSatiety(1)); + context + .read() + .add(ChangeSatiety(1, state.diaryId)); }, ), ScaleElement( color: Colors.yellow, isSelected: state.selectedSatiety == 2, onTap: () { - context.read().add(ChangeSatiety(2)); + context + .read() + .add(ChangeSatiety(2, state.diaryId)); }, ), ScaleElement( color: Colors.lime, isSelected: state.selectedSatiety == 3, onTap: () { - context.read().add(ChangeSatiety(3)); + context + .read() + .add(ChangeSatiety(3, state.diaryId)); }, ), ScaleElement( color: Colors.lightGreen, isSelected: state.selectedSatiety == 4, onTap: () { - context.read().add(ChangeSatiety(4)); + context + .read() + .add(ChangeSatiety(4, state.diaryId)); }, ), ScaleElement( color: Colors.green, isSelected: state.selectedSatiety == 5, onTap: () { - context.read().add(ChangeSatiety(5)); + context + .read() + .add(ChangeSatiety(5, state.diaryId)); }, ), Text("😊"), @@ -761,30 +779,33 @@ class DiaryEditScreen extends StatelessWidget { padding: const EdgeInsets.only(left: 16.0), child: Column( children: [ + SizedBox(height: 20.v), GestureDetector( onTap: () => _selectTime(context, state), child: AbsorbPointer( - child: TextFormField( - decoration: InputDecoration( - labelText: 'Во сколько вы просунились?', - prefixIcon: Icon(Icons.sunny), - ), - initialValue: state.wakeupController.toString(), + child: CustomTextFormField( + hintText: state.wakeupController + ?.format(context) + .toString(), + prefix: Icon(Icons.sunny), + autofocus: false, ), ), ), + SizedBox(height: 20.v), GestureDetector( onTap: () => _selectTime(context, state), child: AbsorbPointer( - child: TextFormField( - decoration: InputDecoration( - labelText: 'Во сколько вы легли спать?', - prefixIcon: Icon(Icons.bed), - ), - initialValue: state.retireController.toString(), + child: CustomTextFormField( + hintText: state.retireController + ?.format(context) + .toString(), + prefix: Icon(Icons.bed), + autofocus: false, ), ), - ) + ), + SizedBox(height: 20.v), ], ), ), @@ -857,42 +878,54 @@ class DiaryEditScreen extends StatelessWidget { color: Colors.red, isSelected: state.selectedMood == 0, onTap: () { - context.read().add(ChangeMood(0)); + context + .read() + .add(ChangeMood(0, state.diaryId)); }, ), ScaleElement( color: Colors.orange, isSelected: state.selectedMood == 1, onTap: () { - context.read().add(ChangeMood(1)); + context + .read() + .add(ChangeMood(1, state.diaryId)); }, ), ScaleElement( color: Colors.yellow, isSelected: state.selectedMood == 2, onTap: () { - context.read().add(ChangeMood(2)); + context + .read() + .add(ChangeMood(2, state.diaryId)); }, ), ScaleElement( color: Colors.lime, isSelected: state.selectedMood == 3, onTap: () { - context.read().add(ChangeMood(3)); + context + .read() + .add(ChangeMood(3, state.diaryId)); }, ), ScaleElement( color: Colors.lightGreen, isSelected: state.selectedMood == 4, onTap: () { - context.read().add(ChangeMood(4)); + context + .read() + .add(ChangeMood(4, state.diaryId)); }, ), ScaleElement( color: Colors.green, isSelected: state.selectedMood == 5, onTap: () { - context.read().add(ChangeMood(5)); + context + .read() + .add(ChangeMood(5, state.diaryId)); }, ), Text("😊"),