From c83bfee7cc81552fcd6a716723d6d0e786e704e2 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 2 Aug 2024 10:20:06 +0300 Subject: [PATCH 1/5] feat(app): Server changed to dev2 --- lib/core/constants/constants.dart | 2 +- .../initialization_cubit.dart | 23 +++++++++++++------ .../bloc/chat_room_cubit/chat_room_cubit.dart | 21 ++++++++++++----- 3 files changed, 32 insertions(+), 14 deletions(-) diff --git a/lib/core/constants/constants.dart b/lib/core/constants/constants.dart index c0353c48..4daf5231 100644 --- a/lib/core/constants/constants.dart +++ b/lib/core/constants/constants.dart @@ -1 +1 @@ -const String baseUrl = 'https://mobile-stage.eatvio.ru'; +const String baseUrl = 'https://dev2.eatvio.ru'; diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index 4a1bcaf2..dd06a97a 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -11,13 +11,18 @@ class InitializationCubit extends Cubit { final ChatRepository chatRepository; bool wasInitialized = false; - InitializationCubit({required this.chatRepository}) : super(const InitializationState.loading()); + InitializationCubit({required this.chatRepository}) + : super(const InitializationState.loading()); - Future subscribeNotifications(int userId, PusherChannelsClient client) async { + Future subscribeNotifications( + int userId, PusherChannelsClient client) async { final privateNotificationChannel = await client.privateChannel( 'private-message-events.$userId', - authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( - authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), + authorizationDelegate: + EndpointAuthorizableChannelTokenAuthorizationDelegate + .forPrivateChannel( + authorizationEndpoint: + Uri.parse('https://dev2.eatvio.ru/broadcasting/auth'), headers: { 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, @@ -31,11 +36,15 @@ class InitializationCubit extends Cubit { }); } - Future subscribeChatMessages(int userId, PusherChannelsClient client) async { + Future subscribeChatMessages( + int userId, PusherChannelsClient client) async { final privateMessagesChannel = await client.privateChannel( 'private-new-chat-messages.$userId', - authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( - authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), + authorizationDelegate: + EndpointAuthorizableChannelTokenAuthorizationDelegate + .forPrivateChannel( + authorizationEndpoint: + Uri.parse('https://dev2.eatvio.ru/broadcasting/auth'), headers: { 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart index 3773c43c..49ab7678 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart @@ -39,12 +39,16 @@ class ChatRoomCubit extends Cubit { )); try { - final chatMessages = await chatRepository.getChatMessages(chatId, currentPage + 1); + final chatMessages = + await chatRepository.getChatMessages(chatId, currentPage + 1); isLoading = false; emit(ChatRoomState.loaded( chatRoom: (state as ChatRoomStateLoaded).chatRoom, - chatMessages: [...(state as ChatRoomStateLoaded).chatMessages, ...chatMessages.messagesList], + chatMessages: [ + ...(state as ChatRoomStateLoaded).chatMessages, + ...chatMessages.messagesList + ], isTyping: (state as ChatRoomStateLoaded).isTyping, isLoading: isLoading, )); @@ -61,10 +65,12 @@ class ChatRoomCubit extends Cubit { try { final chatRoom = await chatRepository.getChatRoom(chatId); - final chatMessages = await chatRepository.getChatMessages(chatId, currentPage); + final chatMessages = + await chatRepository.getChatMessages(chatId, currentPage); lastPage = chatMessages.meta.lastPage; - await subscribeToChatChannel(initCubit: initializationCubit, chatId: chatId); + await subscribeToChatChannel( + initCubit: initializationCubit, chatId: chatId); emit(ChatRoomState.loaded( chatRoom: chatRoom, @@ -86,8 +92,11 @@ class ChatRoomCubit extends Cubit { privateChatChannel = await client.privateChannel( 'private-direct-chat.$chatId', - authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( - authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), + authorizationDelegate: + EndpointAuthorizableChannelTokenAuthorizationDelegate + .forPrivateChannel( + authorizationEndpoint: + Uri.parse('https://dev2.eatvio.ru/broadcasting/auth'), headers: { 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, From f3d099fe0c938d8b0e09f1c0660f510340028100 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 2 Aug 2024 07:29:32 +0000 Subject: [PATCH 2/5] revert c83bfee7cc81552fcd6a716723d6d0e786e704e2 revert feat(app): Server changed to dev2 --- lib/core/constants/constants.dart | 2 +- .../initialization_cubit.dart | 23 ++++++------------- .../bloc/chat_room_cubit/chat_room_cubit.dart | 21 +++++------------ 3 files changed, 14 insertions(+), 32 deletions(-) diff --git a/lib/core/constants/constants.dart b/lib/core/constants/constants.dart index 4daf5231..c0353c48 100644 --- a/lib/core/constants/constants.dart +++ b/lib/core/constants/constants.dart @@ -1 +1 @@ -const String baseUrl = 'https://dev2.eatvio.ru'; +const String baseUrl = 'https://mobile-stage.eatvio.ru'; diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index dd06a97a..4a1bcaf2 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -11,18 +11,13 @@ class InitializationCubit extends Cubit { final ChatRepository chatRepository; bool wasInitialized = false; - InitializationCubit({required this.chatRepository}) - : super(const InitializationState.loading()); + InitializationCubit({required this.chatRepository}) : super(const InitializationState.loading()); - Future subscribeNotifications( - int userId, PusherChannelsClient client) async { + Future subscribeNotifications(int userId, PusherChannelsClient client) async { final privateNotificationChannel = await client.privateChannel( 'private-message-events.$userId', - authorizationDelegate: - EndpointAuthorizableChannelTokenAuthorizationDelegate - .forPrivateChannel( - authorizationEndpoint: - Uri.parse('https://dev2.eatvio.ru/broadcasting/auth'), + authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( + authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), headers: { 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, @@ -36,15 +31,11 @@ class InitializationCubit extends Cubit { }); } - Future subscribeChatMessages( - int userId, PusherChannelsClient client) async { + Future subscribeChatMessages(int userId, PusherChannelsClient client) async { final privateMessagesChannel = await client.privateChannel( 'private-new-chat-messages.$userId', - authorizationDelegate: - EndpointAuthorizableChannelTokenAuthorizationDelegate - .forPrivateChannel( - authorizationEndpoint: - Uri.parse('https://dev2.eatvio.ru/broadcasting/auth'), + authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( + authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), headers: { 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart index 49ab7678..3773c43c 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart @@ -39,16 +39,12 @@ class ChatRoomCubit extends Cubit { )); try { - final chatMessages = - await chatRepository.getChatMessages(chatId, currentPage + 1); + final chatMessages = await chatRepository.getChatMessages(chatId, currentPage + 1); isLoading = false; emit(ChatRoomState.loaded( chatRoom: (state as ChatRoomStateLoaded).chatRoom, - chatMessages: [ - ...(state as ChatRoomStateLoaded).chatMessages, - ...chatMessages.messagesList - ], + chatMessages: [...(state as ChatRoomStateLoaded).chatMessages, ...chatMessages.messagesList], isTyping: (state as ChatRoomStateLoaded).isTyping, isLoading: isLoading, )); @@ -65,12 +61,10 @@ class ChatRoomCubit extends Cubit { try { final chatRoom = await chatRepository.getChatRoom(chatId); - final chatMessages = - await chatRepository.getChatMessages(chatId, currentPage); + final chatMessages = await chatRepository.getChatMessages(chatId, currentPage); lastPage = chatMessages.meta.lastPage; - await subscribeToChatChannel( - initCubit: initializationCubit, chatId: chatId); + await subscribeToChatChannel(initCubit: initializationCubit, chatId: chatId); emit(ChatRoomState.loaded( chatRoom: chatRoom, @@ -92,11 +86,8 @@ class ChatRoomCubit extends Cubit { privateChatChannel = await client.privateChannel( 'private-direct-chat.$chatId', - authorizationDelegate: - EndpointAuthorizableChannelTokenAuthorizationDelegate - .forPrivateChannel( - authorizationEndpoint: - Uri.parse('https://dev2.eatvio.ru/broadcasting/auth'), + authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( + authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), headers: { 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, From 5d13358fbc322e7ea7a7101dde2cfbfce8230c01 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 2 Aug 2024 18:08:28 +0300 Subject: [PATCH 3/5] feat(diary): Diary ID is passed on calendar click, new layouts for calendar, fixed nutrition chart --- lib/app_router.dart | 15 +- .../calendar/models/calendar_entry_model.dart | 20 ++ .../presentation/pages/calendar_screen.dart | 221 ++++++++++++------ .../diary/presentation/bloc/diary_bloc.dart | 58 +++-- .../presentation/pages/diary_screen.dart | 24 +- 5 files changed, 230 insertions(+), 108 deletions(-) create mode 100644 lib/features/calendar/models/calendar_entry_model.dart diff --git a/lib/app_router.dart b/lib/app_router.dart index 5eb1d0cc..0b89f71b 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -68,10 +68,14 @@ class AppRouter { builder: (context, state) => FeedScreenNew(), ), GoRoute( - path: '/diary-screen', - name: 'diaryScreen', - builder: (context, state) => DiaryScreen(), - ), + path: '/diary-screen', + name: 'diaryScreen', + builder: (context, state) { + if (state.extra != null) + return DiaryScreen(diaryID: state.extra as String); + else + return DiaryScreen(diaryID: '0'); + }), GoRoute( path: '/chat-select-screen', name: 'chatSelectScreen', @@ -87,7 +91,8 @@ class AppRouter { GoRoute( path: '/blog-post-screen', name: 'blogPostScreen', - builder: (context, state) => BlogPostScreen(blogPostID: state.extra as String), + builder: (context, state) => + BlogPostScreen(blogPostID: state.extra as String), ), GoRoute( path: '/blog-post-edit-screen', diff --git a/lib/features/calendar/models/calendar_entry_model.dart b/lib/features/calendar/models/calendar_entry_model.dart new file mode 100644 index 00000000..d9fa7049 --- /dev/null +++ b/lib/features/calendar/models/calendar_entry_model.dart @@ -0,0 +1,20 @@ +import 'package:eatvio_app/core/app_export.dart'; + +/// This class is used in the [userprofile_item_widget] screen. +// ignore_for_file: must_be_immutable + +class CalendarEntryModel { + String? date; + String? status; + String id; + + CalendarEntryModel({ + this.date, + this.status, + required this.id, + }) { + date = date; + status = status; + id = id; + } +} diff --git a/lib/features/calendar/presentation/pages/calendar_screen.dart b/lib/features/calendar/presentation/pages/calendar_screen.dart index ab90403e..3824512e 100644 --- a/lib/features/calendar/presentation/pages/calendar_screen.dart +++ b/lib/features/calendar/presentation/pages/calendar_screen.dart @@ -1,11 +1,10 @@ // ignore_for_file: unused_local_variable -import 'package:eatvio_app/features/calendar/models/calendar_model.dart'; import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_cubit.dart'; import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_state.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:go_router/go_router.dart'; -import 'package:table_calendar/table_calendar.dart'; +import 'package:intl/intl.dart'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; @@ -54,7 +53,7 @@ class CalendarScreen extends StatelessWidget { toolbarHeight: 0, automaticallyImplyLeading: false, ), - backgroundColor: Color.fromARGB(255, 240, 242, 245), + backgroundColor: Colors.white, resizeToAvoidBottomInset: true, body: SizedBox( width: double.maxFinite, @@ -83,82 +82,154 @@ class CalendarScreen extends StatelessWidget { } _buildCalendarBody(BuildContext context, CalendarStateLoaded state) { - return Container( - margin: EdgeInsets.symmetric(horizontal: 16.h, vertical: 16.h), - padding: EdgeInsets.symmetric( - horizontal: 24.h, - vertical: 12.v, - ), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: const BorderRadius.all(Radius.circular(12)), - boxShadow: [ - BoxShadow( - color: Colors.grey.withOpacity(0.5), - spreadRadius: 2, - blurRadius: 5, - offset: Offset(0, 3), + return ListView.separated( + padding: EdgeInsets.all(8), + shrinkWrap: true, + physics: NeverScrollableScrollPhysics(), + separatorBuilder: (context, index) { + return SizedBox( + height: 2.v, + ); + }, + itemCount: state.calendarList.length, + itemBuilder: (context, index) { + Map diary = {}; + if (state.calendarList[index].diary is List) { + diary['status'] = 'Скоро'; + } else if (state.calendarList[index].diary is Map) { + diary = state.calendarList[index].diary as Map; + } + return InkWell( + borderRadius: BorderRadiusStyle.circleBorder8, + onTap: () => GoRouter.of(context).go( + '/diary-screen', + extra: diary['id'].toString(), ), - ], - ), - child: TableCalendar( - locale: 'ru_RU', - firstDay: DateTime.utc(2010, 10, 16), - lastDay: DateTime.utc(2030, 3, 14), - focusedDay: DateTime.now(), - startingDayOfWeek: StartingDayOfWeek.monday, - calendarBuilders: CalendarBuilders( - selectedBuilder: (context, day, focusedDay) => - _buildCellDate(context, day, focusedDay: focusedDay, state), - defaultBuilder: (context, day, focusedDay) => - _buildCellDate(context, day, state), - todayBuilder: (context, day, focusedDay) => - _buildCellDate(context, day, state), - ), - ), + child: Ink( + padding: EdgeInsets.all(8), + decoration: BoxDecoration( + borderRadius: BorderRadiusStyle.circleBorder8, + color: getBackgroundColor(diary['state']), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + formatDate(state.calendarList[index].date), + style: theme.textTheme.titleMedium, + ), + SizedBox(height: 2.v), + if (diary['state'] != null) + Row(children: [ + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: diary['state'] == 'finished' + ? Color.fromRGBO(1, 154, 62, 1) + : Color.fromRGBO(154, 74, 1, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + _getStateText(diary['state'] ?? ''), + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + SizedBox(width: 4), + if (diary['state'] == 'started') + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(13, 110, 253, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Заполнить отчет', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + if (diary['state'] == 'finished') + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(13, 110, 253, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Изменить отчет', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + ]), + if (state.calendarList[index].diary is List) + Container( + padding: + EdgeInsets.all(4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(108, 117, 125, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Cкоро', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + ], + ), + ), + ], + ), + ), + ); + }, ); } } -Widget _buildCellDate( - BuildContext context, DateTime day, CalendarStateLoaded state, - {DateTime? focusedDay}) { - final String dayString = day.toIso8601String().split('T').first; - final List calendarModels = state.calendarList; - - // Находим первую модель, соответствующую дате - final CalendarModel model = calendarModels.firstWhere( - (model) => model.date == dayString, - orElse: () => CalendarModel(date: dayString, diary: {})); - - Color? bgclr; // Объявляем переменную bgclr здесь - - final Map diary = model.diary as Map; - if (model.diary is Map) { - if (diary['state'] == "started") { - bgclr = Colors.grey; - } else if (diary['state'] == "finished") { - bgclr = Colors.green; - } else { - bgclr = Colors.white; - } - } else { - bgclr = Colors.white; // Значение по умолчанию, если diary не является Map +String _getStateText(String state) { + switch (state) { + case 'finished': + return 'Готово'; + case 'started': + return 'В процессе'; + default: + return ''; // Возвращаем пустую строку, если состояние не распознано + } +} + +String formatDate(String dateString) { + // Преобразуем строку в объект DateTime + DateTime dateTime = DateTime.parse(dateString); + + // Форматируем дату + String formattedDate = DateFormat('d MMMM', 'ru_RU').format(dateTime); + + // Возвращаем результат в нужном формате + return '$formattedDate'; +} + +Color getBackgroundColor(String? status) { + switch (status) { + case 'finished': + return Color.fromRGBO(1, 154, 62, .1); + case 'started': + return Color.fromRGBO(154, 74, 1, .1); + default: + return Color.fromRGBO(126, 136, 151, .1); } - - return GestureDetector( - onTap: () => GoRouter.of(context).pushNamed( - 'diaryScreen', - extra: diary['id'], - ), - child: Container( - margin: const EdgeInsets.all(5), - alignment: Alignment.center, - decoration: BoxDecoration( - shape: (day == focusedDay) ? BoxShape.circle : BoxShape.rectangle, - color: bgclr, - borderRadius: (day == focusedDay) ? null : BorderRadius.circular(4), - ), - child: Text(day.day.toString(), style: TextStyle(color: Colors.black)), - )); } diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index b81dd215..9c18af53 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -16,7 +16,8 @@ part 'diary_event.dart'; class DiaryBloc extends Bloc { final DiaryRepository diaryRepository; - DiaryBloc({required this.diaryRepository}) : super(const DiaryState.loading()) { + DiaryBloc({required this.diaryRepository}) + : super(const DiaryState.loading()) { on(loadDiary); on(_changeSatiety); // пользователь нажимает на шкалу сытости on(_changeMood); // пользователь нажимает на шкалу настроения @@ -53,18 +54,33 @@ class DiaryBloc extends Bloc { final DiaryModel diary = await diaryRepository.getDiary(diaryID ?? 45); final Meal currentMeal = diary.meals[0]; - List portionList = [SelectionPopupModel(title: "gr"), SelectionPopupModel(title: "pcs")]; + List portionList = [ + SelectionPopupModel(title: "gr"), + SelectionPopupModel(title: "pcs") + ]; - final Map chartData = await diaryRepository.getChartData(diaryID ?? 45); - final Map dailyNutritionIntake = chartData['dailyNutritionIntake']!; - final Map dailyNutritionRecommendations = chartData['dailyNutritionRecommendation']!; - final double ccal = dailyNutritionIntake['energy']! / dailyNutritionRecommendations['energy']! * 50; - final double proteins = dailyNutritionIntake['proteins']! / dailyNutritionRecommendations['proteins']! * 50; - final double fats = dailyNutritionIntake['fats']! / dailyNutritionRecommendations['fats']! * 50; - final double carbs = dailyNutritionIntake['carbohydrates']! / dailyNutritionRecommendations['carbohydrates']! * 50; + final Map chartData = + await diaryRepository.getChartData(diaryID ?? 45); + print(chartData); + final Map dailyNutritionIntake = + chartData['dailyNutritionIntake']!; + final Map dailyNutritionRecommendations = + chartData['dailyNutritionRecommendation']!; + final double ccal = dailyNutritionIntake['energy']! / + dailyNutritionRecommendations['energy']! * + 100; + final double proteins = dailyNutritionIntake['proteins']! / + dailyNutritionRecommendations['proteins']! * + 100; + final double fats = dailyNutritionIntake['fats']! / + dailyNutritionRecommendations['fats']! * + 100; + final double carbs = dailyNutritionIntake['carbohydrates']! / + dailyNutritionRecommendations['carbohydrates']! * + 100; Color getColor(double value) { - if (value >= 99.1) { + if (value >= 49.1) { return Colors.red; } else { return Colors.blue; @@ -86,7 +102,6 @@ class DiaryBloc extends Bloc { SelectionPopupModel(title: "Прием пищи 5", id: 5), SelectionPopupModel(title: "Прием пищи 6", id: 6), ]; - emit(DiaryState.loaded( diary: diary, currentMeal: currentMeal, @@ -163,9 +178,11 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = currentState.copyWith(wakeupController: event.selectedTime); + var updatedState = + currentState.copyWith(wakeupController: event.selectedTime); final DateFormat formatter = DateFormat('HH:mm'); - final String wakeupString = formatter.format(DateTime(2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); + final String wakeupString = formatter.format(DateTime( + 2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); await diaryRepository.changeWakeup( currentState.diary.id, wakeupString, @@ -180,9 +197,11 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = currentState.copyWith(retireController: event.selectedTime); + var updatedState = + currentState.copyWith(retireController: event.selectedTime); final DateFormat formatter = DateFormat('HH:mm'); - final String retireString = formatter.format(DateTime(2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); + final String retireString = formatter.format(DateTime( + 2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); await diaryRepository.changeRetire( currentState.diary.id, retireString, @@ -208,7 +227,8 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { final currentState = state as DiaryStateLoaded; - final Meal meal = currentState.diary.meals.firstWhere((meal) => meal.type == event.value.id); + final Meal meal = currentState.diary.meals + .firstWhere((meal) => meal.type == event.value.id); DiaryStateLoaded updatedState = currentState.copyWith( currentMeal: meal, portions: meal.portions, @@ -227,10 +247,12 @@ class DiaryBloc extends Bloc { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - final Map> productNutritionalValues = await diaryRepository.inputProduct(event.input); + final Map> productNutritionalValues = + await diaryRepository.inputProduct(event.input); var updatedState = currentState.copyWith( product_nameController: TextEditingController(text: event.input), - autocompleteList: productNutritionalValues['product_nutritional_value'] ?? [], + autocompleteList: + productNutritionalValues['product_nutritional_value'] ?? [], ); if (event.input.length > 3) { updatedState = updatedState.copyWith(moderationExpanded: true); diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index e41d0525..cd66fb0c 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -23,7 +23,13 @@ import 'package:syncfusion_flutter_charts/charts.dart'; // ignore: must_be_immutable class DiaryScreen extends StatelessWidget { - DiaryScreen({Key? key}) : super(key: key); + final String? diaryID; + + const DiaryScreen({ + this.diaryID, + super.key, + }); + Widget build(BuildContext context) { return BlocBuilder( builder: (context, state) { @@ -141,7 +147,6 @@ class DiaryScreen extends StatelessWidget { alignment: Alignment.centerRight, widthFactor: 0.5, child: SfCircularChart( - legend: Legend(isVisible: false), series: [ RadialBarSeries( dataSource: state.chartData, @@ -153,30 +158,29 @@ class DiaryScreen extends StatelessWidget { ), ), )), - SizedBox(height: 16.0), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('Калории'), - Text('Белки'), - Text('Жиры'), Text('Углеводы'), + Text('Жиры'), + Text('Белки'), + Text('Калории'), ], ), Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( - '${state.chartData![0].nutrition.toStringAsFixed(1)}'), // Калории + '${state.chartData![3].nutrition.toStringAsFixed(0)}%'), // Калории Text( - '${state.chartData![1].nutrition.toStringAsFixed(1)}'), // Белки + '${state.chartData![2].nutrition.toStringAsFixed(0)}%'), // Белки Text( - '${state.chartData![2].nutrition.toStringAsFixed(1)}'), // Жиры + '${state.chartData![1].nutrition.toStringAsFixed(0)}%'), // Жиры Text( - '${state.chartData![3].nutrition.toStringAsFixed(1)}'), // Углеводы + '${state.chartData![0].nutrition.toStringAsFixed(0)}% '), // Углеводы ], ), ], From 5ddaf42a5f4a6e6e852c547c5891861c9bc7f242 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 2 Aug 2024 18:08:39 +0300 Subject: [PATCH 4/5] feat(diary): Diary ID is passed on calendar click, new layouts for calendar, fixed nutrition chart --- lib/features/calendar/models/calendar_entry_model.dart | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/features/calendar/models/calendar_entry_model.dart b/lib/features/calendar/models/calendar_entry_model.dart index d9fa7049..e0ce0d5c 100644 --- a/lib/features/calendar/models/calendar_entry_model.dart +++ b/lib/features/calendar/models/calendar_entry_model.dart @@ -1,5 +1,3 @@ -import 'package:eatvio_app/core/app_export.dart'; - /// This class is used in the [userprofile_item_widget] screen. // ignore_for_file: must_be_immutable From 45e796152c5a4bd8a3df978acab3a032cc8cbf17 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Tue, 6 Aug 2024 14:28:03 +0300 Subject: [PATCH 5/5] feat(calendar): Calendar to diary transition --- .../presentation/pages/calendar_screen.dart | 265 ++++++++++++------ .../diary/presentation/bloc/diary_bloc.dart | 103 ++++++- .../diary/presentation/bloc/diary_event.dart | 9 + .../diary/presentation/bloc/diary_state.dart | 4 +- .../bloc/diary_state.freezed.dart | 78 ++++-- .../presentation/pages/diary_screen.dart | 3 + 6 files changed, 346 insertions(+), 116 deletions(-) diff --git a/lib/features/calendar/presentation/pages/calendar_screen.dart b/lib/features/calendar/presentation/pages/calendar_screen.dart index 3824512e..320ad2c9 100644 --- a/lib/features/calendar/presentation/pages/calendar_screen.dart +++ b/lib/features/calendar/presentation/pages/calendar_screen.dart @@ -96,106 +96,199 @@ class CalendarScreen extends StatelessWidget { Map diary = {}; if (state.calendarList[index].diary is List) { diary['status'] = 'Скоро'; - } else if (state.calendarList[index].diary is Map) { - diary = state.calendarList[index].diary as Map; - } - return InkWell( - borderRadius: BorderRadiusStyle.circleBorder8, - onTap: () => GoRouter.of(context).go( - '/diary-screen', - extra: diary['id'].toString(), - ), - child: Ink( - padding: EdgeInsets.all(8), - decoration: BoxDecoration( - borderRadius: BorderRadiusStyle.circleBorder8, - color: getBackgroundColor(diary['state']), - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - formatDate(state.calendarList[index].date), - style: theme.textTheme.titleMedium, - ), - SizedBox(height: 2.v), - if (diary['state'] != null) - Row(children: [ + return InkWell( + borderRadius: BorderRadiusStyle.circleBorder8, + child: Ink( + padding: EdgeInsets.all(8), + decoration: BoxDecoration( + borderRadius: BorderRadiusStyle.circleBorder8, + color: getBackgroundColor(diary['state']), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + formatDate(state.calendarList[index].date), + style: theme.textTheme.titleMedium, + ), + SizedBox(height: 2.v), + if (diary['state'] != null) + Row(children: [ + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: diary['state'] == 'finished' + ? Color.fromRGBO(1, 154, 62, 1) + : Color.fromRGBO(154, 74, 1, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + _getStateText(diary['state'] ?? ''), + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + SizedBox(width: 4), + if (diary['state'] == 'started') + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(13, 110, 253, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Заполнить отчет', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + if (diary['state'] == 'finished') + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(13, 110, 253, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Изменить отчет', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + ]), + if (state.calendarList[index].diary is List) Container( padding: EdgeInsets.all( 4.0), // Отступы внутри контейнера decoration: BoxDecoration( - color: diary['state'] == 'finished' - ? Color.fromRGBO(1, 154, 62, 1) - : Color.fromRGBO(154, 74, 1, 1), + color: Color.fromRGBO(108, 117, 125, 1), borderRadius: BorderRadius.circular( 24.0), // Закругленные углы ), child: Text( - _getStateText(diary['state'] ?? ''), + 'Cкоро', style: CustomTextStyles .titleSmallBold, // Предполагается, что текст белый ), ), - SizedBox(width: 4), - if (diary['state'] == 'started') - Container( - padding: EdgeInsets.all( - 4.0), // Отступы внутри контейнера - decoration: BoxDecoration( - color: Color.fromRGBO(13, 110, 253, 1), - borderRadius: BorderRadius.circular( - 24.0), // Закругленные углы - ), - child: Text( - 'Заполнить отчет', - style: CustomTextStyles - .titleSmallBold, // Предполагается, что текст белый - ), - ), - if (diary['state'] == 'finished') - Container( - padding: EdgeInsets.all( - 4.0), // Отступы внутри контейнера - decoration: BoxDecoration( - color: Color.fromRGBO(13, 110, 253, 1), - borderRadius: BorderRadius.circular( - 24.0), // Закругленные углы - ), - child: Text( - 'Изменить отчет', - style: CustomTextStyles - .titleSmallBold, // Предполагается, что текст белый - ), - ), - ]), - if (state.calendarList[index].diary is List) - Container( - padding: - EdgeInsets.all(4.0), // Отступы внутри контейнера - decoration: BoxDecoration( - color: Color.fromRGBO(108, 117, 125, 1), - borderRadius: BorderRadius.circular( - 24.0), // Закругленные углы - ), - child: Text( - 'Cкоро', - style: CustomTextStyles - .titleSmallBold, // Предполагается, что текст белый - ), - ), - ], + ], + ), ), - ), - ], + ], + ), ), - ), - ); + ); + } else { + diary = state.calendarList[index].diary as Map; + return InkWell( + borderRadius: BorderRadiusStyle.circleBorder8, + onTap: () => GoRouter.of(context).go( + '/diary-screen', + extra: diary['id'].toString(), + ), + child: Ink( + padding: EdgeInsets.all(8), + decoration: BoxDecoration( + borderRadius: BorderRadiusStyle.circleBorder8, + color: getBackgroundColor(diary['state']), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + formatDate(state.calendarList[index].date), + style: theme.textTheme.titleMedium, + ), + SizedBox(height: 2.v), + if (diary['state'] != null) + Row(children: [ + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: diary['state'] == 'finished' + ? Color.fromRGBO(1, 154, 62, 1) + : Color.fromRGBO(154, 74, 1, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + _getStateText(diary['state'] ?? ''), + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + SizedBox(width: 4), + if (diary['state'] == 'started') + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(13, 110, 253, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Заполнить отчет', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + if (diary['state'] == 'finished') + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(13, 110, 253, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Изменить отчет', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + ]), + if (state.calendarList[index].diary is List) + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(108, 117, 125, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Cкоро', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + ], + ), + ), + ], + ), + ), + ); + } }, ); } diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index 9c18af53..379aaeae 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -19,6 +19,7 @@ class DiaryBloc extends Bloc { DiaryBloc({required this.diaryRepository}) : super(const DiaryState.loading()) { on(loadDiary); + on(loadDiaryById); on(_changeSatiety); // пользователь нажимает на шкалу сытости on(_changeMood); // пользователь нажимает на шкалу настроения on(_changeMealTime); // пользовательяет времяа пиши @@ -61,26 +62,25 @@ class DiaryBloc extends Bloc { final Map chartData = await diaryRepository.getChartData(diaryID ?? 45); - print(chartData); final Map dailyNutritionIntake = chartData['dailyNutritionIntake']!; final Map dailyNutritionRecommendations = chartData['dailyNutritionRecommendation']!; final double ccal = dailyNutritionIntake['energy']! / dailyNutritionRecommendations['energy']! * - 100; + 50; final double proteins = dailyNutritionIntake['proteins']! / dailyNutritionRecommendations['proteins']! * - 100; + 50; final double fats = dailyNutritionIntake['fats']! / dailyNutritionRecommendations['fats']! * - 100; + 50; final double carbs = dailyNutritionIntake['carbohydrates']! / dailyNutritionRecommendations['carbohydrates']! * - 100; + 50; Color getColor(double value) { - if (value >= 49.1) { + if (value >= 99.1) { return Colors.red; } else { return Colors.blue; @@ -102,6 +102,97 @@ class DiaryBloc extends Bloc { SelectionPopupModel(title: "Прием пищи 5", id: 5), SelectionPopupModel(title: "Прием пищи 6", id: 6), ]; + + emit(DiaryState.loaded( + diary: diary, + currentMeal: currentMeal, + portions: currentMeal.portions, + portionList: portionList, + portionController: portionList[0], + mealList: mealList, + chartData: chartDataCounted, + selectedMood: currentMeal.mood, + selectedSatiety: currentMeal.satiety, + wakeupController: TimeOfDay.now(), + retireController: TimeOfDay.now(), + commentController: TextEditingController(), + product_nameController: TextEditingController(), + productQuantityController: TextEditingController(), + caloriesController: TextEditingController(), + fatsController: TextEditingController(), + proteinsController: TextEditingController(), + carbsController: TextEditingController(), + wakeupExpanded: false, + moderationExpanded: false, + moodExpanded: false, + isLoading: false, + isAdded: false, + autocompleteList: [], + recommendedChartValues: [1, 1, 1, 1], + consumedChartValues: [1, 1, 1, 1])); + } catch (e) { + emit(DiaryState.error(errorMessage: e.toString())); + } + } + + loadDiaryById( + LoadDiaryById event, + Emitter emit, + ) async { + emit(const DiaryState.loading()); + try { + final int diaryID = int.parse(event.id ?? "0"); + final DiaryModel diary = await diaryRepository.getDiary(diaryID); + final Meal currentMeal = diary.meals[0]; + + List portionList = [ + SelectionPopupModel(title: "gr"), + SelectionPopupModel(title: "pcs") + ]; + + final Map chartData = + await diaryRepository.getChartData(diaryID); + final Map dailyNutritionIntake = + chartData['dailyNutritionIntake']!; + final Map dailyNutritionRecommendations = + chartData['dailyNutritionRecommendation']!; + final double ccal = dailyNutritionIntake['energy']! / + dailyNutritionRecommendations['energy']! * + 50; + final double proteins = dailyNutritionIntake['proteins']! / + dailyNutritionRecommendations['proteins']! * + 50; + final double fats = dailyNutritionIntake['fats']! / + dailyNutritionRecommendations['fats']! * + 50; + final double carbs = dailyNutritionIntake['carbohydrates']! / + dailyNutritionRecommendations['carbohydrates']! * + 50; + + Color getColor(double value) { + if (value >= 99.1) { + return Colors.red; + } else { + return Colors.blue; + } + } + + final List chartDataCounted = [ + NutritionData('Калории', ccal, getColor(ccal)), + NutritionData('Белки', proteins, getColor(proteins)), + NutritionData('Жиры', fats, getColor(fats)), + NutritionData('Углеводы', carbs, getColor(carbs)), + ]; + + List mealList = [ + SelectionPopupModel(title: "Прием пищи 1", id: 1), + SelectionPopupModel(title: "Прием пищи 2", id: 2), + SelectionPopupModel(title: "Прием пищи 3", id: 3), + SelectionPopupModel(title: "Прием пищи 4", id: 4), + SelectionPopupModel(title: "Прием пищи 5", id: 5), + SelectionPopupModel(title: "Прием пищи 6", id: 6), + ]; + emit(DiaryState.loaded( diary: diary, currentMeal: currentMeal, diff --git a/lib/features/diary/presentation/bloc/diary_event.dart b/lib/features/diary/presentation/bloc/diary_event.dart index 490fa0c6..4faa190b 100644 --- a/lib/features/diary/presentation/bloc/diary_event.dart +++ b/lib/features/diary/presentation/bloc/diary_event.dart @@ -15,6 +15,15 @@ class LoadDiary extends DiaryEvent { List get props => []; } +class LoadDiaryById extends DiaryEvent { + LoadDiaryById( + this.id, + ); + final String? id; + @override + List get props => []; +} + class ChangeSatiety extends DiaryEvent { ChangeSatiety( this.selectedElement, diff --git a/lib/features/diary/presentation/bloc/diary_state.dart b/lib/features/diary/presentation/bloc/diary_state.dart index 91565766..07259914 100644 --- a/lib/features/diary/presentation/bloc/diary_state.dart +++ b/lib/features/diary/presentation/bloc/diary_state.dart @@ -13,7 +13,9 @@ part 'diary_state.freezed.dart'; abstract class DiaryState with _$DiaryState { const factory DiaryState() = _DiaryState; - const factory DiaryState.loading() = DiaryStateLoading; + const factory DiaryState.loading({ + int? id, + }) = DiaryStateLoading; const factory DiaryState.loaded({ required DiaryModel diary, diff --git a/lib/features/diary/presentation/bloc/diary_state.freezed.dart b/lib/features/diary/presentation/bloc/diary_state.freezed.dart index 99328a6d..24dbb0a9 100644 --- a/lib/features/diary/presentation/bloc/diary_state.freezed.dart +++ b/lib/features/diary/presentation/bloc/diary_state.freezed.dart @@ -19,7 +19,7 @@ mixin _$DiaryState { @optionalTypeArgs TResult when( TResult Function() $default, { - required TResult Function() loading, + required TResult Function(int? id) loading, required TResult Function( DiaryModel diary, String? diaryDate, @@ -56,7 +56,7 @@ mixin _$DiaryState { @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { - TResult? Function()? loading, + TResult? Function(int? id)? loading, TResult? Function( DiaryModel diary, String? diaryDate, @@ -93,7 +93,7 @@ mixin _$DiaryState { @optionalTypeArgs TResult maybeWhen( TResult Function()? $default, { - TResult Function()? loading, + TResult Function(int? id)? loading, TResult Function( DiaryModel diary, String? diaryDate, @@ -212,7 +212,7 @@ class _$DiaryStateImpl implements _DiaryState { @optionalTypeArgs TResult when( TResult Function() $default, { - required TResult Function() loading, + required TResult Function(int? id) loading, required TResult Function( DiaryModel diary, String? diaryDate, @@ -252,7 +252,7 @@ class _$DiaryStateImpl implements _DiaryState { @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { - TResult? Function()? loading, + TResult? Function(int? id)? loading, TResult? Function( DiaryModel diary, String? diaryDate, @@ -292,7 +292,7 @@ class _$DiaryStateImpl implements _DiaryState { @optionalTypeArgs TResult maybeWhen( TResult Function()? $default, { - TResult Function()? loading, + TResult Function(int? id)? loading, TResult Function( DiaryModel diary, String? diaryDate, @@ -379,6 +379,8 @@ abstract class _$$DiaryStateLoadingImplCopyWith<$Res> { factory _$$DiaryStateLoadingImplCopyWith(_$DiaryStateLoadingImpl value, $Res Function(_$DiaryStateLoadingImpl) then) = __$$DiaryStateLoadingImplCopyWithImpl<$Res>; + @useResult + $Res call({int? id}); } /// @nodoc @@ -388,32 +390,57 @@ class __$$DiaryStateLoadingImplCopyWithImpl<$Res> __$$DiaryStateLoadingImplCopyWithImpl(_$DiaryStateLoadingImpl _value, $Res Function(_$DiaryStateLoadingImpl) _then) : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = freezed, + }) { + return _then(_$DiaryStateLoadingImpl( + id: freezed == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int?, + )); + } } /// @nodoc class _$DiaryStateLoadingImpl implements DiaryStateLoading { - const _$DiaryStateLoadingImpl(); + const _$DiaryStateLoadingImpl({this.id}); + + @override + final int? id; @override String toString() { - return 'DiaryState.loading()'; + return 'DiaryState.loading(id: $id)'; } @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && other is _$DiaryStateLoadingImpl); + (other.runtimeType == runtimeType && + other is _$DiaryStateLoadingImpl && + (identical(other.id, id) || other.id == id)); } @override - int get hashCode => runtimeType.hashCode; + int get hashCode => Object.hash(runtimeType, id); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$DiaryStateLoadingImplCopyWith<_$DiaryStateLoadingImpl> get copyWith => + __$$DiaryStateLoadingImplCopyWithImpl<_$DiaryStateLoadingImpl>( + this, _$identity); @override @optionalTypeArgs TResult when( TResult Function() $default, { - required TResult Function() loading, + required TResult Function(int? id) loading, required TResult Function( DiaryModel diary, String? diaryDate, @@ -446,14 +473,14 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { loaded, required TResult Function(String errorMessage) error, }) { - return loading(); + return loading(id); } @override @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { - TResult? Function()? loading, + TResult? Function(int? id)? loading, TResult? Function( DiaryModel diary, String? diaryDate, @@ -486,14 +513,14 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { loaded, TResult? Function(String errorMessage)? error, }) { - return loading?.call(); + return loading?.call(id); } @override @optionalTypeArgs TResult maybeWhen( TResult Function()? $default, { - TResult Function()? loading, + TResult Function(int? id)? loading, TResult Function( DiaryModel diary, String? diaryDate, @@ -528,7 +555,7 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { required TResult orElse(), }) { if (loading != null) { - return loading(); + return loading(id); } return orElse(); } @@ -572,7 +599,12 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { } abstract class DiaryStateLoading implements DiaryState { - const factory DiaryStateLoading() = _$DiaryStateLoadingImpl; + const factory DiaryStateLoading({final int? id}) = _$DiaryStateLoadingImpl; + + int? get id; + @JsonKey(ignore: true) + _$$DiaryStateLoadingImplCopyWith<_$DiaryStateLoadingImpl> get copyWith => + throw _privateConstructorUsedError; } /// @nodoc @@ -1050,7 +1082,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { @optionalTypeArgs TResult when( TResult Function() $default, { - required TResult Function() loading, + required TResult Function(int? id) loading, required TResult Function( DiaryModel diary, String? diaryDate, @@ -1118,7 +1150,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { - TResult? Function()? loading, + TResult? Function(int? id)? loading, TResult? Function( DiaryModel diary, String? diaryDate, @@ -1186,7 +1218,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { @optionalTypeArgs TResult maybeWhen( TResult Function()? $default, { - TResult Function()? loading, + TResult Function(int? id)? loading, TResult Function( DiaryModel diary, String? diaryDate, @@ -1423,7 +1455,7 @@ class _$DiaryStateErrorImpl implements DiaryStateError { @optionalTypeArgs TResult when( TResult Function() $default, { - required TResult Function() loading, + required TResult Function(int? id) loading, required TResult Function( DiaryModel diary, String? diaryDate, @@ -1463,7 +1495,7 @@ class _$DiaryStateErrorImpl implements DiaryStateError { @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { - TResult? Function()? loading, + TResult? Function(int? id)? loading, TResult? Function( DiaryModel diary, String? diaryDate, @@ -1503,7 +1535,7 @@ class _$DiaryStateErrorImpl implements DiaryStateError { @optionalTypeArgs TResult maybeWhen( TResult Function()? $default, { - TResult Function()? loading, + TResult Function(int? id)? loading, TResult Function( DiaryModel diary, String? diaryDate, diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index cd66fb0c..fb781890 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -31,6 +31,9 @@ class DiaryScreen extends StatelessWidget { }); Widget build(BuildContext context) { + if (diaryID != "0") { + context.read().add(LoadDiaryById(diaryID)); + } return BlocBuilder( builder: (context, state) { if (state is DiaryStateLoaded) {