diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 00000000..017f6122 Binary files /dev/null and b/.DS_Store differ diff --git a/.env b/.env deleted file mode 100644 index e223a359..00000000 --- a/.env +++ /dev/null @@ -1,2 +0,0 @@ -SERVER_ROOT='https://mobile-stage.eatvio.ru/api' -STORAGE_URL='https://mobile-stage.eatvio.ru/storage/' \ No newline at end of file diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 955d74d5..e8e16098 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -78,7 +78,6 @@ jobs: - name: Test run: | - touch .env flutter test - name: Build apk diff --git a/.gitea/workflows/test.yml b/.gitea/workflows/test.yml index a21834f8..54d180cb 100644 --- a/.gitea/workflows/test.yml +++ b/.gitea/workflows/test.yml @@ -89,7 +89,6 @@ jobs: - name: Test run: | - touch .env flutter test - name: Build apk diff --git a/.gitignore b/.gitignore index 9d9b1cef..4a5c4e73 100644 --- a/.gitignore +++ b/.gitignore @@ -6,5 +6,4 @@ /.flutter-plugins /.flutter-plugins-dependencies /.packages -/.env /node_modules/ diff --git a/flutter_01.log b/flutter_01.log new file mode 100644 index 00000000..f7f3c20d --- /dev/null +++ b/flutter_01.log @@ -0,0 +1,97 @@ +Flutter crash report. +Please report a bug at https://github.com/flutter/flutter/issues. + +## command + +flutter analyze + +## exception + +PathNotFoundException: PathNotFoundException: Cannot open file, path = '/home/alex/snap/flutter/common/flutter/version' (OS Error: No such file or directory, errno = 2) + +``` +#0 _File.throwIfError (dart:io/file_impl.dart:675:7) +#1 _File.openSync (dart:io/file_impl.dart:490:5) +#2 _File.readAsBytesSync (dart:io/file_impl.dart:574:18) +#3 _File.readAsStringSync (dart:io/file_impl.dart:624:18) +#4 ForwardingFile.readAsStringSync (package:file/src/forwarding/forwarding_file.dart:99:16) +#5 ErrorHandlingFile.readAsStringSync. (package:flutter_tools/src/base/error_handling_io.dart:217:22) +#6 _runSync (package:flutter_tools/src/base/error_handling_io.dart:587:14) +#7 ErrorHandlingFile.readAsStringSync (package:flutter_tools/src/base/error_handling_io.dart:216:12) +#8 _DefaultPub.get (package:flutter_tools/src/dart/pub.dart:302:58) +#9 FlutterCommand.verifyThenRunCommand (package:flutter_tools/src/runner/flutter_command.dart:1724:17) + +#10 FlutterCommand.run. (package:flutter_tools/src/runner/flutter_command.dart:1394:27) + +#11 AppContext.run. (package:flutter_tools/src/base/context.dart:153:19) + +#12 CommandRunner.runCommand (package:args/command_runner.dart:212:13) + +#13 FlutterCommandRunner.runCommand. (package:flutter_tools/src/runner/flutter_command_runner.dart:372:9) + +#14 AppContext.run. (package:flutter_tools/src/base/context.dart:153:19) + +#15 FlutterCommandRunner.runCommand (package:flutter_tools/src/runner/flutter_command_runner.dart:308:5) + +#16 run.. (package:flutter_tools/runner.dart:130:9) + +#17 AppContext.run. (package:flutter_tools/src/base/context.dart:153:19) + +#18 main (package:flutter_tools/executable.dart:93:3) + +``` + +## flutter doctor + +``` +[!] Flutter (Channel [user-branch], 0.0.0-unknown, on Ubuntu 24.04 LTS 6.8.0-38-generic, locale ru_RU.UTF-8) + ! Flutter version 0.0.0-unknown on channel [user-branch] at /home/alex/snap/flutter/common/flutter + Currently on an unknown channel. Run `flutter channel` to switch to an official channel. + If that doesn't fix the issue, reinstall Flutter by following instructions at https://flutter.dev/docs/get-started/install. + Cannot resolve current version, possibly due to local changes. + Reinstall Flutter by following instructions at https://flutter.dev/docs/get-started/install. + ! Upstream repository unknown source is not a standard remote. + Set environment variable "FLUTTER_GIT_URL" to unknown source to dismiss this error. + • Framework revision (), 1970-01-01 03:00:00.000 + • Engine revision edd8546116 + • Dart version 3.4.3 + • DevTools version 2.34.3 + • If those were intentional, you can disregard the above warnings; however it is recommended to use "git" directly to perform update checks and upgrades. + +[✓] Android toolchain - develop for Android devices (Android SDK version 35.0.0) + • Android SDK at /home/alex/Android/Sdk + • Platform android-35, build-tools 35.0.0 + • Java binary at: /snap/android-studio/161/jbr/bin/java + • Java version OpenJDK Runtime Environment (build 17.0.10+0-17.0.10b1087.21-11609105) + • All Android licenses accepted. + +[✓] Chrome - develop for the web + • Chrome at google-chrome + +[✓] Linux toolchain - develop for Linux desktop + • clang version 10.0.0-4ubuntu1 + • cmake version 3.16.3 + • ninja version 1.10.0 + • pkg-config version 0.29.1 + +[✓] Android Studio (version 2024.1) + • Android Studio at /snap/android-studio/161 + • Flutter plugin version 80.0.2 + • Dart plugin can be installed from: + 🔨 https://plugins.jetbrains.com/plugin/6351-dart + • Java version OpenJDK Runtime Environment (build 17.0.10+0-17.0.10b1087.21-11609105) + +[✓] VS Code (version 1.91.1) + • VS Code at /usr/share/code + • Flutter extension version 3.92.0 + +[✓] Connected device (3 available) + • sdk gphone64 x86 64 (mobile) • emulator-5554 • android-x64 • Android 15 (API 35) (emulator) + • Linux (desktop) • linux • linux-x64 • Ubuntu 24.04 LTS 6.8.0-38-generic + • Chrome (web) • chrome • web-javascript • Google Chrome 126.0.6478.126 + +[✓] Network resources + • All expected network resources are available. + +! Doctor found issues in 1 category. +``` diff --git a/lib/app_router.dart b/lib/app_router.dart index 02c517f7..9c23dd00 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -1,37 +1,23 @@ import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.dart'; import 'package:eatvio_app/core/token_storage.dart'; +import 'package:eatvio_app/features/blog_post/presentation/pages/blog_post_screen.dart'; +import 'package:eatvio_app/features/blog_post_create/presentation/pages/blog_post_create_screen.dart'; +import 'package:eatvio_app/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart'; import 'package:eatvio_app/features/chat/presentation/pages/chat_screen.dart'; import 'package:eatvio_app/features/chat/presentation/pages/chat_select_screen/chat_select_screen.dart'; +import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; +import 'package:eatvio_app/features/feed/presentation/pages/feed_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/registration_screen.dart'; import 'package:eatvio_app/presentation/auth/auth_screen/auth_screen.dart'; import 'package:eatvio_app/presentation/diary/diary_edit_screen/diary_edit_screen.dart'; import 'package:eatvio_app/presentation/diets/diet_create_screen/diet_create_screen.dart'; import 'package:eatvio_app/presentation/diets/diet_select_screen/diet_select_screen.dart'; -import 'package:eatvio_app/features/blog_post_create/presentation/pages/blog_post_create_screen.dart'; import 'package:eatvio_app/presentation/feed/blog_post_edit_screen/blog_post_edit_screen.dart'; -import 'package:eatvio_app/features/blog_post/presentation/pages/blog_post_screen.dart'; -import 'package:eatvio_app/features/feed/presentation/pages/feed_screen.dart'; import 'package:eatvio_app/presentation/glossary/glossary_screen/glossary_screen.dart'; import 'package:eatvio_app/presentation/plans/plan_select_screen/plan_select_screen.dart'; import 'package:eatvio_app/presentation/profile/my_profile_screen/my_profile_screen.dart'; import 'package:eatvio_app/presentation/profile/my_profile_screen/my_settings_screen.dart'; import 'package:eatvio_app/presentation/recipe/recipe_select_screen/recipe_select_screen.dart'; -import 'package:eatvio_app/presentation/registration/additional_information_screen/additional_information_screen.dart'; -import 'package:eatvio_app/presentation/registration/allergies_screen/allergies_screen.dart'; -import 'package:eatvio_app/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart'; -import 'package:eatvio_app/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart'; -import 'package:eatvio_app/presentation/registration/city_of_living_screen/city_of_living_screen.dart'; -import 'package:eatvio_app/presentation/registration/credentials_screen/credentials_screen.dart'; -import 'package:eatvio_app/presentation/registration/date_of_birth_screen/date_of_birth_screen.dart'; -import 'package:eatvio_app/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart'; -import 'package:eatvio_app/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart'; -import 'package:eatvio_app/presentation/registration/gender_screen/gender_screen.dart'; -import 'package:eatvio_app/presentation/registration/height_screen/height_screen.dart'; -import 'package:eatvio_app/presentation/registration/language_select_screen/language_select_screen.dart'; -import 'package:eatvio_app/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart'; -import 'package:eatvio_app/presentation/registration/name_screen/name_screen.dart'; -import 'package:eatvio_app/presentation/registration/weight_screen/weight_screen.dart'; -import 'package:eatvio_app/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart'; -import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; @@ -48,7 +34,6 @@ class AppRouter { name: 'authScreen', redirect: (context, state) async { if (await TokenStorage.haveTokenInStorage()) { - await context.read().runInitialization(); return '/my-profile-screen'; } return null; @@ -56,105 +41,9 @@ class AppRouter { builder: (context, state) => AuthScreen.builder(context), routes: [ GoRoute( - path: 'language-select-screen', - name: 'languageSelectScreen', - builder: (context, state) => LanguageSelectScreen.builder(context), - routes: [ - GoRoute( - path: 'credentials-screen', - name: 'credentialsScreen', - builder: (context, state) => CredentialsScreen.builder(context, state.extra), - routes: [ - GoRoute( - path: 'name-screen', - name: 'nameScreen', - builder: (context, state) => NameScreen.builder(context, state.extra), - routes: [ - GoRoute( - path: 'gender-screen', - name: 'genderScreen', - builder: (context, state) => GenderScreen.builder(context, state.extra), - routes: [ - GoRoute( - path: 'date-of-birth-screen', - name: 'dateOfBirthScreen', - builder: (context, state) => DateOfBirthScreen.builder(context, state.extra), - routes: [ - GoRoute( - path: 'city-of-living-screen', - name: 'cityOfLivingScreen', - builder: (context, state) => CityOfLivingScreen.builder(context, state.extra), - routes: [ - GoRoute( - path: 'body-circumferences-screen', - name: 'bodyCircumferencesScreen', - builder: (context, state) => BodyCircumferencesScreen.builder(context, state.extra), - routes: [ - GoRoute( - path: 'weight-screen', - name: 'weightScreen', - builder: (context, state) => WeightScreen.builder(context, state.extra), - routes: [ - GoRoute( - path: 'height-screen', - name: 'heightScreen', - builder: (context, state) => HeightScreen.builder(context, state.extra), - routes: [ - GoRoute( - path: 'blood-pressure-screen', - name: 'bloodPressureScreen', - builder: (context, state) => BloodPressureScreen.builder(context, state.extra), - routes: [ - GoRoute( - path: 'favorite-sports-screen', - name: 'favoriteSportsScreen', - builder: (context, state) => FavoriteSportsScreen.builder(context, state.extra), - routes: [ - GoRoute( - name: 'allergiesScreen', - path: 'allergiesScreen', - builder: (context, state) => AllergiesScreen.builder(context, state.extra), - routes: [ - GoRoute( - name: 'medicineIntakeScreen', - path: 'medicine-intake-screen', - builder: (context, state) => MedicineIntakeScreen.builder(context, state.extra), - ), - GoRoute( - name: 'favoriteFoodsScreen', - path: 'favorite-foods-screen', - builder: (context, state) => FavoriteFoodsScreen.builder(context, state.extra), - routes: [ - GoRoute( - path: 'additional-information-screen', - name: 'additionalInformationScreen', - builder: (context, state) => AdditionalInformationScreen.builder(context, state.extra), - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], + path: 'registration-screen', + name: 'registrationScreen', + builder: (context, state) => const RegistrationScreen(), ), ], ), @@ -166,6 +55,10 @@ class AppRouter { GoRoute( path: '/my-profile-screen', name: 'myProfileScreen', + redirect: (context, state) async { + await context.read().runInitialization(); + return null; + }, builder: (context, state) => MyProfileScreen(), ), GoRoute( diff --git a/lib/core/app_export.dart b/lib/core/app_export.dart index ae95a220..76a79551 100644 --- a/lib/core/app_export.dart +++ b/lib/core/app_export.dart @@ -1,6 +1,6 @@ -export 'package:flutter_bloc/flutter_bloc.dart'; export 'package:eatvio_app/core/constants/constants.dart'; export 'package:eatvio_app/core/errors/exceptions.dart'; +export 'package:eatvio_app/core/utils/date_time_utils.dart'; export 'package:eatvio_app/core/utils/image_constant.dart'; export 'package:eatvio_app/core/utils/logger.dart'; export 'package:eatvio_app/core/utils/pref_utils.dart'; @@ -11,6 +11,7 @@ export 'package:eatvio_app/theme/app_decoration.dart'; export 'package:eatvio_app/theme/custom_text_style.dart'; export 'package:eatvio_app/theme/theme_helper.dart'; export 'package:eatvio_app/widgets/custom_image_view.dart'; +export 'package:flutter_bloc/flutter_bloc.dart'; + export '../theme/bloc/theme_bloc.dart'; export '../theme/custom_button_style.dart'; -export 'package:eatvio_app/core/utils/date_time_utils.dart'; diff --git a/lib/core/constants/constants.dart b/lib/core/constants/constants.dart index 8b137891..c0353c48 100644 --- a/lib/core/constants/constants.dart +++ b/lib/core/constants/constants.dart @@ -1 +1 @@ - +const String baseUrl = 'https://mobile-stage.eatvio.ru'; diff --git a/lib/core/errors/exceptions.dart b/lib/core/errors/exceptions.dart index d7d4de89..7cbb3f19 100644 --- a/lib/core/errors/exceptions.dart +++ b/lib/core/errors/exceptions.dart @@ -1,5 +1,5 @@ -import 'package:flutter/material.dart'; import 'package:eatvio_app/main.dart'; +import 'package:flutter/material.dart'; class ServerException implements Exception {} @@ -13,8 +13,7 @@ class NoInternetException implements Exception { NoInternetException([String message = 'NoInternetException Occurred']) { if (globalMessengerKey.currentState != null) { - globalMessengerKey.currentState! - .showSnackBar(SnackBar(content: Text(message))); + globalMessengerKey.currentState!.showSnackBar(SnackBar(content: Text(message))); } this._message = message; } diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index a7034e21..2052a25a 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -9,6 +9,7 @@ import 'package:eatvio_app/locator_service.dart'; class InitializationCubit extends Cubit { final ChatRepository chatRepository; + bool wasInitializated = false; InitializationCubit({required this.chatRepository}) : super(const InitializationState.loading()); @@ -49,48 +50,51 @@ class InitializationCubit extends Cubit { } Future runInitialization() async { - try { - await TokenStorage.haveTokenInStorage(); - final wsUrl = await chatRepository.getWebsocket(); - final options = PusherChannelsOptions.fromHost( - scheme: 'wss', - key: wsUrl.key, - host: wsUrl.host, - shouldSupplyMetadataQueries: true, - metadata: PusherChannelsOptionsMetadata.byDefault(), - port: 443, - ); - final client = PusherChannelsClient.websocket( - options: options, - connectionErrorHandler: (exception, trace, refresh) { - refresh(); - }, - minimumReconnectDelayDuration: const Duration( - seconds: 1, - ), - defaultActivityDuration: const Duration( - seconds: 120, - ), - activityDurationOverride: const Duration( - seconds: 120, - ), - waitForPongDuration: const Duration( - seconds: 30, - ), - ); - await client.connect(); + if (!wasInitializated) { + wasInitializated = true; + try { + await TokenStorage.haveTokenInStorage(); + final wsUrl = await chatRepository.getWebsocket(); + final options = PusherChannelsOptions.fromHost( + scheme: 'wss', + key: wsUrl.key, + host: wsUrl.host, + shouldSupplyMetadataQueries: true, + metadata: PusherChannelsOptionsMetadata.byDefault(), + port: 443, + ); + final client = PusherChannelsClient.websocket( + options: options, + connectionErrorHandler: (exception, trace, refresh) { + refresh(); + }, + minimumReconnectDelayDuration: const Duration( + seconds: 1, + ), + defaultActivityDuration: const Duration( + seconds: 120, + ), + activityDurationOverride: const Duration( + seconds: 120, + ), + waitForPongDuration: const Duration( + seconds: 30, + ), + ); + await client.connect(); - await subscribeNotifications(wsUrl.userId, client); - await subscribeChatMessages(wsUrl.userId, client); + await subscribeNotifications(wsUrl.userId, client); + await subscribeChatMessages(wsUrl.userId, client); - emit(InitializationState.success( - client: client, - )); - } catch (e) { - emit(InitializationState.error( - errorMessage: e.toString(), - )); - rethrow; + emit(InitializationState.success( + client: client, + )); + } catch (e) { + emit(InitializationState.error( + errorMessage: e.toString(), + )); + rethrow; + } } } } diff --git a/lib/core/utils/image_constant.dart b/lib/core/utils/image_constant.dart index 07aa9abb..6a7785af 100644 --- a/lib/core/utils/image_constant.dart +++ b/lib/core/utils/image_constant.dart @@ -24,15 +24,13 @@ class ImageConstant { // Блог images static String imgRectangle14 = '$imagePath/img_rectangle_14.png'; - static String imgRectangle14220x341 = - '$imagePath/img_rectangle_14_220x341.png'; + static String imgRectangle14220x341 = '$imagePath/img_rectangle_14_220x341.png'; // Блог - Tab Container images static String imgCrop = '$imagePath/img_crop.svg'; // Статья images - static String imgRectangle14220x375 = - '$imagePath/img_rectangle_14_220x375.png'; + static String imgRectangle14220x375 = '$imagePath/img_rectangle_14_220x375.png'; static String imgVector = '$imagePath/img_vector.svg'; @@ -116,13 +114,11 @@ class ImageConstant { static String imgNavBlueGray400 = '$imagePath/img_nav_blue_gray_400.svg'; - static String imgNavBlueGray40024x23 = - '$imagePath/img_nav_blue_gray_400_24x23.svg'; + static String imgNavBlueGray40024x23 = '$imagePath/img_nav_blue_gray_400_24x23.svg'; static String imgNavPrimary = '$imagePath/img_nav_primary.svg'; - static String imgNavBlueGray40024x25 = - '$imagePath/img_nav_blue_gray_400_24x25.svg'; + static String imgNavBlueGray40024x25 = '$imagePath/img_nav_blue_gray_400_24x25.svg'; static String imgEye = '$imagePath/img_eye.svg'; @@ -134,11 +130,9 @@ class ImageConstant { static String imgEllipse142x42 = '$imagePath/img_ellipse_1_42x42.png'; - static String imgIconMoreHorizontal = - '$imagePath/img_icon_more_horizontal.svg'; + static String imgIconMoreHorizontal = '$imagePath/img_icon_more_horizontal.svg'; - static String imgRectangle14250x311 = - '$imagePath/img_rectangle_14_250x311.png'; + static String imgRectangle14250x311 = '$imagePath/img_rectangle_14_250x311.png'; static String imgIconMessageSquare = '$imagePath/img_icon_message_square.svg'; diff --git a/lib/core/utils/progress_dialog_utils.dart b/lib/core/utils/progress_dialog_utils.dart index 98cdac07..ced3347c 100644 --- a/lib/core/utils/progress_dialog_utils.dart +++ b/lib/core/utils/progress_dialog_utils.dart @@ -8,18 +8,19 @@ class ProgressDialogUtils { static void showProgressDialog({BuildContext? context, isCancellable = false}) async { if (!isProgressVisible && AppRouter.navigatorKey.currentState?.overlay?.context != null) { showDialog( - barrierDismissible: isCancellable, - context: AppRouter.navigatorKey.currentState!.overlay!.context, - builder: (BuildContext context) { - return Center( - child: CircularProgressIndicator.adaptive( - strokeWidth: 4, - valueColor: AlwaysStoppedAnimation( - Colors.white, - ), + barrierDismissible: isCancellable, + context: AppRouter.navigatorKey.currentState!.overlay!.context, + builder: (BuildContext context) { + return Center( + child: CircularProgressIndicator.adaptive( + strokeWidth: 4, + valueColor: AlwaysStoppedAnimation( + Colors.white, ), - ); - },); + ), + ); + }, + ); isProgressVisible = true; } } diff --git a/lib/core/utils/size_utils.dart b/lib/core/utils/size_utils.dart index 55953775..04f09c8a 100644 --- a/lib/core/utils/size_utils.dart +++ b/lib/core/utils/size_utils.dart @@ -3,7 +3,8 @@ import 'package:flutter/material.dart'; // This functions are responsible to make UI responsive across all the mobile devices. MediaQueryData mediaQueryData = MediaQueryData.fromView( - WidgetsBinding.instance.platformDispatcher.views.single,); + WidgetsBinding.instance.platformDispatcher.views.single, +); // These are the Viewport values of your Figma Design. // These are used in the code as a reference to create your UI Responsively. @@ -30,8 +31,7 @@ extension ResponsiveExtension on num { double get h => ((this * _width) / FIGMA_DESIGN_WIDTH); ///This method is used to set padding/margin (for the top and bottom side) & height of the screen or widget according to the Viewport height. - double get v => - (this * _height) / (FIGMA_DESIGN_HEIGHT - FIGMA_DESIGN_STATUS_BAR); + double get v => (this * _height) / (FIGMA_DESIGN_HEIGHT - FIGMA_DESIGN_STATUS_BAR); ///This method is used to set smallest px in image height and width double get adaptSize { diff --git a/lib/data/models/selectionPopupModel/selection_popup_model.dart b/lib/data/models/selectionPopupModel/selection_popup_model.dart index e9aa2c89..f304e8d1 100644 --- a/lib/data/models/selectionPopupModel/selection_popup_model.dart +++ b/lib/data/models/selectionPopupModel/selection_popup_model.dart @@ -1,15 +1,13 @@ -///SelectionPopupModel is common model -///used for setting data into dropdowns -class SelectionPopupModel { - int? id; - String title; - dynamic value; - bool isSelected; +import 'package:freezed_annotation/freezed_annotation.dart'; - SelectionPopupModel({ - this.id, - required this.title, - this.value, - this.isSelected = false, - }); +part 'selection_popup_model.freezed.dart'; + +@freezed +class SelectionPopupModel with _$SelectionPopupModel { + const factory SelectionPopupModel({ + int? id, + required String title, + dynamic value, + @Default(false) bool isSelected, + }) = _SelectionPopupModel; } diff --git a/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart b/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart new file mode 100644 index 00000000..917785c7 --- /dev/null +++ b/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart @@ -0,0 +1,189 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'selection_popup_model.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$SelectionPopupModel { + int? get id => throw _privateConstructorUsedError; + String get title => throw _privateConstructorUsedError; + dynamic get value => throw _privateConstructorUsedError; + bool get isSelected => throw _privateConstructorUsedError; + + @JsonKey(ignore: true) + $SelectionPopupModelCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $SelectionPopupModelCopyWith<$Res> { + factory $SelectionPopupModelCopyWith( + SelectionPopupModel value, $Res Function(SelectionPopupModel) then) = + _$SelectionPopupModelCopyWithImpl<$Res, SelectionPopupModel>; + @useResult + $Res call({int? id, String title, dynamic value, bool isSelected}); +} + +/// @nodoc +class _$SelectionPopupModelCopyWithImpl<$Res, $Val extends SelectionPopupModel> + implements $SelectionPopupModelCopyWith<$Res> { + _$SelectionPopupModelCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = freezed, + Object? title = null, + Object? value = freezed, + Object? isSelected = null, + }) { + return _then(_value.copyWith( + id: freezed == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int?, + title: null == title + ? _value.title + : title // ignore: cast_nullable_to_non_nullable + as String, + value: freezed == value + ? _value.value + : value // ignore: cast_nullable_to_non_nullable + as dynamic, + isSelected: null == isSelected + ? _value.isSelected + : isSelected // ignore: cast_nullable_to_non_nullable + as bool, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$SelectionPopupModelImplCopyWith<$Res> + implements $SelectionPopupModelCopyWith<$Res> { + factory _$$SelectionPopupModelImplCopyWith(_$SelectionPopupModelImpl value, + $Res Function(_$SelectionPopupModelImpl) then) = + __$$SelectionPopupModelImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({int? id, String title, dynamic value, bool isSelected}); +} + +/// @nodoc +class __$$SelectionPopupModelImplCopyWithImpl<$Res> + extends _$SelectionPopupModelCopyWithImpl<$Res, _$SelectionPopupModelImpl> + implements _$$SelectionPopupModelImplCopyWith<$Res> { + __$$SelectionPopupModelImplCopyWithImpl(_$SelectionPopupModelImpl _value, + $Res Function(_$SelectionPopupModelImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = freezed, + Object? title = null, + Object? value = freezed, + Object? isSelected = null, + }) { + return _then(_$SelectionPopupModelImpl( + id: freezed == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int?, + title: null == title + ? _value.title + : title // ignore: cast_nullable_to_non_nullable + as String, + value: freezed == value + ? _value.value + : value // ignore: cast_nullable_to_non_nullable + as dynamic, + isSelected: null == isSelected + ? _value.isSelected + : isSelected // ignore: cast_nullable_to_non_nullable + as bool, + )); + } +} + +/// @nodoc + +class _$SelectionPopupModelImpl implements _SelectionPopupModel { + const _$SelectionPopupModelImpl( + {this.id, required this.title, this.value, this.isSelected = false}); + + @override + final int? id; + @override + final String title; + @override + final dynamic value; + @override + @JsonKey() + final bool isSelected; + + @override + String toString() { + return 'SelectionPopupModel(id: $id, title: $title, value: $value, isSelected: $isSelected)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SelectionPopupModelImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.title, title) || other.title == title) && + const DeepCollectionEquality().equals(other.value, value) && + (identical(other.isSelected, isSelected) || + other.isSelected == isSelected)); + } + + @override + int get hashCode => Object.hash(runtimeType, id, title, + const DeepCollectionEquality().hash(value), isSelected); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$SelectionPopupModelImplCopyWith<_$SelectionPopupModelImpl> get copyWith => + __$$SelectionPopupModelImplCopyWithImpl<_$SelectionPopupModelImpl>( + this, _$identity); +} + +abstract class _SelectionPopupModel implements SelectionPopupModel { + const factory _SelectionPopupModel( + {final int? id, + required final String title, + final dynamic value, + final bool isSelected}) = _$SelectionPopupModelImpl; + + @override + int? get id; + @override + String get title; + @override + dynamic get value; + @override + bool get isSelected; + @override + @JsonKey(ignore: true) + _$$SelectionPopupModelImplCopyWith<_$SelectionPopupModelImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/data/models/tokenModel/token_model.dart b/lib/data/models/tokenModel/token_model.dart index 3aa1d3f6..ce310e2e 100644 --- a/lib/data/models/tokenModel/token_model.dart +++ b/lib/data/models/tokenModel/token_model.dart @@ -1,4 +1,5 @@ import 'package:hive/hive.dart'; + /// https://pub.dev/packages/flutter_secure_storage TODO replace hive to secure_storage for token storage @HiveType(typeId: 0) class TokenModel { diff --git a/lib/data/models/userRegistrationModel/user_registration_model.dart b/lib/data/models/userRegistrationModel/user_registration_model.dart index baeb3a16..5e308189 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.dart @@ -1,92 +1,40 @@ -class UserRegistrationSheet { - String name; - String firstName; - String lastName; - String email; - String password; - String passwordConfirmation; - String termsAccepted; - String birthdate; - String gender; - String country; - String city; - String lang; - String weight; - String height; - String chestCircumference; - String waistCircumference; - String hipCircumference; - String bloodPressureUp; - String bloodPressureDown; - String hasHypo = ''; - String hasHyper = ''; - String aboutAllergy = ''; - String aboutTakingPils = ''; - String aboutSportHobbies = ''; - String favoriteFoods = ''; - String unfavoriteFoods = ''; - String additionalInfo = ''; +import 'package:freezed_annotation/freezed_annotation.dart'; - UserRegistrationSheet({ - required this.name, - required this.firstName, - required this.lastName, - required this.email, - required this.password, - required this.passwordConfirmation, - required this.termsAccepted, - required this.birthdate, - required this.gender, - required this.country, - required this.city, - required this.lang, - required this.weight, - required this.height, - required this.chestCircumference, - required this.waistCircumference, - required this.hipCircumference, - required this.bloodPressureUp, - required this.bloodPressureDown, - required this.hasHypo, - required this.hasHyper, - required this.aboutAllergy, - required this.aboutTakingPils, - required this.aboutSportHobbies, - required this.favoriteFoods, - required this.unfavoriteFoods, - required this.additionalInfo, - }); +part 'user_registration_model.freezed.dart'; +part 'user_registration_model.g.dart'; - Map toJson() { - return { - 'name': name, - 'first_name': firstName, - 'last_name': lastName, - 'email': email, - 'password': password, - 'password_confirmation': passwordConfirmation, - 'terms': termsAccepted, - 'birthdate': birthdate.toString(), - 'gender': gender, - 'country': country, - 'city': city, - 'lang': lang, - 'weight': weight, - 'height': height, - 'chest_circumference': chestCircumference, - 'waist_circumference': waistCircumference, - 'hip_circumference': hipCircumference, - 'blood_pressure_up': bloodPressureUp, - 'blood_pressure_down': bloodPressureDown, - 'has_hypo': hasHypo, - 'has_hyper': hasHyper, - 'about_alergy': aboutAllergy, - 'about_taking_pils': aboutTakingPils, - 'about_sport_hobbies': aboutSportHobbies, - 'favorite_foods': favoriteFoods, - 'unfavorite_foods': unfavoriteFoods, - 'additional_info': additionalInfo, - 'activity_coefficient': '1.2', - }; - } +@freezed +class UserRegistrationSheet with _$UserRegistrationSheet { + const factory UserRegistrationSheet({ + required String name, + @JsonKey(name: 'first_name') required String firstName, + @JsonKey(name: 'last_name') required String lastName, + required String email, + required String password, + @JsonKey(name: 'password_confirmation') required String passwordConfirmation, + @Default('accepted') @JsonKey(name: 'terms') String termsAccepted, + required String birthdate, + required String gender, + required String country, + required String city, + required String lang, + required int weight, + required int height, + @JsonKey(name: 'chest_circumference') required int chestCircumference, + @JsonKey(name: 'waist_circumference') required int waistCircumference, + @JsonKey(name: 'hip_circumference') required int hipCircumference, + @JsonKey(name: 'blood_pressure_up') required int bloodPressureUp, + @JsonKey(name: 'blood_pressure_down') required int bloodPressureDown, + @JsonKey(name: 'has_hypo') required int hasHypo, + @JsonKey(name: 'has_hyper') required int hasHyper, + @JsonKey(name: 'about_alergy') required String aboutAllergy, + @JsonKey(name: 'about_taking_pils') required String aboutTakingPils, + @JsonKey(name: 'about_sport_hobbies') required String aboutSportHobbies, + @JsonKey(name: 'favorite_foods') required String favoriteFoods, + @JsonKey(name: 'unfavorite_foods') required String unfavoriteFoods, + @JsonKey(name: 'additional_info') required String additionalInfo, + @Default(1.2) @JsonKey(name: 'activity_coefficient') double activityCoefficient, + }) = _UserRegistrationSheet; + + factory UserRegistrationSheet.fromJson(Map json) => _$UserRegistrationSheetFromJson(json); } diff --git a/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart b/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart new file mode 100644 index 00000000..4aa91df8 --- /dev/null +++ b/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart @@ -0,0 +1,810 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'user_registration_model.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +UserRegistrationSheet _$UserRegistrationSheetFromJson( + Map json) { + return _UserRegistrationSheet.fromJson(json); +} + +/// @nodoc +mixin _$UserRegistrationSheet { + String get name => throw _privateConstructorUsedError; + @JsonKey(name: 'first_name') + String get firstName => throw _privateConstructorUsedError; + @JsonKey(name: 'last_name') + String get lastName => throw _privateConstructorUsedError; + String get email => throw _privateConstructorUsedError; + String get password => throw _privateConstructorUsedError; + @JsonKey(name: 'password_confirmation') + String get passwordConfirmation => throw _privateConstructorUsedError; + @JsonKey(name: 'terms') + String get termsAccepted => throw _privateConstructorUsedError; + String get birthdate => throw _privateConstructorUsedError; + String get gender => throw _privateConstructorUsedError; + String get country => throw _privateConstructorUsedError; + String get city => throw _privateConstructorUsedError; + String get lang => throw _privateConstructorUsedError; + int get weight => throw _privateConstructorUsedError; + int get height => throw _privateConstructorUsedError; + @JsonKey(name: 'chest_circumference') + int get chestCircumference => throw _privateConstructorUsedError; + @JsonKey(name: 'waist_circumference') + int get waistCircumference => throw _privateConstructorUsedError; + @JsonKey(name: 'hip_circumference') + int get hipCircumference => throw _privateConstructorUsedError; + @JsonKey(name: 'blood_pressure_up') + int get bloodPressureUp => throw _privateConstructorUsedError; + @JsonKey(name: 'blood_pressure_down') + int get bloodPressureDown => throw _privateConstructorUsedError; + @JsonKey(name: 'has_hypo') + int get hasHypo => throw _privateConstructorUsedError; + @JsonKey(name: 'has_hyper') + int get hasHyper => throw _privateConstructorUsedError; + @JsonKey(name: 'about_alergy') + String get aboutAllergy => throw _privateConstructorUsedError; + @JsonKey(name: 'about_taking_pils') + String get aboutTakingPils => throw _privateConstructorUsedError; + @JsonKey(name: 'about_sport_hobbies') + String get aboutSportHobbies => throw _privateConstructorUsedError; + @JsonKey(name: 'favorite_foods') + String get favoriteFoods => throw _privateConstructorUsedError; + @JsonKey(name: 'unfavorite_foods') + String get unfavoriteFoods => throw _privateConstructorUsedError; + @JsonKey(name: 'additional_info') + String get additionalInfo => throw _privateConstructorUsedError; + @JsonKey(name: 'activity_coefficient') + double get activityCoefficient => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $UserRegistrationSheetCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $UserRegistrationSheetCopyWith<$Res> { + factory $UserRegistrationSheetCopyWith(UserRegistrationSheet value, + $Res Function(UserRegistrationSheet) then) = + _$UserRegistrationSheetCopyWithImpl<$Res, UserRegistrationSheet>; + @useResult + $Res call( + {String name, + @JsonKey(name: 'first_name') String firstName, + @JsonKey(name: 'last_name') String lastName, + String email, + String password, + @JsonKey(name: 'password_confirmation') String passwordConfirmation, + @JsonKey(name: 'terms') String termsAccepted, + String birthdate, + String gender, + String country, + String city, + String lang, + int weight, + int height, + @JsonKey(name: 'chest_circumference') int chestCircumference, + @JsonKey(name: 'waist_circumference') int waistCircumference, + @JsonKey(name: 'hip_circumference') int hipCircumference, + @JsonKey(name: 'blood_pressure_up') int bloodPressureUp, + @JsonKey(name: 'blood_pressure_down') int bloodPressureDown, + @JsonKey(name: 'has_hypo') int hasHypo, + @JsonKey(name: 'has_hyper') int hasHyper, + @JsonKey(name: 'about_alergy') String aboutAllergy, + @JsonKey(name: 'about_taking_pils') String aboutTakingPils, + @JsonKey(name: 'about_sport_hobbies') String aboutSportHobbies, + @JsonKey(name: 'favorite_foods') String favoriteFoods, + @JsonKey(name: 'unfavorite_foods') String unfavoriteFoods, + @JsonKey(name: 'additional_info') String additionalInfo, + @JsonKey(name: 'activity_coefficient') double activityCoefficient}); +} + +/// @nodoc +class _$UserRegistrationSheetCopyWithImpl<$Res, + $Val extends UserRegistrationSheet> + implements $UserRegistrationSheetCopyWith<$Res> { + _$UserRegistrationSheetCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? name = null, + Object? firstName = null, + Object? lastName = null, + Object? email = null, + Object? password = null, + Object? passwordConfirmation = null, + Object? termsAccepted = null, + Object? birthdate = null, + Object? gender = null, + Object? country = null, + Object? city = null, + Object? lang = null, + Object? weight = null, + Object? height = null, + Object? chestCircumference = null, + Object? waistCircumference = null, + Object? hipCircumference = null, + Object? bloodPressureUp = null, + Object? bloodPressureDown = null, + Object? hasHypo = null, + Object? hasHyper = null, + Object? aboutAllergy = null, + Object? aboutTakingPils = null, + Object? aboutSportHobbies = null, + Object? favoriteFoods = null, + Object? unfavoriteFoods = null, + Object? additionalInfo = null, + Object? activityCoefficient = null, + }) { + return _then(_value.copyWith( + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + firstName: null == firstName + ? _value.firstName + : firstName // ignore: cast_nullable_to_non_nullable + as String, + lastName: null == lastName + ? _value.lastName + : lastName // ignore: cast_nullable_to_non_nullable + as String, + email: null == email + ? _value.email + : email // ignore: cast_nullable_to_non_nullable + as String, + password: null == password + ? _value.password + : password // ignore: cast_nullable_to_non_nullable + as String, + passwordConfirmation: null == passwordConfirmation + ? _value.passwordConfirmation + : passwordConfirmation // ignore: cast_nullable_to_non_nullable + as String, + termsAccepted: null == termsAccepted + ? _value.termsAccepted + : termsAccepted // ignore: cast_nullable_to_non_nullable + as String, + birthdate: null == birthdate + ? _value.birthdate + : birthdate // ignore: cast_nullable_to_non_nullable + as String, + gender: null == gender + ? _value.gender + : gender // ignore: cast_nullable_to_non_nullable + as String, + country: null == country + ? _value.country + : country // ignore: cast_nullable_to_non_nullable + as String, + city: null == city + ? _value.city + : city // ignore: cast_nullable_to_non_nullable + as String, + lang: null == lang + ? _value.lang + : lang // ignore: cast_nullable_to_non_nullable + as String, + weight: null == weight + ? _value.weight + : weight // ignore: cast_nullable_to_non_nullable + as int, + height: null == height + ? _value.height + : height // ignore: cast_nullable_to_non_nullable + as int, + chestCircumference: null == chestCircumference + ? _value.chestCircumference + : chestCircumference // ignore: cast_nullable_to_non_nullable + as int, + waistCircumference: null == waistCircumference + ? _value.waistCircumference + : waistCircumference // ignore: cast_nullable_to_non_nullable + as int, + hipCircumference: null == hipCircumference + ? _value.hipCircumference + : hipCircumference // ignore: cast_nullable_to_non_nullable + as int, + bloodPressureUp: null == bloodPressureUp + ? _value.bloodPressureUp + : bloodPressureUp // ignore: cast_nullable_to_non_nullable + as int, + bloodPressureDown: null == bloodPressureDown + ? _value.bloodPressureDown + : bloodPressureDown // ignore: cast_nullable_to_non_nullable + as int, + hasHypo: null == hasHypo + ? _value.hasHypo + : hasHypo // ignore: cast_nullable_to_non_nullable + as int, + hasHyper: null == hasHyper + ? _value.hasHyper + : hasHyper // ignore: cast_nullable_to_non_nullable + as int, + aboutAllergy: null == aboutAllergy + ? _value.aboutAllergy + : aboutAllergy // ignore: cast_nullable_to_non_nullable + as String, + aboutTakingPils: null == aboutTakingPils + ? _value.aboutTakingPils + : aboutTakingPils // ignore: cast_nullable_to_non_nullable + as String, + aboutSportHobbies: null == aboutSportHobbies + ? _value.aboutSportHobbies + : aboutSportHobbies // ignore: cast_nullable_to_non_nullable + as String, + favoriteFoods: null == favoriteFoods + ? _value.favoriteFoods + : favoriteFoods // ignore: cast_nullable_to_non_nullable + as String, + unfavoriteFoods: null == unfavoriteFoods + ? _value.unfavoriteFoods + : unfavoriteFoods // ignore: cast_nullable_to_non_nullable + as String, + additionalInfo: null == additionalInfo + ? _value.additionalInfo + : additionalInfo // ignore: cast_nullable_to_non_nullable + as String, + activityCoefficient: null == activityCoefficient + ? _value.activityCoefficient + : activityCoefficient // ignore: cast_nullable_to_non_nullable + as double, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$UserRegistrationSheetImplCopyWith<$Res> + implements $UserRegistrationSheetCopyWith<$Res> { + factory _$$UserRegistrationSheetImplCopyWith( + _$UserRegistrationSheetImpl value, + $Res Function(_$UserRegistrationSheetImpl) then) = + __$$UserRegistrationSheetImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {String name, + @JsonKey(name: 'first_name') String firstName, + @JsonKey(name: 'last_name') String lastName, + String email, + String password, + @JsonKey(name: 'password_confirmation') String passwordConfirmation, + @JsonKey(name: 'terms') String termsAccepted, + String birthdate, + String gender, + String country, + String city, + String lang, + int weight, + int height, + @JsonKey(name: 'chest_circumference') int chestCircumference, + @JsonKey(name: 'waist_circumference') int waistCircumference, + @JsonKey(name: 'hip_circumference') int hipCircumference, + @JsonKey(name: 'blood_pressure_up') int bloodPressureUp, + @JsonKey(name: 'blood_pressure_down') int bloodPressureDown, + @JsonKey(name: 'has_hypo') int hasHypo, + @JsonKey(name: 'has_hyper') int hasHyper, + @JsonKey(name: 'about_alergy') String aboutAllergy, + @JsonKey(name: 'about_taking_pils') String aboutTakingPils, + @JsonKey(name: 'about_sport_hobbies') String aboutSportHobbies, + @JsonKey(name: 'favorite_foods') String favoriteFoods, + @JsonKey(name: 'unfavorite_foods') String unfavoriteFoods, + @JsonKey(name: 'additional_info') String additionalInfo, + @JsonKey(name: 'activity_coefficient') double activityCoefficient}); +} + +/// @nodoc +class __$$UserRegistrationSheetImplCopyWithImpl<$Res> + extends _$UserRegistrationSheetCopyWithImpl<$Res, + _$UserRegistrationSheetImpl> + implements _$$UserRegistrationSheetImplCopyWith<$Res> { + __$$UserRegistrationSheetImplCopyWithImpl(_$UserRegistrationSheetImpl _value, + $Res Function(_$UserRegistrationSheetImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? name = null, + Object? firstName = null, + Object? lastName = null, + Object? email = null, + Object? password = null, + Object? passwordConfirmation = null, + Object? termsAccepted = null, + Object? birthdate = null, + Object? gender = null, + Object? country = null, + Object? city = null, + Object? lang = null, + Object? weight = null, + Object? height = null, + Object? chestCircumference = null, + Object? waistCircumference = null, + Object? hipCircumference = null, + Object? bloodPressureUp = null, + Object? bloodPressureDown = null, + Object? hasHypo = null, + Object? hasHyper = null, + Object? aboutAllergy = null, + Object? aboutTakingPils = null, + Object? aboutSportHobbies = null, + Object? favoriteFoods = null, + Object? unfavoriteFoods = null, + Object? additionalInfo = null, + Object? activityCoefficient = null, + }) { + return _then(_$UserRegistrationSheetImpl( + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + firstName: null == firstName + ? _value.firstName + : firstName // ignore: cast_nullable_to_non_nullable + as String, + lastName: null == lastName + ? _value.lastName + : lastName // ignore: cast_nullable_to_non_nullable + as String, + email: null == email + ? _value.email + : email // ignore: cast_nullable_to_non_nullable + as String, + password: null == password + ? _value.password + : password // ignore: cast_nullable_to_non_nullable + as String, + passwordConfirmation: null == passwordConfirmation + ? _value.passwordConfirmation + : passwordConfirmation // ignore: cast_nullable_to_non_nullable + as String, + termsAccepted: null == termsAccepted + ? _value.termsAccepted + : termsAccepted // ignore: cast_nullable_to_non_nullable + as String, + birthdate: null == birthdate + ? _value.birthdate + : birthdate // ignore: cast_nullable_to_non_nullable + as String, + gender: null == gender + ? _value.gender + : gender // ignore: cast_nullable_to_non_nullable + as String, + country: null == country + ? _value.country + : country // ignore: cast_nullable_to_non_nullable + as String, + city: null == city + ? _value.city + : city // ignore: cast_nullable_to_non_nullable + as String, + lang: null == lang + ? _value.lang + : lang // ignore: cast_nullable_to_non_nullable + as String, + weight: null == weight + ? _value.weight + : weight // ignore: cast_nullable_to_non_nullable + as int, + height: null == height + ? _value.height + : height // ignore: cast_nullable_to_non_nullable + as int, + chestCircumference: null == chestCircumference + ? _value.chestCircumference + : chestCircumference // ignore: cast_nullable_to_non_nullable + as int, + waistCircumference: null == waistCircumference + ? _value.waistCircumference + : waistCircumference // ignore: cast_nullable_to_non_nullable + as int, + hipCircumference: null == hipCircumference + ? _value.hipCircumference + : hipCircumference // ignore: cast_nullable_to_non_nullable + as int, + bloodPressureUp: null == bloodPressureUp + ? _value.bloodPressureUp + : bloodPressureUp // ignore: cast_nullable_to_non_nullable + as int, + bloodPressureDown: null == bloodPressureDown + ? _value.bloodPressureDown + : bloodPressureDown // ignore: cast_nullable_to_non_nullable + as int, + hasHypo: null == hasHypo + ? _value.hasHypo + : hasHypo // ignore: cast_nullable_to_non_nullable + as int, + hasHyper: null == hasHyper + ? _value.hasHyper + : hasHyper // ignore: cast_nullable_to_non_nullable + as int, + aboutAllergy: null == aboutAllergy + ? _value.aboutAllergy + : aboutAllergy // ignore: cast_nullable_to_non_nullable + as String, + aboutTakingPils: null == aboutTakingPils + ? _value.aboutTakingPils + : aboutTakingPils // ignore: cast_nullable_to_non_nullable + as String, + aboutSportHobbies: null == aboutSportHobbies + ? _value.aboutSportHobbies + : aboutSportHobbies // ignore: cast_nullable_to_non_nullable + as String, + favoriteFoods: null == favoriteFoods + ? _value.favoriteFoods + : favoriteFoods // ignore: cast_nullable_to_non_nullable + as String, + unfavoriteFoods: null == unfavoriteFoods + ? _value.unfavoriteFoods + : unfavoriteFoods // ignore: cast_nullable_to_non_nullable + as String, + additionalInfo: null == additionalInfo + ? _value.additionalInfo + : additionalInfo // ignore: cast_nullable_to_non_nullable + as String, + activityCoefficient: null == activityCoefficient + ? _value.activityCoefficient + : activityCoefficient // ignore: cast_nullable_to_non_nullable + as double, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { + const _$UserRegistrationSheetImpl( + {required this.name, + @JsonKey(name: 'first_name') required this.firstName, + @JsonKey(name: 'last_name') required this.lastName, + required this.email, + required this.password, + @JsonKey(name: 'password_confirmation') + required this.passwordConfirmation, + @JsonKey(name: 'terms') this.termsAccepted = 'accepted', + required this.birthdate, + required this.gender, + required this.country, + required this.city, + required this.lang, + required this.weight, + required this.height, + @JsonKey(name: 'chest_circumference') required this.chestCircumference, + @JsonKey(name: 'waist_circumference') required this.waistCircumference, + @JsonKey(name: 'hip_circumference') required this.hipCircumference, + @JsonKey(name: 'blood_pressure_up') required this.bloodPressureUp, + @JsonKey(name: 'blood_pressure_down') required this.bloodPressureDown, + @JsonKey(name: 'has_hypo') required this.hasHypo, + @JsonKey(name: 'has_hyper') required this.hasHyper, + @JsonKey(name: 'about_alergy') required this.aboutAllergy, + @JsonKey(name: 'about_taking_pils') required this.aboutTakingPils, + @JsonKey(name: 'about_sport_hobbies') required this.aboutSportHobbies, + @JsonKey(name: 'favorite_foods') required this.favoriteFoods, + @JsonKey(name: 'unfavorite_foods') required this.unfavoriteFoods, + @JsonKey(name: 'additional_info') required this.additionalInfo, + @JsonKey(name: 'activity_coefficient') this.activityCoefficient = 1.2}); + + factory _$UserRegistrationSheetImpl.fromJson(Map json) => + _$$UserRegistrationSheetImplFromJson(json); + + @override + final String name; + @override + @JsonKey(name: 'first_name') + final String firstName; + @override + @JsonKey(name: 'last_name') + final String lastName; + @override + final String email; + @override + final String password; + @override + @JsonKey(name: 'password_confirmation') + final String passwordConfirmation; + @override + @JsonKey(name: 'terms') + final String termsAccepted; + @override + final String birthdate; + @override + final String gender; + @override + final String country; + @override + final String city; + @override + final String lang; + @override + final int weight; + @override + final int height; + @override + @JsonKey(name: 'chest_circumference') + final int chestCircumference; + @override + @JsonKey(name: 'waist_circumference') + final int waistCircumference; + @override + @JsonKey(name: 'hip_circumference') + final int hipCircumference; + @override + @JsonKey(name: 'blood_pressure_up') + final int bloodPressureUp; + @override + @JsonKey(name: 'blood_pressure_down') + final int bloodPressureDown; + @override + @JsonKey(name: 'has_hypo') + final int hasHypo; + @override + @JsonKey(name: 'has_hyper') + final int hasHyper; + @override + @JsonKey(name: 'about_alergy') + final String aboutAllergy; + @override + @JsonKey(name: 'about_taking_pils') + final String aboutTakingPils; + @override + @JsonKey(name: 'about_sport_hobbies') + final String aboutSportHobbies; + @override + @JsonKey(name: 'favorite_foods') + final String favoriteFoods; + @override + @JsonKey(name: 'unfavorite_foods') + final String unfavoriteFoods; + @override + @JsonKey(name: 'additional_info') + final String additionalInfo; + @override + @JsonKey(name: 'activity_coefficient') + final double activityCoefficient; + + @override + String toString() { + return 'UserRegistrationSheet(name: $name, firstName: $firstName, lastName: $lastName, email: $email, password: $password, passwordConfirmation: $passwordConfirmation, termsAccepted: $termsAccepted, birthdate: $birthdate, gender: $gender, country: $country, city: $city, lang: $lang, weight: $weight, height: $height, chestCircumference: $chestCircumference, waistCircumference: $waistCircumference, hipCircumference: $hipCircumference, bloodPressureUp: $bloodPressureUp, bloodPressureDown: $bloodPressureDown, hasHypo: $hasHypo, hasHyper: $hasHyper, aboutAllergy: $aboutAllergy, aboutTakingPils: $aboutTakingPils, aboutSportHobbies: $aboutSportHobbies, favoriteFoods: $favoriteFoods, unfavoriteFoods: $unfavoriteFoods, additionalInfo: $additionalInfo, activityCoefficient: $activityCoefficient)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$UserRegistrationSheetImpl && + (identical(other.name, name) || other.name == name) && + (identical(other.firstName, firstName) || + other.firstName == firstName) && + (identical(other.lastName, lastName) || + other.lastName == lastName) && + (identical(other.email, email) || other.email == email) && + (identical(other.password, password) || + other.password == password) && + (identical(other.passwordConfirmation, passwordConfirmation) || + other.passwordConfirmation == passwordConfirmation) && + (identical(other.termsAccepted, termsAccepted) || + other.termsAccepted == termsAccepted) && + (identical(other.birthdate, birthdate) || + other.birthdate == birthdate) && + (identical(other.gender, gender) || other.gender == gender) && + (identical(other.country, country) || other.country == country) && + (identical(other.city, city) || other.city == city) && + (identical(other.lang, lang) || other.lang == lang) && + (identical(other.weight, weight) || other.weight == weight) && + (identical(other.height, height) || other.height == height) && + (identical(other.chestCircumference, chestCircumference) || + other.chestCircumference == chestCircumference) && + (identical(other.waistCircumference, waistCircumference) || + other.waistCircumference == waistCircumference) && + (identical(other.hipCircumference, hipCircumference) || + other.hipCircumference == hipCircumference) && + (identical(other.bloodPressureUp, bloodPressureUp) || + other.bloodPressureUp == bloodPressureUp) && + (identical(other.bloodPressureDown, bloodPressureDown) || + other.bloodPressureDown == bloodPressureDown) && + (identical(other.hasHypo, hasHypo) || other.hasHypo == hasHypo) && + (identical(other.hasHyper, hasHyper) || + other.hasHyper == hasHyper) && + (identical(other.aboutAllergy, aboutAllergy) || + other.aboutAllergy == aboutAllergy) && + (identical(other.aboutTakingPils, aboutTakingPils) || + other.aboutTakingPils == aboutTakingPils) && + (identical(other.aboutSportHobbies, aboutSportHobbies) || + other.aboutSportHobbies == aboutSportHobbies) && + (identical(other.favoriteFoods, favoriteFoods) || + other.favoriteFoods == favoriteFoods) && + (identical(other.unfavoriteFoods, unfavoriteFoods) || + other.unfavoriteFoods == unfavoriteFoods) && + (identical(other.additionalInfo, additionalInfo) || + other.additionalInfo == additionalInfo) && + (identical(other.activityCoefficient, activityCoefficient) || + other.activityCoefficient == activityCoefficient)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hashAll([ + runtimeType, + name, + firstName, + lastName, + email, + password, + passwordConfirmation, + termsAccepted, + birthdate, + gender, + country, + city, + lang, + weight, + height, + chestCircumference, + waistCircumference, + hipCircumference, + bloodPressureUp, + bloodPressureDown, + hasHypo, + hasHyper, + aboutAllergy, + aboutTakingPils, + aboutSportHobbies, + favoriteFoods, + unfavoriteFoods, + additionalInfo, + activityCoefficient + ]); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$UserRegistrationSheetImplCopyWith<_$UserRegistrationSheetImpl> + get copyWith => __$$UserRegistrationSheetImplCopyWithImpl< + _$UserRegistrationSheetImpl>(this, _$identity); + + @override + Map toJson() { + return _$$UserRegistrationSheetImplToJson( + this, + ); + } +} + +abstract class _UserRegistrationSheet implements UserRegistrationSheet { + const factory _UserRegistrationSheet( + {required final String name, + @JsonKey(name: 'first_name') required final String firstName, + @JsonKey(name: 'last_name') required final String lastName, + required final String email, + required final String password, + @JsonKey(name: 'password_confirmation') + required final String passwordConfirmation, + @JsonKey(name: 'terms') final String termsAccepted, + required final String birthdate, + required final String gender, + required final String country, + required final String city, + required final String lang, + required final int weight, + required final int height, + @JsonKey(name: 'chest_circumference') + required final int chestCircumference, + @JsonKey(name: 'waist_circumference') + required final int waistCircumference, + @JsonKey(name: 'hip_circumference') required final int hipCircumference, + @JsonKey(name: 'blood_pressure_up') required final int bloodPressureUp, + @JsonKey(name: 'blood_pressure_down') + required final int bloodPressureDown, + @JsonKey(name: 'has_hypo') required final int hasHypo, + @JsonKey(name: 'has_hyper') required final int hasHyper, + @JsonKey(name: 'about_alergy') required final String aboutAllergy, + @JsonKey(name: 'about_taking_pils') required final String aboutTakingPils, + @JsonKey(name: 'about_sport_hobbies') + required final String aboutSportHobbies, + @JsonKey(name: 'favorite_foods') required final String favoriteFoods, + @JsonKey(name: 'unfavorite_foods') required final String unfavoriteFoods, + @JsonKey(name: 'additional_info') required final String additionalInfo, + @JsonKey(name: 'activity_coefficient') + final double activityCoefficient}) = _$UserRegistrationSheetImpl; + + factory _UserRegistrationSheet.fromJson(Map json) = + _$UserRegistrationSheetImpl.fromJson; + + @override + String get name; + @override + @JsonKey(name: 'first_name') + String get firstName; + @override + @JsonKey(name: 'last_name') + String get lastName; + @override + String get email; + @override + String get password; + @override + @JsonKey(name: 'password_confirmation') + String get passwordConfirmation; + @override + @JsonKey(name: 'terms') + String get termsAccepted; + @override + String get birthdate; + @override + String get gender; + @override + String get country; + @override + String get city; + @override + String get lang; + @override + int get weight; + @override + int get height; + @override + @JsonKey(name: 'chest_circumference') + int get chestCircumference; + @override + @JsonKey(name: 'waist_circumference') + int get waistCircumference; + @override + @JsonKey(name: 'hip_circumference') + int get hipCircumference; + @override + @JsonKey(name: 'blood_pressure_up') + int get bloodPressureUp; + @override + @JsonKey(name: 'blood_pressure_down') + int get bloodPressureDown; + @override + @JsonKey(name: 'has_hypo') + int get hasHypo; + @override + @JsonKey(name: 'has_hyper') + int get hasHyper; + @override + @JsonKey(name: 'about_alergy') + String get aboutAllergy; + @override + @JsonKey(name: 'about_taking_pils') + String get aboutTakingPils; + @override + @JsonKey(name: 'about_sport_hobbies') + String get aboutSportHobbies; + @override + @JsonKey(name: 'favorite_foods') + String get favoriteFoods; + @override + @JsonKey(name: 'unfavorite_foods') + String get unfavoriteFoods; + @override + @JsonKey(name: 'additional_info') + String get additionalInfo; + @override + @JsonKey(name: 'activity_coefficient') + double get activityCoefficient; + @override + @JsonKey(ignore: true) + _$$UserRegistrationSheetImplCopyWith<_$UserRegistrationSheetImpl> + get copyWith => throw _privateConstructorUsedError; +} diff --git a/lib/data/models/userRegistrationModel/user_registration_model.g.dart b/lib/data/models/userRegistrationModel/user_registration_model.g.dart new file mode 100644 index 00000000..132240b7 --- /dev/null +++ b/lib/data/models/userRegistrationModel/user_registration_model.g.dart @@ -0,0 +1,74 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'user_registration_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson( + Map json) => + _$UserRegistrationSheetImpl( + name: json['name'] as String, + firstName: json['first_name'] as String, + lastName: json['last_name'] as String, + email: json['email'] as String, + password: json['password'] as String, + passwordConfirmation: json['password_confirmation'] as String, + termsAccepted: json['terms'] as String? ?? 'accepted', + birthdate: json['birthdate'] as String, + gender: json['gender'] as String, + country: json['country'] as String, + city: json['city'] as String, + lang: json['lang'] as String, + weight: (json['weight'] as num).toInt(), + height: (json['height'] as num).toInt(), + chestCircumference: (json['chest_circumference'] as num).toInt(), + waistCircumference: (json['waist_circumference'] as num).toInt(), + hipCircumference: (json['hip_circumference'] as num).toInt(), + bloodPressureUp: (json['blood_pressure_up'] as num).toInt(), + bloodPressureDown: (json['blood_pressure_down'] as num).toInt(), + hasHypo: (json['has_hypo'] as num).toInt(), + hasHyper: (json['has_hyper'] as num).toInt(), + aboutAllergy: json['about_alergy'] as String, + aboutTakingPils: json['about_taking_pils'] as String, + aboutSportHobbies: json['about_sport_hobbies'] as String, + favoriteFoods: json['favorite_foods'] as String, + unfavoriteFoods: json['unfavorite_foods'] as String, + additionalInfo: json['additional_info'] as String, + activityCoefficient: + (json['activity_coefficient'] as num?)?.toDouble() ?? 1.2, + ); + +Map _$$UserRegistrationSheetImplToJson( + _$UserRegistrationSheetImpl instance) => + { + 'name': instance.name, + 'first_name': instance.firstName, + 'last_name': instance.lastName, + 'email': instance.email, + 'password': instance.password, + 'password_confirmation': instance.passwordConfirmation, + 'terms': instance.termsAccepted, + 'birthdate': instance.birthdate, + 'gender': instance.gender, + 'country': instance.country, + 'city': instance.city, + 'lang': instance.lang, + 'weight': instance.weight, + 'height': instance.height, + 'chest_circumference': instance.chestCircumference, + 'waist_circumference': instance.waistCircumference, + 'hip_circumference': instance.hipCircumference, + 'blood_pressure_up': instance.bloodPressureUp, + 'blood_pressure_down': instance.bloodPressureDown, + 'has_hypo': instance.hasHypo, + 'has_hyper': instance.hasHyper, + 'about_alergy': instance.aboutAllergy, + 'about_taking_pils': instance.aboutTakingPils, + 'about_sport_hobbies': instance.aboutSportHobbies, + 'favorite_foods': instance.favoriteFoods, + 'unfavorite_foods': instance.unfavoriteFoods, + 'additional_info': instance.additionalInfo, + 'activity_coefficient': instance.activityCoefficient, + }; diff --git a/lib/features/blog_post/models/blog_post_model.dart b/lib/features/blog_post/models/blog_post_model.dart index df39fe1e..1a428e0c 100644 --- a/lib/features/blog_post/models/blog_post_model.dart +++ b/lib/features/blog_post/models/blog_post_model.dart @@ -18,6 +18,5 @@ class BlogPostModel with _$BlogPostModel { required String title, }) = _BlogPostModel; - factory BlogPostModel.fromJson(Map json) => - _$BlogPostModelFromJson(json); + factory BlogPostModel.fromJson(Map json) => _$BlogPostModelFromJson(json); } diff --git a/lib/features/blog_post/presentation/bloc/blog_post_cubit.dart b/lib/features/blog_post/presentation/bloc/blog_post_cubit.dart index 90520c95..301e0efc 100644 --- a/lib/features/blog_post/presentation/bloc/blog_post_cubit.dart +++ b/lib/features/blog_post/presentation/bloc/blog_post_cubit.dart @@ -5,8 +5,7 @@ import 'package:eatvio_app/features/blog_post/repositories/blog_post_repository. class BlogPostCubit extends Cubit { final BlogPostRepository blogPostRepository; - BlogPostCubit({required this.blogPostRepository}) - : super(const BlogPostState.loading()); + BlogPostCubit({required this.blogPostRepository}) : super(const BlogPostState.loading()); loadBlogPost(String blogPostID) async { emit(const BlogPostState.loading()); diff --git a/lib/features/blog_post/presentation/pages/blog_post_screen.dart b/lib/features/blog_post/presentation/pages/blog_post_screen.dart index f9fc9696..c46c8b15 100644 --- a/lib/features/blog_post/presentation/pages/blog_post_screen.dart +++ b/lib/features/blog_post/presentation/pages/blog_post_screen.dart @@ -1,15 +1,14 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/features/blog_post/presentation/bloc/blog_post_cubit.dart'; import 'package:eatvio_app/features/blog_post/presentation/bloc/blog_post_state.dart'; import 'package:eatvio_app/locator_service.dart'; -import 'package:go_router/go_router.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:flutter/material.dart'; -import 'package:intl/intl.dart'; import 'package:eatvio_app/widgets/custom_edit_text_form_field.dart'; import 'package:eatvio_app/widgets/custom_outlined_button.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; +import 'package:intl/intl.dart'; class BlogPostScreen extends StatelessWidget { final String blogPostID; @@ -97,8 +96,7 @@ class BlogPostScreen extends StatelessWidget { ), ), CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + - (state.blogPost.author_avatar_path ?? ''), + imageUrl: baseUrl + '/storage/' + (state.blogPost.author_avatar_path ?? ''), imageBuilder: (context, imageProvider) => CircleAvatar( backgroundImage: imageProvider, radius: 25, @@ -221,7 +219,7 @@ class BlogPostScreen extends StatelessWidget { _buildImage(BlogPostStateLoaded state) { return CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (state.blogPost.image ?? ""), + imageUrl: baseUrl + '/storage/' + (state.blogPost.image ?? ""), imageBuilder: (context, imageProvider) => Stack( children: [ ClipRRect( diff --git a/lib/features/blog_post/services/blog_post_service.dart b/lib/features/blog_post/services/blog_post_service.dart index a406a7f3..00d8e560 100644 --- a/lib/features/blog_post/services/blog_post_service.dart +++ b/lib/features/blog_post/services/blog_post_service.dart @@ -8,6 +8,6 @@ part 'blog_post_service.g.dart'; abstract class BlogPostService { factory BlogPostService(Dio dio, {String baseUrl}) = _BlogPostService; - @GET('/feed/show/{id}') + @GET('/api/feed/show/{id}') Future getBlogPost(@Path() String id); } diff --git a/lib/features/blog_post/services/blog_post_service.g.dart b/lib/features/blog_post/services/blog_post_service.g.dart index c99e7859..40905775 100644 --- a/lib/features/blog_post/services/blog_post_service.g.dart +++ b/lib/features/blog_post/services/blog_post_service.g.dart @@ -32,7 +32,7 @@ class _BlogPostService implements BlogPostService { ) .compose( _dio.options, - '/feed/show/${id}', + '/api/feed/show/${id}', queryParameters: queryParameters, data: _data, ) diff --git a/lib/features/blog_post_create/models/blog_post_create_credentials_model.dart b/lib/features/blog_post_create/models/blog_post_create_credentials_model.dart index e961471b..ba68b46b 100644 --- a/lib/features/blog_post_create/models/blog_post_create_credentials_model.dart +++ b/lib/features/blog_post_create/models/blog_post_create_credentials_model.dart @@ -1,4 +1,5 @@ import 'package:freezed_annotation/freezed_annotation.dart'; + part '../../../presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.freezed.dart'; part '../../../presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.g.dart'; diff --git a/lib/features/blog_post_create/presentation/pages/blog_post_create_screen.dart b/lib/features/blog_post_create/presentation/pages/blog_post_create_screen.dart index 4bedcf52..755ce127 100644 --- a/lib/features/blog_post_create/presentation/pages/blog_post_create_screen.dart +++ b/lib/features/blog_post_create/presentation/pages/blog_post_create_screen.dart @@ -1,11 +1,13 @@ -import '../../../../presentation/feed/blog_post_create_screen/bloc/blog_post_create_bloc.dart'; -import '../../../../presentation/feed/blog_post_create_screen/models/blog_post_create_model.dart'; +import 'dart:io'; + import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/widgets/custom_outlined_button.dart'; +import 'package:eatvio_app/widgets/custom_text_form_field.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:eatvio_app/widgets/custom_outlined_button.dart'; -import 'dart:io'; + +import '../../../../presentation/feed/blog_post_create_screen/bloc/blog_post_create_bloc.dart'; +import '../../../../presentation/feed/blog_post_create_screen/models/blog_post_create_model.dart'; class BlogPostCreateScreen extends StatelessWidget { const BlogPostCreateScreen({Key? key}) : super(key: key); @@ -13,9 +15,7 @@ class BlogPostCreateScreen extends StatelessWidget { static Widget builder(BuildContext context) { final blog_postID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( - create: (context) => BlogPostCreateBloc(BlogPostCreateState( - blog_postModelObj: - BlogPostCreateModel(blog_postID: blog_postID.toString()))) + create: (context) => BlogPostCreateBloc(BlogPostCreateState(blog_postModelObj: BlogPostCreateModel(blog_postID: blog_postID.toString()))) ..add(BlogPostCreateInitialEvent()), child: BlogPostCreateScreen(), ); @@ -77,15 +77,13 @@ class BlogPostCreateScreen extends StatelessWidget { children: [ Column( children: [ - Text("Заголовок новости", - style: theme.textTheme.bodyLarge), + Text("Заголовок новости", style: theme.textTheme.bodyLarge), CustomTextFormField( controller: state.title, validator: _validateTitle, ), SizedBox(height: 8.0), - Text("Ссылка на YouTube", - style: theme.textTheme.bodyLarge), + Text("Ссылка на YouTube", style: theme.textTheme.bodyLarge), CustomTextFormField( controller: state.youtubeURL, validator: _validateYouTubeLink, @@ -102,8 +100,7 @@ class BlogPostCreateScreen extends StatelessWidget { SizedBox(height: 16.0), // Add widget for image upload here CustomOutlinedButton( - onPressed: () => _submitForm(context, state.title!.text, - state.description!.text, state.youtubeURL!.text), + onPressed: () => _submitForm(context, state.title!.text, state.description!.text, state.youtubeURL!.text), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, text: 'Создать', ), @@ -119,20 +116,16 @@ class BlogPostCreateScreen extends StatelessWidget { } } -_submitForm( - BuildContext context, String title, String description, String youtubeURL) { +_submitForm(BuildContext context, String title, String description, String youtubeURL) { String? titleError = _validateTitle(title); String? descriptionError = _validateDescription(description); String? youtubeURLError = _validateYouTubeLink(youtubeURL); - if (titleError != null || - descriptionError != null || - youtubeURLError != null) { + if (titleError != null || descriptionError != null || youtubeURLError != null) { // Display error messages or handle invalid input as needed // For example, show a snackbar with the error message ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text(titleError ?? descriptionError ?? youtubeURLError!)), + SnackBar(content: Text(titleError ?? descriptionError ?? youtubeURLError!)), ); } else { // Proceed with form submission @@ -233,7 +226,6 @@ String? _validateYouTubeLink(value) { } bool _isValidUrl(String url) { - final RegExp urlRegExp = - new RegExp(r"^(http|https):\/\/([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$"); + final RegExp urlRegExp = new RegExp(r"^(http|https):\/\/([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$"); return urlRegExp.hasMatch(url); } diff --git a/lib/features/blog_post_create/repositories/blog_repository.dart b/lib/features/blog_post_create/repositories/blog_repository.dart index e11bce9e..25b70823 100644 --- a/lib/features/blog_post_create/repositories/blog_repository.dart +++ b/lib/features/blog_post_create/repositories/blog_repository.dart @@ -8,8 +8,7 @@ class BlogRepository { required this.blogService, }); - Future createBlogPost( - BlogPostCreateCredentialsModel model) async { + Future createBlogPost(BlogPostCreateCredentialsModel model) async { try { return (await blogService.createBlogPost(model)); } catch (e) { diff --git a/lib/features/blog_post_create/services/blog_service.dart b/lib/features/blog_post_create/services/blog_service.dart index 1291c9a9..142682f5 100644 --- a/lib/features/blog_post_create/services/blog_service.dart +++ b/lib/features/blog_post_create/services/blog_service.dart @@ -1,5 +1,5 @@ -import 'package:eatvio_app/features/blog_post_create/models/blog_post_create_credentials_model.dart'; import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/blog_post_create/models/blog_post_create_credentials_model.dart'; import 'package:retrofit/retrofit.dart'; part 'blog_service.g.dart'; @@ -8,7 +8,6 @@ part 'blog_service.g.dart'; abstract class BlogService { factory BlogService(Dio dio, {String baseUrl}) = _BlogService; - @POST('/blog_post/create') - Future createBlogPost( - BlogPostCreateCredentialsModel model); + @POST('/api/blog_post/create') + Future createBlogPost(BlogPostCreateCredentialsModel model); } diff --git a/lib/features/blog_post_create/services/blog_service.g.dart b/lib/features/blog_post_create/services/blog_service.g.dart index 71ca2119..a6ff68e4 100644 --- a/lib/features/blog_post_create/services/blog_service.g.dart +++ b/lib/features/blog_post_create/services/blog_service.g.dart @@ -33,7 +33,7 @@ class _BlogService implements BlogService { ) .compose( _dio.options, - '/blog_post/create', + '/api/blog_post/create', queryParameters: queryParameters, data: _data, ) diff --git a/lib/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart b/lib/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart index 9865221a..5b890281 100644 --- a/lib/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart +++ b/lib/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart @@ -1,13 +1,13 @@ +import 'package:badges/badges.dart' as badges; import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart'; import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.dart'; import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_cubit.dart'; import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.dart'; -import 'package:flutter/material.dart'; import 'package:eatvio_app/widgets/custom_navigation_menu.dart'; +import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; -import 'package:badges/badges.dart' as badges; int currentBottomNavBarIndex = 0; diff --git a/lib/features/chat/models/chat_message_model.dart b/lib/features/chat/models/chat_message_model.dart index 00e17f59..23f03f9f 100644 --- a/lib/features/chat/models/chat_message_model.dart +++ b/lib/features/chat/models/chat_message_model.dart @@ -1,7 +1,6 @@ import 'package:freezed_annotation/freezed_annotation.dart'; part 'chat_message_model.freezed.dart'; - part 'chat_message_model.g.dart'; @freezed diff --git a/lib/features/chat/models/chat_messages_model.dart b/lib/features/chat/models/chat_messages_model.dart index 84a51b48..999f598e 100644 --- a/lib/features/chat/models/chat_messages_model.dart +++ b/lib/features/chat/models/chat_messages_model.dart @@ -3,7 +3,6 @@ import 'package:eatvio_app/features/chat/models/chat_meta_model.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'chat_messages_model.freezed.dart'; - part 'chat_messages_model.g.dart'; @freezed diff --git a/lib/features/chat/models/chat_meta_model.dart b/lib/features/chat/models/chat_meta_model.dart index 4c4d6cf0..b1e68a41 100644 --- a/lib/features/chat/models/chat_meta_model.dart +++ b/lib/features/chat/models/chat_meta_model.dart @@ -1,7 +1,6 @@ import 'package:freezed_annotation/freezed_annotation.dart'; part 'chat_meta_model.freezed.dart'; - part 'chat_meta_model.g.dart'; @freezed diff --git a/lib/features/chat/models/chat_room_model.dart b/lib/features/chat/models/chat_room_model.dart index 0196b49c..f9e9a416 100644 --- a/lib/features/chat/models/chat_room_model.dart +++ b/lib/features/chat/models/chat_room_model.dart @@ -3,7 +3,6 @@ import 'package:eatvio_app/features/chat/models/chat_user_model.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'chat_room_model.freezed.dart'; - part 'chat_room_model.g.dart'; @freezed diff --git a/lib/features/chat/models/chat_room_settings_model.dart b/lib/features/chat/models/chat_room_settings_model.dart index 7262c9a2..de41f221 100644 --- a/lib/features/chat/models/chat_room_settings_model.dart +++ b/lib/features/chat/models/chat_room_settings_model.dart @@ -1,7 +1,6 @@ import 'package:freezed_annotation/freezed_annotation.dart'; part 'chat_room_settings_model.freezed.dart'; - part 'chat_room_settings_model.g.dart'; @freezed diff --git a/lib/features/chat/models/chat_user_model.dart b/lib/features/chat/models/chat_user_model.dart index dd8bf02a..4ead086f 100644 --- a/lib/features/chat/models/chat_user_model.dart +++ b/lib/features/chat/models/chat_user_model.dart @@ -1,7 +1,6 @@ import 'package:freezed_annotation/freezed_annotation.dart'; part 'chat_user_model.freezed.dart'; - part 'chat_user_model.g.dart'; @freezed @@ -9,10 +8,8 @@ class ChatUserModel with _$ChatUserModel { const factory ChatUserModel({ required int id, required String name, - @JsonKey(name: 'profile_photo_path') - String? profilePhotoPath, - @JsonKey(name: 'profile_photo_url') - String? profilePhotoUrl, + @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, + @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl, }) = _ChatUserModel; factory ChatUserModel.fromJson(Map json) => _$ChatUserModelFromJson(json); diff --git a/lib/features/chat/models/websocket_info_model.dart b/lib/features/chat/models/websocket_info_model.dart index 274b4214..ed6167a0 100644 --- a/lib/features/chat/models/websocket_info_model.dart +++ b/lib/features/chat/models/websocket_info_model.dart @@ -1,7 +1,6 @@ import 'package:freezed_annotation/freezed_annotation.dart'; part 'websocket_info_model.freezed.dart'; - part 'websocket_info_model.g.dart'; @freezed @@ -11,8 +10,7 @@ class WebsocketInfoModel with _$WebsocketInfoModel { required String host, required String port, required String cluster, - @JsonKey(name: 'user_id') - required int userId, + @JsonKey(name: 'user_id') required int userId, }) = _WebsocketInfoModel; factory WebsocketInfoModel.fromJson(Map json) => _$WebsocketInfoModelFromJson(json); diff --git a/lib/features/chat/presentation/pages/chat_screen.dart b/lib/features/chat/presentation/pages/chat_screen.dart index d3ecef8b..d4747123 100644 --- a/lib/features/chat/presentation/pages/chat_screen.dart +++ b/lib/features/chat/presentation/pages/chat_screen.dart @@ -1,9 +1,9 @@ +import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart'; import 'package:eatvio_app/features/chat/presentation/widgets/chat_bubble_widget.dart'; import 'package:eatvio_app/locator_service.dart'; import 'package:flutter/cupertino.dart'; -import 'package:eatvio_app/core/app_export.dart'; import 'package:flutter/material.dart'; import 'package:lazy_load_scrollview/lazy_load_scrollview.dart'; @@ -155,9 +155,7 @@ class _ChatScreenState extends State { children: [ SizedBox(width: 8), InkWell( - onTap: () { - - }, + onTap: () {}, borderRadius: BorderRadiusStyle.circleBorder17, child: Ink( height: 32, @@ -179,7 +177,6 @@ class _ChatScreenState extends State { keyboardType: TextInputType.multiline, style: TextStyle( fontSize: 16, - fontFamily: 'Mulish', fontWeight: FontWeight.w400, color: Colors.black, ), @@ -188,7 +185,6 @@ class _ChatScreenState extends State { hintText: 'Сообщение', hintStyle: TextStyle( fontSize: 16, - fontFamily: 'Mulish', fontWeight: FontWeight.w400, color: Color(0xFFAEAEB2), ), diff --git a/lib/features/chat/presentation/pages/chat_select_screen/bloc/chat_select_bloc.dart b/lib/features/chat/presentation/pages/chat_select_screen/bloc/chat_select_bloc.dart index a055b5ef..8c60e607 100644 --- a/lib/features/chat/presentation/pages/chat_select_screen/bloc/chat_select_bloc.dart +++ b/lib/features/chat/presentation/pages/chat_select_screen/bloc/chat_select_bloc.dart @@ -1,19 +1,19 @@ +import 'dart:convert'; + import 'package:eatvio_app/app_router.dart'; import 'package:eatvio_app/features/chat/presentation/pages/chat_select_screen/models/chat_entry.dart'; import 'package:eatvio_app/features/chat/presentation/pages/chat_select_screen/models/chat_select_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; +import 'package:go_router/go_router.dart'; import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; import 'package:intl/intl.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'dart:convert'; + import '/core/app_export.dart'; -import 'package:go_router/go_router.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. @@ -59,7 +59,7 @@ class ChatSelectBloc extends Bloc { AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); } final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/chat/index'), + Uri.parse(baseUrl + '/api/chat/index'), headers: { 'Authorization': 'Bearer $token', }, diff --git a/lib/features/chat/presentation/pages/chat_select_screen/bloc/chat_select_state.dart b/lib/features/chat/presentation/pages/chat_select_screen/bloc/chat_select_state.dart index e5f1262a..2ee186f8 100644 --- a/lib/features/chat/presentation/pages/chat_select_screen/bloc/chat_select_state.dart +++ b/lib/features/chat/presentation/pages/chat_select_screen/bloc/chat_select_state.dart @@ -20,8 +20,7 @@ class ChatSelectState extends Equatable { } class ChatSelectInitialState extends ChatSelectState { - ChatSelectInitialState({required ChatSelectModel chatSelectModelObj}) - : super(chatSelectModelObj: chatSelectModelObj); + ChatSelectInitialState({required ChatSelectModel chatSelectModelObj}) : super(chatSelectModelObj: chatSelectModelObj); } class ChatSelectLoadedState extends ChatSelectState { diff --git a/lib/features/chat/presentation/pages/chat_select_screen/chat_search_view.dart b/lib/features/chat/presentation/pages/chat_select_screen/chat_search_view.dart index 22020a9e..1b8b49e5 100644 --- a/lib/features/chat/presentation/pages/chat_select_screen/chat_search_view.dart +++ b/lib/features/chat/presentation/pages/chat_select_screen/chat_search_view.dart @@ -1,5 +1,5 @@ -import 'package:flutter/material.dart'; import 'package:eatvio_app/core/app_export.dart'; +import 'package:flutter/material.dart'; class CustomSearchView extends StatelessWidget { CustomSearchView({ diff --git a/lib/features/chat/presentation/pages/chat_select_screen/chat_select_screen.dart b/lib/features/chat/presentation/pages/chat_select_screen/chat_select_screen.dart index d98ea7ff..3df79dfb 100644 --- a/lib/features/chat/presentation/pages/chat_select_screen/chat_select_screen.dart +++ b/lib/features/chat/presentation/pages/chat_select_screen/chat_select_screen.dart @@ -1,12 +1,13 @@ +import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/features/chat/presentation/pages/chat_select_screen/models/chat_entry.dart'; import 'package:eatvio_app/features/chat/presentation/pages/chat_select_screen/widgets/chat_entry_widget.dart'; import 'package:flutter/cupertino.dart'; -import 'bloc/chat_select_bloc.dart'; -import 'models/chat_select_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'chat_search_view.dart'; import 'package:flutter/material.dart'; +import 'bloc/chat_select_bloc.dart'; +import 'chat_search_view.dart'; +import 'models/chat_select_model.dart'; + class ChatSelectScreen extends StatelessWidget { const ChatSelectScreen({Key? key}) : super(key: key); @@ -42,18 +43,24 @@ class ChatSelectScreen extends StatelessWidget { body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return [ - SliverAppBar( - automaticallyImplyLeading: false, - stretchTriggerOffset: 1, - forceMaterialTransparency: true, - floating: true, - snap: true, - title: CustomSearchView( - controller: state.searchController, - fillColor: Color(0xFFF0F2F5), - hintText: "Поиск", - hintStyle: TextStyle( - color: Color(0xFF7B8794), + SliverPadding( + padding: const EdgeInsets.only(top: 8), + sliver: SliverAppBar( + automaticallyImplyLeading: false, + stretchTriggerOffset: 1, + forceMaterialTransparency: true, + floating: true, + snap: true, + title: Padding( + padding: const EdgeInsets.only(top: 8), + child: CustomSearchView( + controller: state.searchController, + fillColor: Color(0xFFF0F2F5), + hintText: "Поиск", + hintStyle: TextStyle( + color: Color(0xFF7B8794), + ), + ), ), ), ), diff --git a/lib/features/chat/presentation/pages/chat_select_screen/widgets/chat_entry_widget.dart b/lib/features/chat/presentation/pages/chat_select_screen/widgets/chat_entry_widget.dart index 4836f94a..0e46e718 100644 --- a/lib/features/chat/presentation/pages/chat_select_screen/widgets/chat_entry_widget.dart +++ b/lib/features/chat/presentation/pages/chat_select_screen/widgets/chat_entry_widget.dart @@ -1,8 +1,8 @@ // ignore_for_file: must_be_immutable +import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/features/chat/presentation/pages/chat_select_screen/models/chat_entry.dart'; import 'package:flutter/material.dart'; -import 'package:eatvio_app/core/app_export.dart'; import 'package:go_router/go_router.dart'; class ChatEntryWidget extends StatelessWidget { diff --git a/lib/features/chat/presentation/pages/photo_view_screen.dart b/lib/features/chat/presentation/pages/photo_view_screen.dart index f576a586..a070103d 100644 --- a/lib/features/chat/presentation/pages/photo_view_screen.dart +++ b/lib/features/chat/presentation/pages/photo_view_screen.dart @@ -2,7 +2,6 @@ import 'package:cached_network_image/cached_network_image.dart'; import 'package:dismissible_page/dismissible_page.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:go_router/go_router.dart'; import 'package:photo_view/photo_view.dart'; import 'package:photo_view/photo_view_gallery.dart'; @@ -84,7 +83,7 @@ class _PhotoViewScreenState extends State { color: Colors.white, ), title: Text( - widget.imageUrls[index].replaceAll(dotenv.env['STORAGE_URL']! + 'chat_files/', ''), + widget.imageUrls[index].replaceAll(baseUrl + '/storage/' + 'chat_files/', ''), style: TextStyle( color: Colors.white, fontSize: 12, diff --git a/lib/features/chat/presentation/widgets/chat_bubble_widget.dart b/lib/features/chat/presentation/widgets/chat_bubble_widget.dart index 6f9e9389..5a773cc3 100644 --- a/lib/features/chat/presentation/widgets/chat_bubble_widget.dart +++ b/lib/features/chat/presentation/widgets/chat_bubble_widget.dart @@ -1,9 +1,9 @@ import 'package:cached_network_image/cached_network_image.dart'; import 'package:dismissible_page/dismissible_page.dart'; +import 'package:eatvio_app/core/constants/constants.dart'; import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; import 'package:eatvio_app/theme/app_decoration.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:url_launcher/url_launcher.dart'; class ChatBubbleWidget extends StatelessWidget { @@ -48,7 +48,7 @@ class ChatBubbleWidget extends StatelessWidget { contentPadding: EdgeInsets.zero, horizontalTitleGap: 8, onTap: () async { - if (!await launchUrl(Uri.parse(dotenv.env['STORAGE_URL']! + mediaData[index].toString()))) { + if (!await launchUrl(Uri.parse(baseUrl + '/storage/' + mediaData[index].toString()))) { throw Exception('Could not launch ${mediaData[index].toString()}'); } }, @@ -75,18 +75,18 @@ class ChatBubbleWidget extends StatelessWidget { onTap: () { context.pushTransparentRoute( PhotoViewScreen( - imageUrls: mediaData.map((e) => dotenv.env['STORAGE_URL']! + e.toString()).toList(), + imageUrls: mediaData.map((e) => baseUrl + '/storage/' + e.toString()).toList(), index: index, ), ); }, child: Hero( - tag: dotenv.env['STORAGE_URL']! + '${mediaData[index]}', + tag: baseUrl + '/storage/' + '${mediaData[index]}', transitionOnUserGestures: true, child: ClipRRect( borderRadius: BorderRadiusStyle.roundedBorder8, child: CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + '${mediaData[index]}', + imageUrl: baseUrl + '/storage/' + '${mediaData[index]}', ), ), ), diff --git a/lib/features/chat/services/chat_service.dart b/lib/features/chat/services/chat_service.dart index 675d6806..888aaba0 100644 --- a/lib/features/chat/services/chat_service.dart +++ b/lib/features/chat/services/chat_service.dart @@ -1,8 +1,8 @@ import 'dart:io'; +import 'package:dio/dio.dart'; import 'package:eatvio_app/features/chat/models/chat_messages_model.dart'; import 'package:eatvio_app/features/chat/models/chat_room_model.dart'; -import 'package:dio/dio.dart'; import 'package:eatvio_app/features/chat/models/websocket_info_model.dart'; import 'package:retrofit/retrofit.dart'; @@ -12,24 +12,24 @@ part 'chat_service.g.dart'; abstract class ChatService { factory ChatService(Dio dio, {String baseUrl}) = _ChatService; - @GET('/chat/show/{id}') + @GET('/api/chat/show/{id}') Future> getChatRoom({ @Path() required String id, }); - @POST('/chat/{id}/message/send') + @POST('/api/chat/{id}/message/send') Future sendMessage({ @Path() required String id, @Part() String? data, @Part() List? filesList, }); - @GET('/chat/show/{id}/messages?page={page}') + @GET('/api/chat/show/{id}/messages?page={page}') Future getChatMessages({ @Path() required String id, @Path() required int page, }); - @GET('/profile/ws/params') + @GET('/api/profile/ws/params') Future getWebsocket(); } diff --git a/lib/features/chat/services/chat_service.g.dart b/lib/features/chat/services/chat_service.g.dart index 65eb7c5e..2f0674be 100644 --- a/lib/features/chat/services/chat_service.g.dart +++ b/lib/features/chat/services/chat_service.g.dart @@ -32,7 +32,7 @@ class _ChatService implements ChatService { ) .compose( _dio.options, - '/chat/show/${id}', + '/api/chat/show/${id}', queryParameters: queryParameters, data: _data, ) @@ -78,7 +78,7 @@ class _ChatService implements ChatService { ) .compose( _dio.options, - '/chat/${id}/message/send', + '/api/chat/${id}/message/send', queryParameters: queryParameters, data: _data, ) @@ -106,7 +106,7 @@ class _ChatService implements ChatService { ) .compose( _dio.options, - '/chat/show/${id}/messages?page=${page}', + '/api/chat/show/${id}/messages?page=${page}', queryParameters: queryParameters, data: _data, ) @@ -133,7 +133,7 @@ class _ChatService implements ChatService { ) .compose( _dio.options, - '/profile/ws/params', + '/api/profile/ws/params', queryParameters: queryParameters, data: _data, ) diff --git a/lib/features/diary/presentation/bloc/diary_cubit.dart b/lib/features/diary/presentation/bloc/diary_cubit.dart index 07477bd0..ddc86761 100644 --- a/lib/features/diary/presentation/bloc/diary_cubit.dart +++ b/lib/features/diary/presentation/bloc/diary_cubit.dart @@ -19,4 +19,4 @@ class DiaryCubit extends Cubit { } } } -*/ \ No newline at end of file +*/ diff --git a/lib/features/diary/presentation/bloc/diary_state.dart b/lib/features/diary/presentation/bloc/diary_state.dart index d4305c8d..90e9f4f6 100644 --- a/lib/features/diary/presentation/bloc/diary_state.dart +++ b/lib/features/diary/presentation/bloc/diary_state.dart @@ -17,4 +17,4 @@ abstract class DiaryState with _$DiaryState { required String errorMessage, }) = DiaryStateError; } -*/ \ No newline at end of file +*/ diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index 9cbf2045..7218cf61 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -7,7 +7,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:fl_chart/fl_chart.dart'; import 'package:image_picker/image_picker.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; + import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/widgets/custom_edit_text_form_field.dart'; import 'package:eatvio_app/widgets/custom_edit_drop_down.dart'; @@ -731,7 +731,7 @@ class DiaryEditScreen extends StatelessWidget { borderRadius: BorderRadiusStyle.roundedBorder5, ), child: Image.network( - dotenv.env['STORAGE_URL']! + photo['path'], + baseUrl + '/storage/' + photo['path'], ), ), Positioned( @@ -1296,4 +1296,4 @@ bool checkConsumedValues( // Если ни одно потребленное значение не превышает рекомендованное с соответствующим индексом return false; // Возвращаем true } -*/ \ No newline at end of file +*/ diff --git a/lib/features/diary/repositories/diary_repository.dart b/lib/features/diary/repositories/diary_repository.dart index 1ae40d88..b5ca0317 100644 --- a/lib/features/diary/repositories/diary_repository.dart +++ b/lib/features/diary/repositories/diary_repository.dart @@ -14,4 +14,4 @@ class DiaryRepository { } } } -*/ \ No newline at end of file +*/ diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart index 6b6cb6bb..07490375 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -8,7 +8,7 @@ part 'diary_service.g.dart'; abstract class DiaryService { factory DiaryService(Dio dio, {String baseUrl}) = _DiaryService; - @GET('/feed/show/{id}') + @GET('/api/feed/show/{id}') Future getDiary(@Path() String id); } -*/ \ No newline at end of file +*/ diff --git a/lib/features/feed/models/feed_blog_post_settings_model.dart b/lib/features/feed/models/feed_blog_post_settings_model.dart new file mode 100644 index 00000000..8296a8be --- /dev/null +++ b/lib/features/feed/models/feed_blog_post_settings_model.dart @@ -0,0 +1,14 @@ +import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'feed_blog_post_settings_model.freezed.dart'; +part 'feed_blog_post_settings_model.g.dart'; + +@freezed +class FeedBlogPostSettingsModel with _$FeedBlogPostSettingsModel { + const factory FeedBlogPostSettingsModel({ + @JsonKey(name: 'data') required List feedBlogPostList, + }) = _FeedBlogPostSettingsModel; + + factory FeedBlogPostSettingsModel.fromJson(Map json) => _$FeedBlogPostSettingsModelFromJson(json); +} diff --git a/lib/features/feed/models/feed_blog_post_settings_model.freezed.dart b/lib/features/feed/models/feed_blog_post_settings_model.freezed.dart new file mode 100644 index 00000000..7fd8a12e --- /dev/null +++ b/lib/features/feed/models/feed_blog_post_settings_model.freezed.dart @@ -0,0 +1,175 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'feed_blog_post_settings_model.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +FeedBlogPostSettingsModel _$FeedBlogPostSettingsModelFromJson( + Map json) { + return _FeedBlogPostSettingsModel.fromJson(json); +} + +/// @nodoc +mixin _$FeedBlogPostSettingsModel { + @JsonKey(name: 'data') + List get feedBlogPostList => + throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $FeedBlogPostSettingsModelCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $FeedBlogPostSettingsModelCopyWith<$Res> { + factory $FeedBlogPostSettingsModelCopyWith(FeedBlogPostSettingsModel value, + $Res Function(FeedBlogPostSettingsModel) then) = + _$FeedBlogPostSettingsModelCopyWithImpl<$Res, FeedBlogPostSettingsModel>; + @useResult + $Res call({@JsonKey(name: 'data') List feedBlogPostList}); +} + +/// @nodoc +class _$FeedBlogPostSettingsModelCopyWithImpl<$Res, + $Val extends FeedBlogPostSettingsModel> + implements $FeedBlogPostSettingsModelCopyWith<$Res> { + _$FeedBlogPostSettingsModelCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? feedBlogPostList = null, + }) { + return _then(_value.copyWith( + feedBlogPostList: null == feedBlogPostList + ? _value.feedBlogPostList + : feedBlogPostList // ignore: cast_nullable_to_non_nullable + as List, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$FeedBlogPostSettingsModelImplCopyWith<$Res> + implements $FeedBlogPostSettingsModelCopyWith<$Res> { + factory _$$FeedBlogPostSettingsModelImplCopyWith( + _$FeedBlogPostSettingsModelImpl value, + $Res Function(_$FeedBlogPostSettingsModelImpl) then) = + __$$FeedBlogPostSettingsModelImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({@JsonKey(name: 'data') List feedBlogPostList}); +} + +/// @nodoc +class __$$FeedBlogPostSettingsModelImplCopyWithImpl<$Res> + extends _$FeedBlogPostSettingsModelCopyWithImpl<$Res, + _$FeedBlogPostSettingsModelImpl> + implements _$$FeedBlogPostSettingsModelImplCopyWith<$Res> { + __$$FeedBlogPostSettingsModelImplCopyWithImpl( + _$FeedBlogPostSettingsModelImpl _value, + $Res Function(_$FeedBlogPostSettingsModelImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? feedBlogPostList = null, + }) { + return _then(_$FeedBlogPostSettingsModelImpl( + feedBlogPostList: null == feedBlogPostList + ? _value._feedBlogPostList + : feedBlogPostList // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$FeedBlogPostSettingsModelImpl implements _FeedBlogPostSettingsModel { + const _$FeedBlogPostSettingsModelImpl( + {@JsonKey(name: 'data') + required final List feedBlogPostList}) + : _feedBlogPostList = feedBlogPostList; + + factory _$FeedBlogPostSettingsModelImpl.fromJson(Map json) => + _$$FeedBlogPostSettingsModelImplFromJson(json); + + final List _feedBlogPostList; + @override + @JsonKey(name: 'data') + List get feedBlogPostList { + if (_feedBlogPostList is EqualUnmodifiableListView) + return _feedBlogPostList; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_feedBlogPostList); + } + + @override + String toString() { + return 'FeedBlogPostSettingsModel(feedBlogPostList: $feedBlogPostList)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$FeedBlogPostSettingsModelImpl && + const DeepCollectionEquality() + .equals(other._feedBlogPostList, _feedBlogPostList)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_feedBlogPostList)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$FeedBlogPostSettingsModelImplCopyWith<_$FeedBlogPostSettingsModelImpl> + get copyWith => __$$FeedBlogPostSettingsModelImplCopyWithImpl< + _$FeedBlogPostSettingsModelImpl>(this, _$identity); + + @override + Map toJson() { + return _$$FeedBlogPostSettingsModelImplToJson( + this, + ); + } +} + +abstract class _FeedBlogPostSettingsModel implements FeedBlogPostSettingsModel { + const factory _FeedBlogPostSettingsModel( + {@JsonKey(name: 'data') + required final List feedBlogPostList}) = + _$FeedBlogPostSettingsModelImpl; + + factory _FeedBlogPostSettingsModel.fromJson(Map json) = + _$FeedBlogPostSettingsModelImpl.fromJson; + + @override + @JsonKey(name: 'data') + List get feedBlogPostList; + @override + @JsonKey(ignore: true) + _$$FeedBlogPostSettingsModelImplCopyWith<_$FeedBlogPostSettingsModelImpl> + get copyWith => throw _privateConstructorUsedError; +} diff --git a/lib/features/feed/models/feed_blog_post_settings_model.g.dart b/lib/features/feed/models/feed_blog_post_settings_model.g.dart new file mode 100644 index 00000000..3f48be1b --- /dev/null +++ b/lib/features/feed/models/feed_blog_post_settings_model.g.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'feed_blog_post_settings_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$FeedBlogPostSettingsModelImpl _$$FeedBlogPostSettingsModelImplFromJson( + Map json) => + _$FeedBlogPostSettingsModelImpl( + feedBlogPostList: (json['data'] as List) + .map((e) => FeedBlogPostModel.fromJson(e as Map)) + .toList(), + ); + +Map _$$FeedBlogPostSettingsModelImplToJson( + _$FeedBlogPostSettingsModelImpl instance) => + { + 'data': instance.feedBlogPostList, + }; diff --git a/lib/features/feed/presentation/pages/feed_screen.dart b/lib/features/feed/presentation/pages/feed_screen.dart index 797bfbba..e97b39e1 100644 --- a/lib/features/feed/presentation/pages/feed_screen.dart +++ b/lib/features/feed/presentation/pages/feed_screen.dart @@ -1,15 +1,14 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_state.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:go_router/go_router.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:eatvio_app/presentation/feed/feed_screen/widgets/feed_search_view.dart'; import 'package:eatvio_app/presentation/feed/feed_screen/widgets/feed_scroll_item.dart'; +import 'package:eatvio_app/presentation/feed/feed_screen/widgets/feed_search_view.dart'; import 'package:eatvio_app/widgets/custom_outlined_button.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; import 'package:intl/intl.dart'; class FeedScreen extends StatelessWidget { @@ -153,7 +152,7 @@ class FeedScreen extends StatelessWidget { children: [ ListTile( leading: CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (''), + imageUrl: baseUrl + '/storage/' + (''), /// todo profile photo path imageBuilder: (context, imageProvider) => CircleAvatar( @@ -224,7 +223,7 @@ class FeedScreen extends StatelessWidget { ), SizedBox(height: 16.0), CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (post.image), + imageUrl: baseUrl + '/storage/' + (post.image), imageBuilder: (context, imageProvider) => Stack( children: [ ClipRRect( diff --git a/lib/features/feed/repositories/feed_repository.dart b/lib/features/feed/repositories/feed_repository.dart index 50799a01..319ac32e 100644 --- a/lib/features/feed/repositories/feed_repository.dart +++ b/lib/features/feed/repositories/feed_repository.dart @@ -8,7 +8,7 @@ class FeedRepository { Future> getFeedBlogPostList() async { try { - return (await feedService.getBlocPostList()).entries.map((entry) => entry.value).toList(); + return (await feedService.getBlocPostList()).feedBlogPostList; } catch (e) { rethrow; } diff --git a/lib/features/feed/services/feed_service.dart b/lib/features/feed/services/feed_service.dart index d4f728fb..d96ba1cc 100644 --- a/lib/features/feed/services/feed_service.dart +++ b/lib/features/feed/services/feed_service.dart @@ -1,5 +1,5 @@ import 'package:dio/dio.dart'; -import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; +import 'package:eatvio_app/features/feed/models/feed_blog_post_settings_model.dart'; import 'package:retrofit/retrofit.dart'; part 'feed_service.g.dart'; @@ -8,6 +8,6 @@ part 'feed_service.g.dart'; abstract class FeedService { factory FeedService(Dio dio, {String baseUrl}) = _FeedService; - @GET('/feed/index') - Future> getBlocPostList(); + @GET('/api/blogPosts/index') + Future getBlocPostList(); } diff --git a/lib/features/feed/services/feed_service.g.dart b/lib/features/feed/services/feed_service.g.dart index 03aa2386..89003f6e 100644 --- a/lib/features/feed/services/feed_service.g.dart +++ b/lib/features/feed/services/feed_service.g.dart @@ -19,20 +19,20 @@ class _FeedService implements FeedService { String? baseUrl; @override - Future> getBlocPostList() async { + Future getBlocPostList() async { final _extra = {}; final queryParameters = {}; final _headers = {}; const Map? _data = null; final _result = await _dio.fetch>( - _setStreamType>(Options( + _setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) .compose( _dio.options, - '/feed/index', + '/api/blogPosts/index', queryParameters: queryParameters, data: _data, ) @@ -41,8 +41,7 @@ class _FeedService implements FeedService { _dio.options.baseUrl, baseUrl, )))); - var _value = _result.data!.map((k, dynamic v) => - MapEntry(k, FeedBlogPostModel.fromJson(v as Map))); + final _value = FeedBlogPostSettingsModel.fromJson(_result.data!); return _value; } diff --git a/lib/features/registration/consts/cities_list.dart b/lib/features/registration/consts/cities_list.dart new file mode 100644 index 00000000..0eea40d6 --- /dev/null +++ b/lib/features/registration/consts/cities_list.dart @@ -0,0 +1,1119 @@ +const List citiesList = const [ + "Абаза", + "Абакан", + "Абдулино", + "Абинск", + "Агидель", + "Агрыз", + "Адыгейск", + "Азнакаево", + "Азов", + "Ак-Довурак", + "Аксай", + "Алагир", + "Алапаевск", + "Алатырь", + "Алдан", + "Алейск", + "Александров", + "Александровск", + "Александровск-Сахалинский", + "Алексеевка", + "Алексин", + "Алзамай", + "АлупкаОспаривается", + "АлуштаОспаривается", + "Альметьевск", + "Амурск", + "Анадырь", + "Анапа", + "Ангарск", + "Андреаполь", + "Анжеро-Судженск", + "Анива", + "Апатиты", + "Апрелевка", + "Апшеронск", + "Арамиль", + "Аргун", + "Ардатов", + "Ардон", + "Арзамас", + "Аркадак", + "Армавир", + "АрмянскОспаривается", + "Арсеньев", + "Арск", + "Артём", + "Артёмовск", + "Артёмовский", + "Архангельск", + "Асбест", + "Асино", + "Астрахань", + "Аткарск", + "Ахтубинск", + "Ачинск", + "Аша", + "Бабаево", + "Бабушкин", + "Бавлы", + "Багратионовск", + "Байкальск", + "Баймак", + "Бакал", + "Баксан", + "Балабаново", + "Балаково", + "Балахна", + "Балашиха", + "Балашов", + "Балей", + "Балтийск", + "Барабинск", + "Барнаул", + "Барыш", + "Батайск", + "БахчисарайОспаривается", + "Бежецк", + "Белая Калитва", + "Белая Холуница", + "Белгород", + "Белебей", + "Белёв", + "Белинский", + "Белово", + "Белогорск", + "БелогорскОспаривается", + "Белозерск", + "Белокуриха", + "Беломорск", + "Белоозёрский", + "Белорецк", + "Белореченск", + "Белоусово", + "Белоярский", + "Белый", + "Бердск", + "Березники", + "Берёзовский", + "Берёзовский", + "Беслан", + "Бийск", + "Бикин", + "Билибино", + "Биробиджан", + "Бирск", + "Бирюсинск", + "Бирюч", + "Благовещенск", + "Благовещенск", + "Благодарный", + "Бобров", + "Богданович", + "Богородицк", + "Богородск", + "Боготол", + "Богучар", + "Бодайбо", + "Бокситогорск", + "Болгар", + "Бологое", + "Болотное", + "Болохово", + "Болхов", + "Большой Камень", + "Бор", + "Борзя", + "Борисоглебск", + "Боровичи", + "Боровск", + "Бородино", + "Братск", + "Бронницы", + "Брянск", + "Бугульма", + "Бугуруслан", + "Будённовск", + "Бузулук", + "Буинск", + "Буй", + "Буйнакск", + "Бутурлиновка", + "Валдай", + "Валуйки", + "Велиж", + "Великие Луки", + "Великий Новгород", + "Великий Устюг", + "Вельск", + "Венёв", + "Верещагино", + "Верея", + "Верхнеуральск", + "Верхний Тагил", + "Верхний Уфалей", + "Верхняя Пышма", + "Верхняя Салда", + "Верхняя Тура", + "Верхотурье", + "Верхоянск", + "Весьегонск", + "Ветлуга", + "Видное", + "Вилюйск", + "Вилючинск", + "Вихоревка", + "Вичуга", + "Владивосток", + "Владикавказ", + "Владимир", + "Волгоград", + "Волгодонск", + "Волгореченск", + "Волжск", + "Волжский", + "Вологда", + "Володарск", + "Волоколамск", + "Волосово", + "Волхов", + "Волчанск", + "Вольск", + "Воркута", + "Воронеж", + "Ворсма", + "Воскресенск", + "Воткинск", + "Всеволожск", + "Вуктыл", + "Выборг", + "Выкса", + "Высоковск", + "Высоцк", + "Вытегра", + "Вышний Волочёк", + "Вяземский", + "Вязники", + "Вязьма", + "Вятские Поляны", + "Гаврилов Посад", + "Гаврилов-Ям", + "Гагарин", + "Гаджиево", + "Гай", + "Галич", + "Гатчина", + "Гвардейск", + "Гдов", + "Геленджик", + "Георгиевск", + "Глазов", + "Голицыно", + "Горбатов", + "Горно-Алтайск", + "Горнозаводск", + "Горняк", + "Городец", + "Городище", + "Городовиковск", + "Гороховец", + "Горячий Ключ", + "Грайворон", + "Гремячинск", + "Грозный", + "Грязи", + "Грязовец", + "Губаха", + "Губкин", + "Губкинский", + "Гудермес", + "Гуково", + "Гулькевичи", + "Гурьевск", + "Гурьевск", + "Гусев", + "Гусиноозёрск", + "Гусь-Хрустальный", + "Давлеканово", + "Дагестанские Огни", + "Далматово", + "Дальнегорск", + "Дальнереченск", + "Данилов", + "Данков", + "Дегтярск", + "Дедовск", + "Демидов", + "Дербент", + "Десногорск", + "ДжанкойОспаривается", + "Дзержинск", + "Дзержинский", + "Дивногорск", + "Дигора", + "Димитровград", + "Дмитриев", + "Дмитров", + "Дмитровск", + "Дно", + "Добрянка", + "Долгопрудный", + "Долинск", + "Домодедово", + "Донецк", + "Донской", + "Дорогобуж", + "Дрезна", + "Дубна", + "Дубовка", + "Дудинка", + "Духовщина", + "Дюртюли", + "Дятьково", + "ЕвпаторияОспаривается", + "Егорьевск", + "Ейск", + "Екатеринбург", + "Елабуга", + "Елец", + "Елизово", + "Ельня", + "Еманжелинск", + "Емва", + "Енисейск", + "Ермолино", + "Ершов", + "Ессентуки", + "Ефремов", + "Железноводск", + "Железногорск", + "Железногорск", + "Железногорск-Илимский", + "Жердевка", + "Жигулёвск", + "Жиздра", + "Жирновск", + "Жуков", + "Жуковка", + "Жуковский", + "Завитинск", + "Заводоуковск", + "Заволжск", + "Заволжье", + "Задонск", + "Заинск", + "Закаменск", + "Заозёрный", + "Заозёрск", + "Западная Двина", + "Заполярный", + "Зарайск", + "Заречный", + "Заречный", + "Заринск", + "Звенигово", + "Звенигород", + "Зверево", + "Зеленогорск", + "Зеленоградск", + "Зеленодольск", + "Зеленокумск", + "Зерноград", + "Зея", + "Зима", + "Златоуст", + "Злынка", + "Змеиногорск", + "Знаменск", + "Зубцов", + "Зуевка", + "Ивангород", + "Иваново", + "Ивантеевка", + "Ивдель", + "Игарка", + "Ижевск", + "Избербаш", + "Изобильный", + "Иланский", + "Инза", + "Иннополис", + "Инсар", + "Инта", + "Ипатово", + "Ирбит", + "Иркутск", + "Исилькуль", + "Искитим", + "Истра", + "Ишим", + "Ишимбай", + "Йошкар-Ола", + "Кадников", + "Казань", + "Калач", + "Калач-на-Дону", + "Калачинск", + "Калининград", + "Калининск", + "Калтан", + "Калуга", + "Калязин", + "Камбарка", + "Каменка", + "Каменногорск", + "Каменск-Уральский", + "Каменск-Шахтинский", + "Камень-на-Оби", + "Камешково", + "Камызяк", + "Камышин", + "Камышлов", + "Канаш", + "Кандалакша", + "Канск", + "Карабаново", + "Карабаш", + "Карабулак", + "Карасук", + "Карачаевск", + "Карачев", + "Каргат", + "Каргополь", + "Карпинск", + "Карталы", + "Касимов", + "Касли", + "Каспийск", + "Катав-Ивановск", + "Катайск", + "Качканар", + "Кашин", + "Кашира", + "Кедровый", + "Кемерово", + "Кемь", + "КерчьОспаривается", + "Кизел", + "Кизилюрт", + "Кизляр", + "Кимовск", + "Кимры", + "Кингисепп", + "Кинель", + "Кинешма", + "Киреевск", + "Киренск", + "Киржач", + "Кириллов", + "Кириши", + "Киров", + "Киров", + "Кировград", + "Кирово-Чепецк", + "Кировск", + "Кировск", + "Кирс", + "Кирсанов", + "Киселёвск", + "Кисловодск", + "Клин", + "Клинцы", + "Княгинино", + "Ковдор", + "Ковров", + "Ковылкино", + "Когалым", + "Кодинск", + "Козельск", + "Козловка", + "Козьмодемьянск", + "Кола", + "Кологрив", + "Коломна", + "Колпашево", + "Кольчугино", + "Коммунар", + "Комсомольск", + "Комсомольск-на-Амуре", + "Конаково", + "Кондопога", + "Кондрово", + "Константиновск", + "Копейск", + "Кораблино", + "Кореновск", + "Коркино", + "Королёв", + "Короча", + "Корсаков", + "Коряжма", + "Костерёво", + "Костомукша", + "Кострома", + "Котельники", + "Котельниково", + "Котельнич", + "Котлас", + "Котово", + "Котовск", + "Кохма", + "Красавино", + "Красноармейск", + "Красноармейск", + "Красновишерск", + "Красногорск", + "Краснодар", + "Краснозаводск", + "Краснознаменск", + "Краснознаменск", + "Краснокаменск", + "Краснокамск", + "КрасноперекопскОспаривается", + "Краснослободск", + "Краснослободск", + "Краснотурьинск", + "Красноуральск", + "Красноуфимск", + "Красноярск", + "Красный Кут", + "Красный Сулин", + "Красный Холм", + "Кремёнки", + "Кропоткин", + "Крымск", + "Кстово", + "Кубинка", + "Кувандык", + "Кувшиново", + "Кудрово", + "Кудымкар", + "Кузнецк", + "Куйбышев", + "Кукмор", + "Кулебаки", + "Кумертау", + "Кунгур", + "Купино", + "Курган", + "Курганинск", + "Курильск", + "Курлово", + "Куровское", + "Курск", + "Куртамыш", + "Курчалой", + "Курчатов", + "Куса", + "Кушва", + "Кызыл", + "Кыштым", + "Кяхта", + "Лабинск", + "Лабытнанги", + "Лагань", + "Ладушкин", + "Лаишево", + "Лакинск", + "Лангепас", + "Лахденпохья", + "Лебедянь", + "Лениногорск", + "Ленинск", + "Ленинск-Кузнецкий", + "Ленск", + "Лермонтов", + "Лесной", + "Лесозаводск", + "Лесосибирск", + "Ливны", + "Ликино-Дулёво", + "Липецк", + "Липки", + "Лиски", + "Лихославль", + "Лобня", + "Лодейное Поле", + "Лосино-Петровский", + "Луга", + "Луза", + "Лукоянов", + "Луховицы", + "Лысково", + "Лысьва", + "Лыткарино", + "Льгов", + "Любань", + "Люберцы", + "Любим", + "Людиново", + "Лянтор", + "Магадан", + "Магас", + "Магнитогорск", + "Майкоп", + "Майский", + "Макаров", + "Макарьев", + "Макушино", + "Малая Вишера", + "Малгобек", + "Малмыж", + "Малоархангельск", + "Малоярославец", + "Мамадыш", + "Мамоново", + "Мантурово", + "Мариинск", + "Мариинский Посад", + "Маркс", + "Махачкала", + "Мглин", + "Мегион", + "Медвежьегорск", + "Медногорск", + "Медынь", + "Межгорье", + "Междуреченск", + "Мезень", + "Меленки", + "Мелеуз", + "Менделеевск", + "Мензелинск", + "Мещовск", + "Миасс", + "Микунь", + "Миллерово", + "Минеральные Воды", + "Минусинск", + "Миньяр", + "Мирный", + "Мирный", + "Михайлов", + "Михайловка", + "Михайловск", + "Михайловск", + "Мичуринск", + "Могоча", + "Можайск", + "Можга", + "Моздок", + "Мончегорск", + "Морозовск", + "Моршанск", + "Мосальск", + "Москва", + "Муравленко", + "Мураши", + "Мурино", + "Мурманск", + "Муром", + "Мценск", + "Мыски", + "Мытищи", + "Мышкин", + "Набережные Челны", + "Навашино", + "Наволоки", + "Надым", + "Назарово", + "Назрань", + "Называевск", + "Нальчик", + "Нариманов", + "Наро-Фоминск", + "Нарткала", + "Нарьян-Мар", + "Находка", + "Невель", + "Невельск", + "Невинномысск", + "Невьянск", + "Нелидово", + "Неман", + "Нерехта", + "Нерчинск", + "Нерюнгри", + "Нестеров", + "Нефтегорск", + "Нефтекамск", + "Нефтекумск", + "Нефтеюганск", + "Нея", + "Нижневартовск", + "Нижнекамск", + "Нижнеудинск", + "Нижние Серги", + "Нижний Ломов", + "Нижний Новгород", + "Нижний Тагил", + "Нижняя Салда", + "Нижняя Тура", + "Николаевск", + "Николаевск-на-Амуре", + "Никольск", + "Никольск", + "Никольское", + "Новая Ладога", + "Новая Ляля", + "Новоалександровск", + "Новоалтайск", + "Новоаннинский", + "Нововоронеж", + "Новодвинск", + "Новозыбков", + "Новокубанск", + "Новокузнецк", + "Новокуйбышевск", + "Новомичуринск", + "Новомосковск", + "Новопавловск", + "Новоржев", + "Новороссийск", + "Новосибирск", + "Новосиль", + "Новосокольники", + "Новотроицк", + "Новоузенск", + "Новоульяновск", + "Новоуральск", + "Новохопёрск", + "Новочебоксарск", + "Новочеркасск", + "Новошахтинск", + "Новый Оскол", + "Новый Уренгой", + "Ногинск", + "Нолинск", + "Норильск", + "Ноябрьск", + "Нурлат", + "Нытва", + "Нюрба", + "Нягань", + "Нязепетровск", + "Няндома", + "Облучье", + "Обнинск", + "Обоянь", + "Обь", + "Одинцово", + "Озёрск", + "Озёрск", + "Озёры", + "Октябрьск", + "Октябрьский", + "Окуловка", + "Олёкминск", + "Оленегорск", + "Олонец", + "Омск", + "Омутнинск", + "Онега", + "Опочка", + "Орёл", + "Оренбург", + "Орехово-Зуево", + "Орлов", + "Орск", + "Оса", + "Осинники", + "Осташков", + "Остров", + "Островной", + "Острогожск", + "Отрадное", + "Отрадный", + "Оха", + "Оханск", + "Очёр", + "Павлово", + "Павловск", + "Павловский Посад", + "Палласовка", + "Партизанск", + "Певек", + "Пенза", + "Первомайск", + "Первоуральск", + "Перевоз", + "Пересвет", + "Переславль-Залесский", + "Пермь", + "Пестово", + "Петров Вал", + "Петровск", + "Петровск-Забайкальский", + "Петрозаводск", + "Петропавловск-Камчатский", + "Петухово", + "Петушки", + "Печора", + "Печоры", + "Пикалёво", + "Пионерский", + "Питкяранта", + "Плавск", + "Пласт", + "Плёс", + "Поворино", + "Подольск", + "Подпорожье", + "Покачи", + "Покров", + "Покровск", + "Полевской", + "Полесск", + "Полысаево", + "Полярные Зори", + "Полярный", + "Поронайск", + "Порхов", + "Похвистнево", + "Почеп", + "Починок", + "Пошехонье", + "Правдинск", + "Приволжск", + "Приморск", + "Приморск", + "Приморско-Ахтарск", + "Приозерск", + "Прокопьевск", + "Пролетарск", + "Протвино", + "Прохладный", + "Псков", + "Пугачёв", + "Пудож", + "Пустошка", + "Пучеж", + "Пушкино", + "Пущино", + "Пыталово", + "Пыть-Ях", + "Пятигорск", + "Радужный", + "Радужный", + "Райчихинск", + "Раменское", + "Рассказово", + "Ревда", + "Реж", + "Реутов", + "Ржев", + "Родники", + "Рославль", + "Россошь", + "Ростов-на-Дону", + "Ростов", + "Рошаль", + "Ртищево", + "Рубцовск", + "Рудня", + "Руза", + "Рузаевка", + "Рыбинск", + "Рыбное", + "Рыльск", + "Ряжск", + "Рязань", + "СакиОспаривается", + "Салават", + "Салаир", + "Салехард", + "Сальск", + "Самара", + "Санкт-Петербург", + "Саранск", + "Сарапул", + "Саратов", + "Саров", + "Сасово", + "Сатка", + "Сафоново", + "Саяногорск", + "Саянск", + "Светлогорск", + "Светлоград", + "Светлый", + "Светогорск", + "Свирск", + "Свободный", + "Себеж", + "СевастопольОспаривается", + "Северо-Курильск", + "Северобайкальск", + "Северодвинск", + "Североморск", + "Североуральск", + "Северск", + "Севск", + "Сегежа", + "Сельцо", + "Семёнов", + "Семикаракорск", + "Семилуки", + "Сенгилей", + "Серафимович", + "Сергач", + "Сергиев Посад", + "Сердобск", + "Серов", + "Серпухов", + "Сертолово", + "Сибай", + "Сим", + "СимферопольОспаривается", + "Сковородино", + "Скопин", + "Славгород", + "Славск", + "Славянск-на-Кубани", + "Сланцы", + "Слободской", + "Слюдянка", + "Смоленск", + "Снежинск", + "Снежногорск", + "Собинка", + "Советск", + "Советск", + "Советск", + "Советская Гавань", + "Советский", + "Сокол", + "Солигалич", + "Соликамск", + "Солнечногорск", + "Соль-Илецк", + "Сольвычегодск", + "Сольцы", + "Сорочинск", + "Сорск", + "Сортавала", + "Сосенский", + "Сосновка", + "Сосновоборск", + "Сосновый Бор", + "Сосногорск", + "Сочи", + "Спас-Деменск", + "Спас-Клепики", + "Спасск", + "Спасск-Дальний", + "Спасск-Рязанский", + "Среднеколымск", + "Среднеуральск", + "Сретенск", + "Ставрополь", + "Старая Купавна", + "Старая Русса", + "Старица", + "Стародуб", + "Старый КрымОспаривается", + "Старый Оскол", + "Стерлитамак", + "Стрежевой", + "Строитель", + "Струнино", + "Ступино", + "Суворов", + "СудакОспаривается", + "Суджа", + "Судогда", + "Суздаль", + "Сунжа", + "Суоярви", + "Сураж", + "Сургут", + "Суровикино", + "Сурск", + "Сусуман", + "Сухиничи", + "Сухой Лог", + "Сызрань", + "Сыктывкар", + "Сысерть", + "Сычёвка", + "Сясьстрой", + "Тавда", + "Таганрог", + "Тайга", + "Тайшет", + "Талдом", + "Талица", + "Тамбов", + "Тара", + "Тарко-Сале", + "Таруса", + "Татарск", + "Таштагол", + "Тверь", + "Теберда", + "Тейково", + "Темников", + "Темрюк", + "Терек", + "Тетюши", + "Тимашёвск", + "Тихвин", + "Тихорецк", + "Тобольск", + "Тогучин", + "Тольятти", + "Томари", + "Томмот", + "Томск", + "Топки", + "Торжок", + "Торопец", + "Тосно", + "Тотьма", + "Трёхгорный", + "Троицк", + "Трубчевск", + "Туапсе", + "Туймазы", + "Тула", + "Тулун", + "Туран", + "Туринск", + "Тутаев", + "Тында", + "Тырныауз", + "Тюкалинск", + "Тюмень", + "Уварово", + "Углегорск", + "Углич", + "Удачный", + "Удомля", + "Ужур", + "Узловая", + "Улан-Удэ", + "Ульяновск", + "Унеча", + "Урай", + "Урень", + "Уржум", + "Урус-Мартан", + "Урюпинск", + "Усинск", + "Усмань", + "Усолье-Сибирское", + "Усолье", + "Уссурийск", + "Усть-Джегута", + "Усть-Илимск", + "Усть-Катав", + "Усть-Кут", + "Усть-Лабинск", + "Устюжна", + "Уфа", + "Ухта", + "Учалы", + "Уяр", + "Фатеж", + "ФеодосияОспаривается", + "Фокино", + "Фокино", + "Фролово", + "Фрязино", + "Фурманов", + "Хабаровск", + "Хадыженск", + "Ханты-Мансийск", + "Харабали", + "Харовск", + "Хасавюрт", + "Хвалынск", + "Хилок", + "Химки", + "Холм", + "Холмск", + "Хотьково", + "Цивильск", + "Цимлянск", + "Циолковский", + "Чадан", + "Чайковский", + "Чапаевск", + "Чаплыгин", + "Чебаркуль", + "Чебоксары", + "Чегем", + "Чекалин", + "Челябинск", + "Чердынь", + "Черемхово", + "Черепаново", + "Череповец", + "Черкесск", + "Чёрмоз", + "Черноголовка", + "Черногорск", + "Чернушка", + "Черняховск", + "Чехов", + "Чистополь", + "Чита", + "Чкаловск", + "Чудово", + "Чулым", + "Чусовой", + "Чухлома", + "Шагонар", + "Шадринск", + "Шали", + "Шарыпово", + "Шарья", + "Шатура", + "Шахты", + "Шахунья", + "Шацк", + "Шебекино", + "Шелехов", + "Шенкурск", + "Шилка", + "Шимановск", + "Шиханы", + "Шлиссельбург", + "Шумерля", + "Шумиха", + "Шуя", + "Щёкино", + "ЩёлкиноОспаривается", + "Щёлково", + "Щигры", + "Щучье", + "Электрогорск", + "Электросталь", + "Электроугли", + "Элиста", + "Энгельс", + "Эртиль", + "Югорск", + "Южа", + "Южно-Сахалинск", + "Южно-Сухокумск", + "Южноуральск", + "Юрга", + "Юрьев-Польский", + "Юрьевец", + "Юрюзань", + "Юхнов", + "Ядрин", + "Якутск", + "ЯлтаОспаривается", + "Ялуторовск", + "Янаул", + "Яранск", + "Яровое", + "Ярославль", + "Ярцево", + "Ясногорск", + "Ясный", + "Яхрома", +]; diff --git a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart new file mode 100644 index 00000000..4d06c950 --- /dev/null +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart @@ -0,0 +1,57 @@ +import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/core/token_storage.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; +import 'package:eatvio_app/features/registration/repositories/registration_repository.dart'; +import 'package:go_router/go_router.dart'; + +class RegistrationCubit extends Cubit { + final RegistrationRepository registrationRepository; + + RegistrationCubit({required this.registrationRepository}) + : super( + RegistrationState( + sheet: UserRegistrationSheet( + name: '', + firstName: '', + lastName: '', + email: '', + password: '', + passwordConfirmation: '', + birthdate: DateTime.now().toString(), + gender: '', + country: '', + city: '', + lang: 'Русский', + weight: 0, + height: 0, + chestCircumference: 0, + waistCircumference: 0, + hipCircumference: 0, + bloodPressureUp: 0, + bloodPressureDown: 0, + hasHypo: 0, + hasHyper: 0, + aboutAllergy: '', + aboutTakingPils: '', + aboutSportHobbies: '', + favoriteFoods: '', + unfavoriteFoods: '', + additionalInfo: '', + ), + ), + ); + + updateSheet(UserRegistrationSheet sheet) => emit(RegistrationState(sheet: sheet)); + + Future tryRegistration() async { + try { + final token = await registrationRepository.tryRegister(state.sheet); + await TokenStorage.saveTokenInStorage(token); + AppRouter.navigatorKey.currentContext?.go('/my-profile-screen'); + } catch (e) { + rethrow; + } + } +} diff --git a/lib/features/registration/presentation/bloc/registration_cubit/registration_state.dart b/lib/features/registration/presentation/bloc/registration_cubit/registration_state.dart new file mode 100644 index 00000000..d1e20906 --- /dev/null +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_state.dart @@ -0,0 +1,11 @@ +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'registration_state.freezed.dart'; + +@freezed +class RegistrationState with _$RegistrationState { + const factory RegistrationState({ + required UserRegistrationSheet sheet, + }) = _RegistrationState; +} diff --git a/lib/features/registration/presentation/bloc/registration_cubit/registration_state.freezed.dart b/lib/features/registration/presentation/bloc/registration_cubit/registration_state.freezed.dart new file mode 100644 index 00000000..dcb49236 --- /dev/null +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_state.freezed.dart @@ -0,0 +1,147 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'registration_state.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$RegistrationState { + UserRegistrationSheet get sheet => throw _privateConstructorUsedError; + + @JsonKey(ignore: true) + $RegistrationStateCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $RegistrationStateCopyWith<$Res> { + factory $RegistrationStateCopyWith( + RegistrationState value, $Res Function(RegistrationState) then) = + _$RegistrationStateCopyWithImpl<$Res, RegistrationState>; + @useResult + $Res call({UserRegistrationSheet sheet}); + + $UserRegistrationSheetCopyWith<$Res> get sheet; +} + +/// @nodoc +class _$RegistrationStateCopyWithImpl<$Res, $Val extends RegistrationState> + implements $RegistrationStateCopyWith<$Res> { + _$RegistrationStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? sheet = null, + }) { + return _then(_value.copyWith( + sheet: null == sheet + ? _value.sheet + : sheet // ignore: cast_nullable_to_non_nullable + as UserRegistrationSheet, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $UserRegistrationSheetCopyWith<$Res> get sheet { + return $UserRegistrationSheetCopyWith<$Res>(_value.sheet, (value) { + return _then(_value.copyWith(sheet: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$RegistrationStateImplCopyWith<$Res> + implements $RegistrationStateCopyWith<$Res> { + factory _$$RegistrationStateImplCopyWith(_$RegistrationStateImpl value, + $Res Function(_$RegistrationStateImpl) then) = + __$$RegistrationStateImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({UserRegistrationSheet sheet}); + + @override + $UserRegistrationSheetCopyWith<$Res> get sheet; +} + +/// @nodoc +class __$$RegistrationStateImplCopyWithImpl<$Res> + extends _$RegistrationStateCopyWithImpl<$Res, _$RegistrationStateImpl> + implements _$$RegistrationStateImplCopyWith<$Res> { + __$$RegistrationStateImplCopyWithImpl(_$RegistrationStateImpl _value, + $Res Function(_$RegistrationStateImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? sheet = null, + }) { + return _then(_$RegistrationStateImpl( + sheet: null == sheet + ? _value.sheet + : sheet // ignore: cast_nullable_to_non_nullable + as UserRegistrationSheet, + )); + } +} + +/// @nodoc + +class _$RegistrationStateImpl implements _RegistrationState { + const _$RegistrationStateImpl({required this.sheet}); + + @override + final UserRegistrationSheet sheet; + + @override + String toString() { + return 'RegistrationState(sheet: $sheet)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$RegistrationStateImpl && + (identical(other.sheet, sheet) || other.sheet == sheet)); + } + + @override + int get hashCode => Object.hash(runtimeType, sheet); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => + __$$RegistrationStateImplCopyWithImpl<_$RegistrationStateImpl>( + this, _$identity); +} + +abstract class _RegistrationState implements RegistrationState { + const factory _RegistrationState( + {required final UserRegistrationSheet sheet}) = _$RegistrationStateImpl; + + @override + UserRegistrationSheet get sheet; + @override + @JsonKey(ignore: true) + _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/registration/presentation/pages/additional_information_screen.dart b/lib/features/registration/presentation/pages/additional_information_screen.dart new file mode 100644 index 00000000..b1838fdd --- /dev/null +++ b/lib/features/registration/presentation/pages/additional_information_screen.dart @@ -0,0 +1,61 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:eatvio_app/widgets/custom_text_form_field.dart'; +import 'package:flutter/material.dart'; + +class AdditionalInformationScreen extends StatefulWidget { + final UserRegistrationSheet sheet; + + const AdditionalInformationScreen({super.key, required this.sheet}); + + @override + State createState() => _AdditionalInformationScreenState(); +} + +class _AdditionalInformationScreenState extends State { + final editTextController = TextEditingController(); + + @override + void initState() { + super.initState(); + editTextController.text = widget.sheet.additionalInfo; + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: Container( + width: double.maxFinite, + padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), + child: Column( + children: [ + Container( + width: 294.h, + margin: EdgeInsets.only(left: 24.h, right: 23.h), + child: Text( + "enter_additional_information".tr, + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: CustomTextStyles.titleMediumSegoeUI, + ), + ), + SizedBox(height: 10.v), + CustomTextFormField( + controller: editTextController, + hintText: "У меня крепкое здоровье, но последнее время часто утомляюсь, однако, это мне не мешает радоваться жизни", + textInputAction: TextInputAction.done, + maxLines: 8, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(additionalInfo: newValue)); + }, + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/registration/presentation/pages/allergies_screen.dart b/lib/features/registration/presentation/pages/allergies_screen.dart new file mode 100644 index 00000000..3261c92f --- /dev/null +++ b/lib/features/registration/presentation/pages/allergies_screen.dart @@ -0,0 +1,53 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:eatvio_app/widgets/custom_text_form_field.dart'; +import 'package:flutter/material.dart'; + +class AllergiesScreen extends StatefulWidget { + final UserRegistrationSheet sheet; + + const AllergiesScreen({super.key, required this.sheet}); + + @override + State createState() => _AllergiesScreenState(); +} + +class _AllergiesScreenState extends State { + final enterInformationController = TextEditingController(); + + @override + void initState() { + super.initState(); + enterInformationController.text = widget.sheet.aboutAllergy; + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: Container( + width: double.maxFinite, + padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), + child: Column( + children: [ + Text("allergies_presence".tr, style: theme.textTheme.headlineSmall), + SizedBox(height: 22.v), + Text("fill_in_information".tr, style: CustomTextStyles.titleMediumSegoeUI), + SizedBox(height: 2.v), + CustomTextFormField( + controller: enterInformationController, + hintText: "enter_information".tr, + textInputAction: TextInputAction.done, + maxLines: 8, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(aboutAllergy: newValue)); + }, + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/registration/presentation/pages/blood_pressure_screen.dart b/lib/features/registration/presentation/pages/blood_pressure_screen.dart new file mode 100644 index 00000000..ef69278b --- /dev/null +++ b/lib/features/registration/presentation/pages/blood_pressure_screen.dart @@ -0,0 +1,158 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:eatvio_app/widgets/custom_drop_down.dart'; +import 'package:eatvio_app/widgets/custom_text_form_field.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +class BloodPressureScreen extends StatefulWidget { + final UserRegistrationSheet sheet; + + const BloodPressureScreen({super.key, required this.sheet}); + + @override + State createState() => _BloodPressureScreenState(); +} + +class _BloodPressureScreenState extends State { + final List selectionPopupList = [ + SelectionPopupModel( + id: 1, + title: "Да", + ), + SelectionPopupModel( + id: 0, + title: "Нет", + ), + ]; + + late SelectionPopupModel selectedPopupHypo; + late SelectionPopupModel selectedPopupHyper; + + final digitsOnly = FilteringTextInputFormatter.digitsOnly; + final upPressureController = TextEditingController(); + final downPressureController = TextEditingController(); + + @override + void initState() { + super.initState(); + selectedPopupHypo = selectionPopupList[1]; + selectedPopupHyper = selectionPopupList[1]; + upPressureController.text = widget.sheet.bloodPressureUp.toString(); + downPressureController.text = widget.sheet.bloodPressureDown.toString(); + widget.sheet.hasHyper == '1' ? selectedPopupHyper = selectionPopupList[0] : selectedPopupHyper = selectionPopupList[1]; + widget.sheet.hasHypo == '1' ? selectedPopupHypo = selectionPopupList[0] : selectedPopupHypo = selectionPopupList[1]; + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: Container( + width: double.maxFinite, + padding: EdgeInsets.symmetric(horizontal: 12.h, vertical: 9.v), + child: Column( + children: [ + SizedBox( + width: 224.h, + child: Text( + "your_blood_pressure".tr, + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: theme.textTheme.headlineSmall, + ), + ), + SizedBox(height: 21.v), + Container( + margin: EdgeInsets.only(right: 1.h), + padding: EdgeInsets.symmetric(horizontal: 3.h), + child: Column( + children: [ + Text("up_pressure".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 2.v), + CustomTextFormField( + inputFormatters: [digitsOnly], + controller: upPressureController, + hintText: "90".tr, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(bloodPressureUp: int.parse(newValue))); + }, + ), + ], + ), + ), + SizedBox(height: 21.v), + Container( + margin: EdgeInsets.only(right: 1.h), + padding: EdgeInsets.symmetric(horizontal: 3.h), + child: Column( + children: [ + Text("down_pressure".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 2.v), + CustomTextFormField( + inputFormatters: [digitsOnly], + controller: downPressureController, + hintText: "90".tr, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(bloodPressureDown: int.parse(newValue))); + }, + ), + ], + ), + ), + SizedBox(height: 22.v), + Text("do_you_have_hypotension_tendency".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 2.v), + Padding( + padding: EdgeInsets.symmetric(horizontal: 4.h), + child: CustomDropDown( + icon: Container( + margin: EdgeInsets.fromLTRB(30.h, 11.v, 13.h, 11.v), + decoration: BoxDecoration(borderRadius: BorderRadius.circular(1.h)), + child: CustomImageView(imagePath: ImageConstant.imgFavorite, height: 12.adaptSize, width: 12.adaptSize), + ), + hintText: "Не выбрано".tr, + items: selectionPopupList, + value: selectedPopupHypo, + onChanged: (newPopup) { + setState(() { + selectedPopupHypo = newPopup; + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(hasHypo: selectedPopupHypo.id!)); + }); + }, + ), + ), + SizedBox(height: 22.v), + Text("do_you_have_hypertension_tendency".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 2.v), + Padding( + padding: EdgeInsets.symmetric(horizontal: 4.h), + child: CustomDropDown( + icon: Container( + margin: EdgeInsets.fromLTRB(30.h, 11.v, 13.h, 11.v), + decoration: BoxDecoration(borderRadius: BorderRadius.circular(1.h)), + child: CustomImageView(imagePath: ImageConstant.imgFavorite, height: 12.adaptSize, width: 12.adaptSize), + ), + hintText: "Не выбрано".tr, + items: selectionPopupList, + value: selectedPopupHyper, + onChanged: (newPopup) { + setState(() { + selectedPopupHyper = newPopup; + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(hasHyper: selectedPopupHyper.id!)); + }); + }, + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/registration/presentation/pages/body_circumferences_screen.dart b/lib/features/registration/presentation/pages/body_circumferences_screen.dart new file mode 100644 index 00000000..c5370843 --- /dev/null +++ b/lib/features/registration/presentation/pages/body_circumferences_screen.dart @@ -0,0 +1,87 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:eatvio_app/widgets/custom_text_form_field.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +class BodyCircumferencesScreen extends StatefulWidget { + final UserRegistrationSheet sheet; + + const BodyCircumferencesScreen({super.key, required this.sheet}); + + @override + State createState() => _BodyCircumferencesScreenState(); +} + +class _BodyCircumferencesScreenState extends State { + final digitsOnly = FilteringTextInputFormatter.digitsOnly; + final chestCircumferenceController = TextEditingController(); + final waistCircumferenceController = TextEditingController(); + final hipCircumferenceController = TextEditingController(); + + @override + void initState() { + super.initState(); + if (widget.sheet.chestCircumference != 0) chestCircumferenceController.text = widget.sheet.chestCircumference.toString(); + if (widget.sheet.waistCircumference != 0) waistCircumferenceController.text = widget.sheet.waistCircumference.toString(); + if (widget.sheet.hipCircumference != 0) hipCircumferenceController.text = widget.sheet.hipCircumference.toString(); + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: Container( + width: double.maxFinite, + padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), + child: Column( + children: [ + Text("initial_measurements".tr, style: theme.textTheme.headlineSmall), + SizedBox(height: 16.v), + Column( + children: [ + Text("chest_circumference".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 3.v), + CustomTextFormField( + inputFormatters: [digitsOnly], + controller: chestCircumferenceController, + hintText: "90".tr, + onChanged: (value) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(chestCircumference: int.parse(value))); + }, + ), + ], + ), + SizedBox(height: 19.v), + Text("waist_circumference".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 5.v), + CustomTextFormField( + inputFormatters: [digitsOnly], + controller: waistCircumferenceController, + hintText: "60".tr, + onChanged: (value) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(waistCircumference: int.parse(value))); + }, + ), + SizedBox(height: 21.v), + Text("hip_circumference".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 3.v), + CustomTextFormField( + inputFormatters: [digitsOnly], + controller: hipCircumferenceController, + hintText: "90".tr, + textInputAction: TextInputAction.done, + onChanged: (value) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(hipCircumference: int.parse(value))); + }, + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/registration/presentation/pages/city_of_living_screen.dart b/lib/features/registration/presentation/pages/city_of_living_screen.dart new file mode 100644 index 00000000..0372d8b5 --- /dev/null +++ b/lib/features/registration/presentation/pages/city_of_living_screen.dart @@ -0,0 +1,88 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/consts/cities_list.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:eatvio_app/widgets/custom_drop_down.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_typeahead/flutter_typeahead.dart'; + +class CityOfLivingScreen extends StatefulWidget { + final UserRegistrationSheet sheet; + + const CityOfLivingScreen({super.key, required this.sheet}); + + @override + State createState() => _CityOfLivingScreenState(); +} + +class _CityOfLivingScreenState extends State { + final dropdownItemList = [ + SelectionPopupModel(id: 1, title: "Россия", isSelected: true), + ]; + + late SelectionPopupModel selectedItem; + final cityController = TextEditingController(); + + @override + void initState() { + super.initState(); + selectedItem = dropdownItemList[0]; + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(country: selectedItem.title)); + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: Container( + width: double.maxFinite, + padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), + child: Column( + children: [ + Text("place_of_living".tr, style: theme.textTheme.headlineSmall), + SizedBox(height: 39.v), + Text("country".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 2.v), + CustomDropDown( + icon: Container( + margin: EdgeInsets.fromLTRB(30.h, 11.v, 17.h, 11.v), + decoration: BoxDecoration(borderRadius: BorderRadius.circular(1.h)), + child: CustomImageView(imagePath: ImageConstant.imgFavorite, height: 12.adaptSize, width: 12.adaptSize), + ), + hintText: "Не выбрано".tr, + items: dropdownItemList, + value: selectedItem, + onChanged: (newValue) { + setState(() { + selectedItem = newValue; + }); + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(country: newValue.title)); + }, + ), + SizedBox(height: 22.v), + Text("Населенный пункт", style: theme.textTheme.bodyLarge), + SizedBox(height: 2.v), + TypeAheadField( + controller: cityController, + itemBuilder: (BuildContext context, String item) { + return Text(item); + }, + onSelected: (item) { + setState(() { + cityController.text = item; + }); + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(city: item)); + }, + suggestionsCallback: (query) { + return citiesList.where((country) => country.toLowerCase().contains(query.toLowerCase())).toList(); + }, + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/registration/presentation/pages/credentials_screen.dart b/lib/features/registration/presentation/pages/credentials_screen.dart new file mode 100644 index 00000000..3175b5c4 --- /dev/null +++ b/lib/features/registration/presentation/pages/credentials_screen.dart @@ -0,0 +1,95 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:eatvio_app/widgets/custom_text_form_field.dart'; +import 'package:flutter/material.dart'; + +class CredentialsScreen extends StatefulWidget { + final UserRegistrationSheet sheet; + + const CredentialsScreen({super.key, required this.sheet}); + + @override + State createState() => _CredentialsScreenState(); +} + +class _CredentialsScreenState extends State { + final emailController = TextEditingController(); + + final nameController = TextEditingController(); + + final passwordController = TextEditingController(); + + final passwordConfirmationController = TextEditingController(); + + @override + void initState() { + super.initState(); + emailController.text = widget.sheet.email; + nameController.text = widget.sheet.name; + passwordController.text = widget.sheet.password; + passwordConfirmationController.text = widget.sheet.passwordConfirmation; + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: Container( + width: double.maxFinite, + padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text("user_registration".tr, style: theme.textTheme.headlineSmall), + SizedBox(height: 16.v), + Text("email".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 3.v), + CustomTextFormField( + controller: emailController, + textInputAction: TextInputAction.done, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(email: newValue)); + }, + ), + SizedBox(height: 22.v), + Text("username".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 3.v), + CustomTextFormField( + controller: nameController, + textInputAction: TextInputAction.done, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(name: newValue)); + }, + ), + SizedBox(height: 19.v), + Text("password".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 5.v), + CustomTextFormField( + obscureText: true, + controller: passwordController, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(password: newValue)); + }, + ), + SizedBox(height: 21.v), + Text("password_confirmation".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 3.v), + CustomTextFormField( + obscureText: true, + controller: passwordConfirmationController, + textInputAction: TextInputAction.done, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(passwordConfirmation: newValue)); + }, + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/registration/presentation/pages/date_of_birth_screen.dart b/lib/features/registration/presentation/pages/date_of_birth_screen.dart new file mode 100644 index 00000000..54e1935d --- /dev/null +++ b/lib/features/registration/presentation/pages/date_of_birth_screen.dart @@ -0,0 +1,113 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:intl/intl.dart'; + +class DateOfBirthScreen extends StatefulWidget { + final UserRegistrationSheet sheet; + + const DateOfBirthScreen({super.key, required this.sheet}); + + @override + State createState() => _DateOfBirthScreenState(); +} + +class _DateOfBirthScreenState extends State { + late DateTime selectedDate; + + @override + void initState() { + super.initState(); + if (widget.sheet.birthdate.isNotEmpty) { + selectedDate = DateFormat('yyyy-mm-dd').parse(widget.sheet.birthdate); + } else { + selectedDate = DateTime.now(); + } + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: Container( + width: double.maxFinite, + padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), + child: Column( + children: [ + Text("date_of_birth".tr, style: theme.textTheme.headlineSmall), + const SizedBox(height: 32), + _buildDateInput(context), + ], + ), + ), + ); + } + + /// Section Widget + _buildDateInput(BuildContext context) { + return Container( + width: 343.h, + padding: EdgeInsets.symmetric(horizontal: 4.h, vertical: 1.v), + decoration: AppDecoration.outlineBlueA.copyWith(borderRadius: BorderRadiusStyle.circleBorder8), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CustomImageView(imagePath: ImageConstant.imgFavorite, height: 12.adaptSize, width: 12.adaptSize, radius: BorderRadius.circular(1.h)), + SizedBox(height: 6.v), + Align( + alignment: Alignment.center, + child: GestureDetector( + onTap: onTapCalendar(context), + child: Text('${selectedDate.day}.${selectedDate.month}.${selectedDate.year}', style: theme.textTheme.titleMedium), + ), + ), + SizedBox(height: 6.v), + ], + ), + ); + } + + onTapCalendar(BuildContext context) { + return () { + _showDialog( + CupertinoDatePicker( + initialDateTime: DateTime.now(), + mode: CupertinoDatePickerMode.date, + onDateTimeChanged: (DateTime newDateTime) { + setState(() { + selectedDate = newDateTime; + print(selectedDate); + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(birthdate: selectedDate.toString())); + }); + }, + ), + ); + }; + } + + void _showDialog(Widget child) { + showCupertinoModalPopup( + context: context, + builder: (BuildContext context) => Container( + height: 216, + padding: const EdgeInsets.only(top: 6.0), + // The Bottom margin is provided to align the popup above the system + // navigation bar. + margin: EdgeInsets.only( + bottom: MediaQuery.of(context).viewInsets.bottom, + ), + // Provide a background color for the popup. + color: CupertinoColors.systemBackground.resolveFrom(context), + // Use a SafeArea widget to avoid system overlaps. + child: SafeArea( + top: false, + child: child, + ), + ), + ); + } +} diff --git a/lib/features/registration/presentation/pages/favorite_foods_screen.dart b/lib/features/registration/presentation/pages/favorite_foods_screen.dart new file mode 100644 index 00000000..d17b5e11 --- /dev/null +++ b/lib/features/registration/presentation/pages/favorite_foods_screen.dart @@ -0,0 +1,77 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:eatvio_app/widgets/custom_text_form_field.dart'; +import 'package:flutter/material.dart'; + +class FavoriteFoodsScreen extends StatefulWidget { + final UserRegistrationSheet sheet; + + const FavoriteFoodsScreen({super.key, required this.sheet}); + + @override + State createState() => _FavoriteFoodsScreenState(); +} + +class _FavoriteFoodsScreenState extends State { + final favoriteFoodsController = TextEditingController(); + final unFavoriteFoodsController = TextEditingController(); + + @override + void initState() { + super.initState(); + favoriteFoodsController.text = widget.sheet.favoriteFoods; + unFavoriteFoodsController.text = widget.sheet.unfavoriteFoods; + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: Container( + width: double.maxFinite, + padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), + child: Column( + children: [ + Container( + width: 327.h, + margin: EdgeInsets.only(left: 8.h, right: 7.h), + child: Text( + "favorite_unfavorite_foods".tr, + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: theme.textTheme.headlineSmall, + ), + ), + SizedBox(height: 13.v), + Text("favorite_foods".tr, style: CustomTextStyles.titleMediumSegoeUI), + SizedBox(height: 2.v), + CustomTextFormField( + controller: favoriteFoodsController, + hintText: "enter_information".tr, + maxLines: 7, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(favoriteFoods: newValue)); + }, + ), + SizedBox(height: 12.v), + Text("unfavorite_foods".tr, style: CustomTextStyles.titleMediumSegoeUI), + SizedBox(height: 2.v), + CustomTextFormField( + controller: unFavoriteFoodsController, + hintText: "enter_information".tr, + textInputAction: TextInputAction.done, + maxLines: 7, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(unfavoriteFoods: newValue)); + }, + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/registration/presentation/pages/favorite_sports_screen.dart b/lib/features/registration/presentation/pages/favorite_sports_screen.dart new file mode 100644 index 00000000..55273ec7 --- /dev/null +++ b/lib/features/registration/presentation/pages/favorite_sports_screen.dart @@ -0,0 +1,55 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:eatvio_app/widgets/custom_text_form_field.dart'; +import 'package:flutter/material.dart'; + +class FavoriteSportsScreen extends StatefulWidget { + final UserRegistrationSheet sheet; + + const FavoriteSportsScreen({super.key, required this.sheet}); + + @override + State createState() => _FavoriteSportsScreenState(); +} + +class _FavoriteSportsScreenState extends State { + final enterInformationController = TextEditingController(); + + @override + void initState() { + super.initState(); + enterInformationController.text = widget.sheet.aboutSportHobbies; + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: Container( + width: double.maxFinite, + padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 5.v), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text("your_favorite_sports".tr, style: theme.textTheme.headlineSmall), + SizedBox(height: 22.v), + Text("fill_in_information".tr, style: CustomTextStyles.titleMediumSegoeUI), + SizedBox(height: 2.v), + CustomTextFormField( + controller: enterInformationController, + hintText: + "Я занимаюсь плаванием , почти каждый вечер прогулки на свежем воздухе, пару раз в месяц играю в волейбол. Стараюсь не сидеть на месте!", + textInputAction: TextInputAction.done, + maxLines: 8, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(aboutSportHobbies: newValue)); + }, + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/registration/presentation/pages/gender_screen.dart b/lib/features/registration/presentation/pages/gender_screen.dart new file mode 100644 index 00000000..62258260 --- /dev/null +++ b/lib/features/registration/presentation/pages/gender_screen.dart @@ -0,0 +1,79 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:flutter/material.dart'; + +class GenderScreen extends StatefulWidget { + final UserRegistrationSheet sheet; + + const GenderScreen({super.key, required this.sheet}); + + @override + State createState() => _GenderScreenState(); +} + +class _GenderScreenState extends State { + late String currentValue; + + @override + void initState() { + super.initState(); + currentValue = widget.sheet.gender; + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: Container( + width: double.maxFinite, + padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), + child: Column( + children: [ + Text("your_gender".tr, style: theme.textTheme.headlineSmall), + RadioListTile( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + title: Text('Мужской'), + value: 'male', + groupValue: currentValue, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(gender: 'male')); + setState(() { + currentValue = 'male'; + }); + }, + secondary: Image.asset( + 'assets/images/img_male.png', + width: 40, + height: 40, + ), + ), + RadioListTile( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + title: Text('Женский'), + value: 'female', + groupValue: currentValue, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(gender: 'female')); + setState(() { + currentValue = 'female'; + }); + }, + secondary: Image.asset( + 'assets/images/img_female.png', + width: 40, + height: 40, + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/registration/presentation/pages/height_screen.dart b/lib/features/registration/presentation/pages/height_screen.dart new file mode 100644 index 00000000..98fc71fa --- /dev/null +++ b/lib/features/registration/presentation/pages/height_screen.dart @@ -0,0 +1,67 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:eatvio_app/widgets/custom_text_form_field.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +class HeightScreen extends StatefulWidget { + final UserRegistrationSheet sheet; + + const HeightScreen({super.key, required this.sheet}); + + @override + State createState() => _HeightScreenState(); +} + +class _HeightScreenState extends State { + final heightController = TextEditingController(); + + @override + void initState() { + super.initState(); + if (widget.sheet.height != 0) heightController.text = widget.sheet.height.toString(); + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: Container( + width: double.maxFinite, + padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), + child: Column( + children: [ + Text( + "height_measurements".tr, + style: theme.textTheme.headlineSmall, + ), + SizedBox(height: 16.v), + Column( + children: [ + Text( + "your_height".tr, + style: theme.textTheme.bodyLarge, + ), + SizedBox(height: 4.v), + CustomTextFormField( + width: 150.h, + textInputAction: TextInputAction.done, + controller: heightController, + keyboardType: TextInputType.number, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, + ], + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(height: int.parse(newValue))); + }, + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/registration/presentation/pages/language_select_screen.dart b/lib/features/registration/presentation/pages/language_select_screen.dart new file mode 100644 index 00000000..c770c0c7 --- /dev/null +++ b/lib/features/registration/presentation/pages/language_select_screen.dart @@ -0,0 +1,63 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:eatvio_app/widgets/custom_drop_down.dart'; +import 'package:flutter/material.dart'; + +class LanguageSelectScreen extends StatefulWidget { + final UserRegistrationSheet sheet; + + const LanguageSelectScreen({required this.sheet, super.key}); + + @override + State createState() => _LanguageSelectScreenState(); +} + +class _LanguageSelectScreenState extends State { + final List dropdownItemList = [ + SelectionPopupModel(id: 1, title: "Русский", isSelected: true), + ]; + + SelectionPopupModel? value; + + @override + void initState() { + super.initState(); + if (widget.sheet.lang.isNotEmpty) { + value = dropdownItemList.first; + } + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: Column( + children: [ + Container( + width: 262.h, + margin: EdgeInsets.only(left: 41.h, right: 39.h), + child: Text( + "preferred_language".tr, + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: theme.textTheme.headlineSmall, + ), + ), + const SizedBox(height: 32), + CustomDropDown( + value: value, + hintText: "Не выбрано".tr, + items: dropdownItemList, + onChanged: (SelectionPopupModel newValue) => setState(() { + value = newValue; + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(lang: value!.title)); + }), + ), + ], + ), + ); + } +} diff --git a/lib/features/registration/presentation/pages/medicine_intake_screen.dart b/lib/features/registration/presentation/pages/medicine_intake_screen.dart new file mode 100644 index 00000000..d6ea9fbb --- /dev/null +++ b/lib/features/registration/presentation/pages/medicine_intake_screen.dart @@ -0,0 +1,63 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:eatvio_app/widgets/custom_text_form_field.dart'; +import 'package:flutter/material.dart'; + +class MedicineIntakeScreen extends StatefulWidget { + final UserRegistrationSheet sheet; + + const MedicineIntakeScreen({super.key, required this.sheet}); + + @override + State createState() => _MedicineIntakeScreenState(); +} + +class _MedicineIntakeScreenState extends State { + final enterInformationController = TextEditingController(); + + @override + void initState() { + super.initState(); + enterInformationController.text = widget.sheet.aboutTakingPils; + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: Container( + width: double.maxFinite, + padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), + child: Column( + children: [ + Container( + width: 271.h, + margin: EdgeInsets.only(left: 35.h, right: 36.h), + child: Text( + "do_you_take_pills".tr, + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: theme.textTheme.headlineSmall, + ), + ), + SizedBox(height: 16.v), + Text("fill_in_information".tr, style: CustomTextStyles.titleMediumSegoeUI), + SizedBox(height: 2.v), + CustomTextFormField( + controller: enterInformationController, + hintText: "enter_information".tr, + textInputAction: TextInputAction.done, + maxLines: 8, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(aboutTakingPils: newValue)); + }, + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/registration/presentation/pages/name_screen.dart b/lib/features/registration/presentation/pages/name_screen.dart new file mode 100644 index 00000000..2f1e4c5f --- /dev/null +++ b/lib/features/registration/presentation/pages/name_screen.dart @@ -0,0 +1,63 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:eatvio_app/widgets/custom_text_form_field.dart'; +import 'package:flutter/material.dart'; + +class NameScreen extends StatefulWidget { + final UserRegistrationSheet sheet; + + const NameScreen({required this.sheet, super.key}); + + @override + State createState() => _NameScreenState(); +} + +class _NameScreenState extends State { + final firstNameController = TextEditingController(); + final lastNameController = TextEditingController(); + + @override + void initState() { + super.initState(); + firstNameController.text = widget.sheet.firstName; + lastNameController.text = widget.sheet.lastName; + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: Container( + width: double.maxFinite, + padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), + child: Column( + children: [ + Text("what_is_your_name".tr, style: theme.textTheme.headlineSmall), + SizedBox(height: 16.v), + Text("first_name".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 3.v), + CustomTextFormField( + controller: firstNameController, + textInputAction: TextInputAction.done, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(firstName: newValue)); + }, + ), + SizedBox(height: 19.v), + Text("last_name".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 5.v), + CustomTextFormField( + controller: lastNameController, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(lastName: newValue)); + }, + ) + ], + ), + ), + ); + } +} diff --git a/lib/features/registration/presentation/pages/registration_screen.dart b/lib/features/registration/presentation/pages/registration_screen.dart new file mode 100644 index 00000000..93a5eae0 --- /dev/null +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -0,0 +1,390 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/additional_information_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/allergies_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/blood_pressure_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/body_circumferences_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/city_of_living_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/credentials_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/date_of_birth_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/favorite_foods_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/favorite_sports_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/gender_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/height_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/language_select_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/medicine_intake_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/name_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/weight_screen.dart'; +import 'package:eatvio_app/locator_service.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; +import 'package:validators/validators.dart'; + +class RegistrationScreen extends StatefulWidget { + const RegistrationScreen({super.key}); + + @override + State createState() => _RegistrationScreenState(); +} + +class _RegistrationScreenState extends State { + double progressValue = 1 / 15; + int step = 1; + final pageController = PageController(); + final RegistrationCubit registrationCubit = sl(); + + _showPopDialog() { + showDialog( + context: context, + builder: (context) => CupertinoAlertDialog( + content: Text('Отменить регистрацию? Заполненные данные не будут сохранены.'), + actions: [ + CupertinoDialogAction( + onPressed: () { + Navigator.pop(context); + GoRouter.of(context).pop(); + }, + child: Text('Да'), + ), + CupertinoDialogAction( + onPressed: () { + Navigator.pop(context); + }, + isDefaultAction: true, + child: Text('Нет'), + ) + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + return BlocProvider( + create: (BuildContext context) => registrationCubit, + child: BlocBuilder( + builder: (BuildContext context, RegistrationState state) { + return PopScope( + canPop: false, + onPopInvoked: (_) => _showPopDialog(), + child: Scaffold( + floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, + floatingActionButton: Row( + children: [ + Container( + height: 48, + width: MediaQuery.of(context).size.width * 0.2, + padding: EdgeInsets.only(left: 16, right: 4), + child: FloatingActionButton.extended( + heroTag: 'backButtonRegistration', + highlightElevation: 0, + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + backgroundColor: Color(0xFFEAF2FD), + onPressed: () { + if (pageController.page == 0) _showPopDialog(); + setState(() { + pageController.previousPage( + duration: const Duration(milliseconds: 350), + curve: Curves.easeInOut, + ); + }); + }, + label: Icon( + Icons.arrow_back_ios_new_rounded, + color: appTheme.blueA400, + ), + ), + ), + Container( + height: 48, + width: MediaQuery.of(context).size.width * 0.8, + padding: EdgeInsets.only(left: 4, right: 16), + child: FloatingActionButton.extended( + heroTag: 'nextButtonRegistration', + highlightElevation: 0, + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + backgroundColor: appTheme.blueA400, + onPressed: () async { + if (await canGoNext(state)) { + setState(() { + pageController.nextPage( + duration: const Duration(milliseconds: 350), + curve: Curves.easeInOut, + ); + }); + } + }, + label: Text( + 'Продолжить', + style: theme.textTheme.titleSmall, + ), + ), + ), + ], + ), + appBar: AppBar( + automaticallyImplyLeading: true, + centerTitle: true, + title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio), + actions: [ + Padding( + padding: const EdgeInsets.only(right: 16), + child: Text('шаг $step из 15'), + ), + ], + bottom: PreferredSize( + preferredSize: Size(MediaQuery.of(context).size.width, 32), + child: Padding( + padding: const EdgeInsets.all(16), + child: TweenAnimationBuilder( + duration: const Duration(milliseconds: 350), + curve: Curves.easeInOut, + tween: Tween( + begin: 0, + end: progressValue, + ), + builder: (context, value, _) => LinearProgressIndicator( + value: value, + borderRadius: BorderRadius.circular(16), + minHeight: 8, + backgroundColor: Colors.grey.shade100, + valueColor: AlwaysStoppedAnimation(appTheme.blueA400), + ), + ), + ), + ), + ), + body: PageView( + physics: NeverScrollableScrollPhysics(), + controller: pageController, + onPageChanged: (index) { + setState(() { + step = index + 1; + progressValue = step / 15; + }); + }, + children: [ + LanguageSelectScreen(sheet: state.sheet), + CredentialsScreen(sheet: state.sheet), + NameScreen(sheet: state.sheet), + GenderScreen(sheet: state.sheet), + DateOfBirthScreen(sheet: state.sheet), + CityOfLivingScreen(sheet: state.sheet), // todo refactor + BodyCircumferencesScreen(sheet: state.sheet), + WeightScreen(sheet: state.sheet), + HeightScreen(sheet: state.sheet), + BloodPressureScreen(sheet: state.sheet), + AllergiesScreen(sheet: state.sheet), + MedicineIntakeScreen(sheet: state.sheet), + FavoriteSportsScreen(sheet: state.sheet), + FavoriteFoodsScreen(sheet: state.sheet), + AdditionalInformationScreen(sheet: state.sheet), + ], + ), + ), + ); + }, + ), + ); + } + + Future canGoNext(state) async { + switch (step) { + case 2: + List errors = validateCredentialsFields(state.sheet.email, state.sheet.name, state.sheet.password, state.sheet.passwordConfirmation); + if (errors.isEmpty) { + return true; + } else { + String errorMessage = ''; + + for (var error in errors) { + errorMessage += error + '\n\n'; + } + + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text('Ошибка'), + content: Text(errorMessage), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text('OK'), + ), + ], + ), + ); + return false; + } + case 3: + List errors = validateNameFields( + state.sheet.firstName.toString(), + state.sheet.lastName.toString(), + ); + if (errors.isEmpty) { + return true; + } else { + String errorMessage = ''; + + for (var error in errors) { + errorMessage += error + '\n\n'; + } + + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text('Ошибка'), + content: Text(errorMessage), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text('OK'), + ), + ], + ), + ); + return false; + } + case 7: + List errors = validateCircumferencesFields( + state.sheet.chestCircumference.toString(), + state.sheet.waistCircumference.toString(), + state.sheet.hipCircumference.toString(), + ); + if (errors.isEmpty) { + return true; + } else { + String errorMessage = ''; + + for (var error in errors) { + errorMessage += error + '\n\n'; + } + + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text('Ошибка'), + content: Text(errorMessage), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text('OK'), + ), + ], + ), + ); + return false; + } + case 15: + try { + showDialog( + barrierDismissible: false, + useSafeArea: false, + context: context, + builder: (context) => PopScope( + canPop: false, + child: Center( + child: CircularProgressIndicator(), + ), + ), + ); + await registrationCubit.tryRegistration(); + Navigator.pop(context); + } catch (e) { + Navigator.pop(context); + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text('Ошибка при попытке регистрации'), + ), + ); + } + return false; + default: + return true; + } + } + + List validateCircumferencesFields( + String chestCircumference, + String waistCircumference, + String hipCircumference, + ) { + List errors = []; + + if (chestCircumference.isEmpty | waistCircumference.isEmpty | hipCircumference.isEmpty) { + errors.add('circumference_empty'.tr); + } + + if (![chestCircumference, waistCircumference, hipCircumference].every((circumference) => int.tryParse(circumference) != null)) { + errors.add('circumference_is_not_a_number'.tr); + } + + return errors; + } + + List validateCredentialsFields(String email, String name, String password, String passwordConfirmation) { + List errors = []; + + if (!isEmail(email)) { + errors.add('email_invalid'.tr); + } + + if (email.isEmpty) { + errors.add('email_empty'.tr); + } + + if (name.length < 6) { + errors.add('name_short'.tr); + } + + if (name.isEmpty) { + errors.add('name_empty'.tr); + } + + if (password.isEmpty) { + errors.add('name_empty'.tr); + } + + if (password.length < 6) { + errors.add('password_short'.tr); + } + + if (password != passwordConfirmation) { + errors.add('password_confirmation_mismatch'.tr); + } + + return errors; + } + + List validateNameFields(String firstName, String lastName) { + List errors = []; + + if (firstName.isEmpty) { + errors.add('First name cannot be empty'); + } + + if (firstName.length < 1) { + errors.add('First name is too short'); + } + + if (lastName.isEmpty) { + errors.add('Last name cannot be empty'); + } + + if (lastName.length < 1) { + errors.add('Last name is too short'); + } + + return errors; + } +} diff --git a/lib/features/registration/presentation/pages/weight_screen.dart b/lib/features/registration/presentation/pages/weight_screen.dart new file mode 100644 index 00000000..855593e5 --- /dev/null +++ b/lib/features/registration/presentation/pages/weight_screen.dart @@ -0,0 +1,67 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:eatvio_app/widgets/custom_text_form_field.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +class WeightScreen extends StatefulWidget { + final UserRegistrationSheet sheet; + + const WeightScreen({super.key, required this.sheet}); + + @override + State createState() => _WeightScreenState(); +} + +class _WeightScreenState extends State { + final weightController = TextEditingController(); + + @override + void initState() { + super.initState(); + if (widget.sheet.weight != 0) weightController.text = widget.sheet.weight.toString(); + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: Container( + width: double.maxFinite, + padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), + child: Column( + children: [ + Text( + "weight_measurements".tr, + style: theme.textTheme.headlineSmall, + ), + SizedBox(height: 16.v), + Column( + children: [ + Text( + "your_weight".tr, + style: theme.textTheme.bodyLarge, + ), + SizedBox(height: 4.v), + CustomTextFormField( + width: 150.h, + textInputAction: TextInputAction.done, + controller: weightController, + keyboardType: TextInputType.number, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, + ], + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(weight: int.parse(newValue))); + }, + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/registration/repositories/registration_repository.dart b/lib/features/registration/repositories/registration_repository.dart new file mode 100644 index 00000000..aa388801 --- /dev/null +++ b/lib/features/registration/repositories/registration_repository.dart @@ -0,0 +1,16 @@ +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/services/registration_service.dart'; + +class RegistrationRepository { + final RegistrationService registrationService; + + RegistrationRepository({required this.registrationService}); + + Future tryRegister(UserRegistrationSheet sheet) async { + try { + return (await registrationService.register(sheet: sheet.toJson()))['token']!; + } catch (e) { + rethrow; + } + } +} diff --git a/lib/features/registration/services/registration_service.dart b/lib/features/registration/services/registration_service.dart new file mode 100644 index 00000000..fefca6ad --- /dev/null +++ b/lib/features/registration/services/registration_service.dart @@ -0,0 +1,14 @@ +import 'package:dio/dio.dart'; +import 'package:retrofit/retrofit.dart'; + +part 'registration_service.g.dart'; + +@RestApi() +abstract class RegistrationService { + factory RegistrationService(Dio dio, {String baseUrl}) = _RegistrationService; + + @POST('/api/register') + Future> register({ + @Body() required Map sheet, + }); +} diff --git a/lib/features/registration/services/registration_service.g.dart b/lib/features/registration/services/registration_service.g.dart new file mode 100644 index 00000000..269d16cc --- /dev/null +++ b/lib/features/registration/services/registration_service.g.dart @@ -0,0 +1,79 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'registration_service.dart'; + +// ************************************************************************** +// RetrofitGenerator +// ************************************************************************** + +// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers,unused_element + +class _RegistrationService implements RegistrationService { + _RegistrationService( + this._dio, { + this.baseUrl, + }); + + final Dio _dio; + + String? baseUrl; + + @override + Future> register( + {required Map sheet}) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + final _data = {}; + _data.addAll(sheet); + final _result = await _dio.fetch>( + _setStreamType>(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/api/register', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = _result.data!.cast(); + return _value; + } + + RequestOptions _setStreamType(RequestOptions requestOptions) { + if (T != dynamic && + !(requestOptions.responseType == ResponseType.bytes || + requestOptions.responseType == ResponseType.stream)) { + if (T == String) { + requestOptions.responseType = ResponseType.plain; + } else { + requestOptions.responseType = ResponseType.json; + } + } + return requestOptions; + } + + String _combineBaseUrls( + String dioBaseUrl, + String? baseUrl, + ) { + if (baseUrl == null || baseUrl.trim().isEmpty) { + return dioBaseUrl; + } + + final url = Uri.parse(baseUrl); + + if (url.isAbsolute) { + return url.toString(); + } + + return Uri.parse(dioBaseUrl).resolveUri(url).toString(); + } +} diff --git a/lib/localization/app_localization.dart b/lib/localization/app_localization.dart index 5d003fca..0c0b2568 100644 --- a/lib/localization/app_localization.dart +++ b/lib/localization/app_localization.dart @@ -1,9 +1,9 @@ import 'package:eatvio_app/app_router.dart'; - -import 'ru/ru_translations.dart'; +import 'package:flutter/cupertino.dart'; //import 'en_us/en_us_translations.dart'; import 'package:flutter/foundation.dart'; -import 'package:flutter/cupertino.dart'; + +import 'ru/ru_translations.dart'; class AppLocalization { AppLocalization(this.locale); @@ -23,24 +23,24 @@ class AppLocalization { return Localizations.of(context, AppLocalization)!; } else { // Обработка ситуации, когда context равен null - return AppLocalization(Locale( - 'ru', - '', - ),); // Возвращаем дефолтное значение или обработку ошибки + return AppLocalization( + Locale( + 'ru', + '', + ), + ); // Возвращаем дефолтное значение или обработку ошибки } } static List languages() => _localizedValues.keys.toList(); - String getString(String text) => - _localizedValues[locale.languageCode]![text] ?? text; + String getString(String text) => _localizedValues[locale.languageCode]![text] ?? text; } class AppLocalizationDelegate extends LocalizationsDelegate { const AppLocalizationDelegate(); @override - bool isSupported(Locale locale) => - AppLocalization.languages().contains(locale.languageCode); + bool isSupported(Locale locale) => AppLocalization.languages().contains(locale.languageCode); //Returning a SynchronousFuture here because an async "load" operation //cause an async "load" operation diff --git a/lib/localization/en_us/en_us_translations.dart b/lib/localization/en_us/en_us_translations.dart index 282c4c70..4c0df242 100644 --- a/lib/localization/en_us/en_us_translations.dart +++ b/lib/localization/en_us/en_us_translations.dart @@ -27,8 +27,7 @@ final Map enUs = { // blood_pressure Screen "no": "No", - "do_you_have_hypertension_tendency": - "Do you have a tendency for hypertension?", + "do_you_have_hypertension_tendency": "Do you have a tendency for hypertension?", "your_blood_pressure": "Your blood pressure?", "average_pressure": "Average pressure:", "do_you_have_hypotension_tendency": "Do you have a tendency for hypotension?", @@ -43,13 +42,11 @@ final Map enUs = { // schedule Screen "your_schedule": "Your Daily Schedule?", - "tell_your_schedule": - "Tell us about your daily routine, when you wake up, eat, and go to sleep:", + "tell_your_schedule": "Tell us about your daily routine, when you wake up, eat, and go to sleep:", // additional_information Screen "additional_information": "Additional Information:", - "enter_additional_information": - "Enter any additional information you would like to share:", + "enter_additional_information": "Enter any additional information you would like to share:", // language_select Screen "lbl_english": "English", diff --git a/lib/localization/ru/ru_translations.dart b/lib/localization/ru/ru_translations.dart index 3d28a232..8d7f708f 100644 --- a/lib/localization/ru/ru_translations.dart +++ b/lib/localization/ru/ru_translations.dart @@ -57,13 +57,11 @@ final Map ru = { // schedule Screen "your_schedule": "Ваш режим дня?", - "tell_your_schedule": - "Расскажите в свободной форме о том как просыпаетесь, когда едите, когда ложитесь спать:", + "tell_your_schedule": "Расскажите в свободной форме о том как просыпаетесь, когда едите, когда ложитесь спать:", // additional_information Screen "additional_information": "Дополнительная информация", - "enter_additional_information": - "Введите любую дополнительную информацию на своё усмотрение:", + "enter_additional_information": "Введите любую дополнительную информацию на своё усмотрение:", // language_select Screen "lbl_english": "English", diff --git a/lib/locator_service.dart b/lib/locator_service.dart index dfd61987..1d95a0b5 100644 --- a/lib/locator_service.dart +++ b/lib/locator_service.dart @@ -1,4 +1,5 @@ import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/constants/constants.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.dart'; import 'package:eatvio_app/features/blog_post/presentation/bloc/blog_post_cubit.dart'; import 'package:eatvio_app/features/blog_post/repositories/blog_post_repository.dart'; @@ -11,7 +12,9 @@ import 'package:eatvio_app/features/chat/services/chat_service.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; import 'package:eatvio_app/features/feed/services/feed_service.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; +import 'package:eatvio_app/features/registration/repositories/registration_repository.dart'; +import 'package:eatvio_app/features/registration/services/registration_service.dart'; import 'package:get_it/get_it.dart'; final sl = GetIt.instance; @@ -22,6 +25,7 @@ Future init() async { sl.registerLazySingleton(() => NewMessagesCubit()); sl.registerLazySingleton(() => NotificationsCubit()); + sl.registerFactory(() => RegistrationCubit(registrationRepository: sl())); sl.registerFactory(() => ChatRoomCubit(chatRepository: sl(), initializationCubit: sl())); sl.registerFactory(() => FeedCubit(feedRepository: sl())); sl.registerFactory(() => BlogPostCubit(blogPostRepository: sl())); @@ -30,17 +34,19 @@ Future init() async { sl.registerLazySingleton(() => ChatRepository(chatService: sl())); sl.registerLazySingleton(() => FeedRepository(feedService: sl())); sl.registerLazySingleton(() => BlogPostRepository(blogPostService: sl())); + sl.registerLazySingleton(() => RegistrationRepository(registrationService: sl())); // Services sl.registerLazySingleton(() => ChatService(sl())); sl.registerLazySingleton(() => FeedService(sl())); sl.registerLazySingleton(() => BlogPostService(sl())); + sl.registerLazySingleton(() => RegistrationService(sl())); // External sl.registerLazySingleton( () => Dio( BaseOptions( - baseUrl: dotenv.env['SERVER_ROOT']!, + baseUrl: baseUrl, ), ), ); diff --git a/lib/main.dart b/lib/main.dart index e73bd429..ab53ccad 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -6,6 +6,7 @@ import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/noti import 'package:eatvio_app/features/chat/presentation/pages/chat_select_screen/bloc/chat_select_bloc.dart'; import 'package:eatvio_app/features/chat/presentation/pages/chat_select_screen/models/chat_select_model.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; +import 'package:eatvio_app/locator_service.dart' as di; import 'package:eatvio_app/locator_service.dart'; import 'package:eatvio_app/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart'; import 'package:eatvio_app/presentation/diary/diary_edit_screen/models/diary_edit_model.dart'; @@ -14,12 +15,11 @@ import 'package:eatvio_app/presentation/profile/my_profile_screen/models/my_prof import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; -import 'core/app_export.dart'; import 'package:hive_flutter/hive_flutter.dart'; -import 'package:path_provider/path_provider.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:keyboard_dismisser/keyboard_dismisser.dart'; -import 'package:eatvio_app/locator_service.dart' as di; +import 'package:path_provider/path_provider.dart'; + +import 'core/app_export.dart'; var globalMessengerKey = GlobalKey(); @@ -28,7 +28,6 @@ void main() async { await di.init(); final appDocumentDir = await getApplicationDocumentsDirectory(); final path = appDocumentDir.path; - await dotenv.load(fileName: ".env"); await Hive.initFlutter(path); SystemChrome.setPreferredOrientations([ DeviceOrientation.landscapeLeft, @@ -47,7 +46,6 @@ class MyApp extends StatelessWidget { BlocProvider(create: (context) => sl()), BlocProvider(create: (context) => sl()), BlocProvider(create: (context) => sl()), - BlocProvider(create: (context) => ThemeBloc(ThemeState(themeType: PrefUtils().getThemeData()))), BlocProvider(create: (context) => sl()..loadFeedBlogPostList()), BlocProvider(create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent())), diff --git a/lib/presentation/auth/auth_screen/auth_screen.dart b/lib/presentation/auth/auth_screen/auth_screen.dart index 4a74ba36..ec01a983 100644 --- a/lib/presentation/auth/auth_screen/auth_screen.dart +++ b/lib/presentation/auth/auth_screen/auth_screen.dart @@ -1,21 +1,21 @@ +import 'dart:convert'; + +import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/core/token_storage.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; +import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; +import 'package:eatvio_app/widgets/custom_text_form_field.dart'; +import 'package:eatvio_app/widgets/next_step_button.dart'; +import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; +import 'package:hive/hive.dart'; +import 'package:http/http.dart' as http; +import 'package:validators/validators.dart'; import 'bloc/auth_bloc.dart'; import 'models/auth_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:validators/validators.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'dart:convert'; -import 'package:hive/hive.dart'; -import 'package:http/http.dart' as http; -class AuthScreen extends StatelessWidget { +class AuthScreen extends StatefulWidget { static Widget builder(BuildContext context) { return BlocProvider( create: (context) => AuthBloc( @@ -29,47 +29,57 @@ class AuthScreen extends StatelessWidget { ); } + @override + State createState() => _AuthScreenState(); +} + +class _AuthScreenState extends State { + bool checkboxState = false; + @override Widget build(BuildContext context) { mediaQueryData = MediaQuery.of(context); return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: GestureDetector( - onTap: () => FocusScope.of(context).unfocus(), - child: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), - child: Column(children: [ - SizedBox(height: 36.v), - Text("user_authorization".tr, style: theme.textTheme.headlineSmall), - SizedBox(height: 60.v), - Text("email".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 3.v), - BlocSelector( - selector: (state) => state.emailController, - builder: (context, emailController) { - return CustomTextFormField(controller: emailController, textInputAction: TextInputAction.done); - },), - SizedBox(height: 22.v), - Text("password".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 5.v), - BlocSelector( - selector: (state) => state.passwordController, - builder: (context, passwordController) { - return CustomTextFormField( - obscureText: true, - controller: passwordController, - ); - },), - SizedBox(height: 50.v), - NextStepButton( - text: "no_account".tr.toUpperCase(), - margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapNoAccount(context), - ), - /*NextStepButton( + resizeToAvoidBottomInset: false, + appBar: _buildAppBar(context), + body: GestureDetector( + onTap: () => FocusScope.of(context).unfocus(), + child: Container( + width: double.maxFinite, + padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), + child: Column( + children: [ + SizedBox(height: 36.v), + Text("user_authorization".tr, style: theme.textTheme.headlineSmall), + SizedBox(height: 60.v), + Text("email".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 3.v), + BlocSelector( + selector: (state) => state.emailController, + builder: (context, emailController) { + return CustomTextFormField(controller: emailController, textInputAction: TextInputAction.done); + }, + ), + SizedBox(height: 22.v), + Text("password".tr, style: theme.textTheme.bodyLarge), + SizedBox(height: 5.v), + BlocSelector( + selector: (state) => state.passwordController, + builder: (context, passwordController) { + return CustomTextFormField( + obscureText: true, + controller: passwordController, + ); + }, + ), + SizedBox(height: 50.v), + NextStepButton( + text: "no_account".tr.toUpperCase(), + margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + onPressed: onTapNoAccount(context), + ), + /*NextStepButton( text: "Тест дневника".toUpperCase(), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), @@ -81,14 +91,21 @@ class AuthScreen extends StatelessWidget { EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, 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),); - },), - ],),),),); + BlocBuilder( + builder: (context, state) { + return NextStepButton( + text: "authentificate".tr.toUpperCase(), + margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 16.v), + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + onPressed: onTapAuth(state, context), + ); + }, + ), + ], + ), + ), + ), + ); } onTapAuth(AuthState state, BuildContext context) { @@ -99,15 +116,19 @@ class AuthScreen extends StatelessWidget { 'email': state.emailController!.text, 'password': state.passwordController!.text, }; - final response = await http.post(Uri.parse(dotenv.env['SERVER_ROOT']! + '/login'), - headers: {'Content-Type': 'application/json'}, body: json.encode(credentials), encoding: utf8,); + final response = await http.post( + Uri.parse(baseUrl + '/api/login'), + 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'); final token = res['token']; box.put('token', token); - TokenStorage.saveTokenInStorage(token); + await TokenStorage.saveTokenInStorage(token); GoRouter.of(context).go('/my-profile-screen'); } else { showDialog( @@ -168,8 +189,11 @@ class AuthScreen extends StatelessWidget { onTapNoAccount(BuildContext context) { return () { - GoRouter.of(context).goNamed('languageSelectScreen'); + GoRouter.of(context).goNamed('registrationScreen'); }; + // return () { + // GoRouter.of(context).goNamed('languageSelectScreen'); + // }; } /// Section Widget diff --git a/lib/presentation/auth/auth_screen/bloc/auth_bloc.dart b/lib/presentation/auth/auth_screen/bloc/auth_bloc.dart index 6622981a..0d8f67ad 100644 --- a/lib/presentation/auth/auth_screen/bloc/auth_bloc.dart +++ b/lib/presentation/auth/auth_screen/bloc/auth_bloc.dart @@ -1,10 +1,10 @@ +import 'package:eatvio_app/presentation/auth/auth_screen/models/auth_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; + import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/auth/auth_screen/models/auth_model.dart'; part 'auth_event.dart'; - part 'auth_state.dart'; /// A bloc that manages the state of a Auth according to the event that is dispatched to it. 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 e93f2957..1792f4d0 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 @@ -1,14 +1,15 @@ import 'dart:async'; -import 'package:intl/intl.dart'; +import 'dart:convert'; + +import 'package:eatvio_app/presentation/diary/diary_edit_screen/models/diary_edit_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -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'; +import 'package:http/http.dart' as http; +import 'package:image_picker/image_picker.dart'; +import 'package:intl/intl.dart'; + +import '/core/app_export.dart'; part 'diary_edit_event.dart'; part 'diary_edit_state.dart'; @@ -148,7 +149,7 @@ class DiaryEditBloc extends Bloc { fetchDiaryId(String token, Emitter emit) async { final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/index'), + Uri.parse(baseUrl + '/api/diary/index'), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $token', @@ -173,7 +174,7 @@ class DiaryEditBloc extends Bloc { fetchDiaryData(String token, int diaryId) async { final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/$diaryId/show/'), + Uri.parse(baseUrl + '/api/diary/$diaryId/show/'), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $token', @@ -191,7 +192,7 @@ class DiaryEditBloc extends Bloc { ) async { final responseChart = await http.get( Uri.parse( - dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/dailyNutritionData/', + baseUrl + '/api/diary/$diaryID/dailyNutritionData/', ), headers: { 'Content-Type': 'application/json', @@ -234,7 +235,7 @@ class DiaryEditBloc extends Bloc { final box = await Hive.openBox('token'); final token = box.get('token'); final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/index'), + Uri.parse(baseUrl + '/api/diary/index'), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $token', @@ -247,7 +248,7 @@ class DiaryEditBloc extends Bloc { final int diaryId = data['id']; final diaryResponse = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/$diaryId/show/'), + Uri.parse(baseUrl + '/api/diary/$diaryId/show/'), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $token', @@ -260,7 +261,7 @@ class DiaryEditBloc extends Bloc { final String diaryDate = diary['date'] ?? DateTime.now().toString(); final responseChart = await http.get( Uri.parse( - dotenv.env['SERVER_ROOT']! + '/diary/$diaryId/dailyNutritionData/', + baseUrl + '/api/diary/$diaryId/dailyNutritionData/', ), headers: { 'Content-Type': 'application/json', @@ -371,7 +372,7 @@ class DiaryEditBloc extends Bloc { int? mealID, int diaryID, ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/meal/$mealID/satiety/fill'; + String url = baseUrl + '/api/diary/$diaryID/meal/$mealID/satiety/fill'; final Map credentials = { 'satiety': selectedSatiety, }; @@ -419,7 +420,7 @@ class DiaryEditBloc extends Bloc { int? mealID, int diaryID, ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/meal/$mealID/mood/fill'; + String url = baseUrl + '/api/diary/$diaryID/meal/$mealID/mood/fill'; final Map credentials = { 'mood': selectedMood, }; @@ -484,7 +485,7 @@ class DiaryEditBloc extends Bloc { TimeOfDay wakeup, int diaryID, ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/wakeUp/fill'; + String url = baseUrl + '/api/diary/$diaryID/wakeUp/fill'; final formatter = DateFormat('HH:mm'); final wakeupString = formatter.format(DateTime(2022, 1, 1, wakeup.hour, wakeup.minute)); final Map credentials = { @@ -509,7 +510,7 @@ class DiaryEditBloc extends Bloc { TimeOfDay retire, int diaryID, ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill'; + String url = baseUrl + '/api/diary/$diaryID/retire/fill'; final formatter = DateFormat('HH:mm'); final retireString = formatter.format(DateTime(2022, 1, 1, retire.hour, retire.minute)); final Map credentials = { @@ -547,7 +548,7 @@ class DiaryEditBloc extends Bloc { int? mealID, int diaryID, ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/???'; + String url = baseUrl + '/api/diary/???'; final Map credentials = { 'time': mealTime, 'meal_id': mealID, @@ -674,7 +675,7 @@ class DiaryEditBloc extends Bloc { int? mealID, int diaryID, ) async { - String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/create'; + String url = '${baseUrl}/api/diary/$diaryID/meal/$mealID/portions/create'; final Map credentials = { 'product_name': name, @@ -705,7 +706,7 @@ class DiaryEditBloc extends Bloc { final Map credentials = {'name': event.input}; final uri = Uri.parse( - '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/filter?${Uri(queryParameters: credentials).query}', + '${baseUrl}/api/diary/product_nutritional_values/filter?${Uri(queryParameters: credentials).query}', ); final response = await http.get( @@ -767,7 +768,7 @@ class DiaryEditBloc extends Bloc { int? mealID, int diaryID, ) async { - String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete'; + String url = '${baseUrl}/api/diary/$diaryID/meal/$mealID/portions/$portionID/delete'; var response = await http.delete( Uri.parse(url), @@ -813,7 +814,7 @@ class DiaryEditBloc extends Bloc { int? mealID, int diaryID, ) async { - String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete'; + String url = '${baseUrl}/api/diary/$diaryID/meal/$mealID/photo/delete'; final Map credentials = { 'id': photoID, 'path': path, @@ -866,7 +867,7 @@ class DiaryEditBloc extends Bloc { 'comment': comment ?? " ", }; - String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/finishDay'; + String url = '${baseUrl}/api/diary/$diaryID/finishDay'; var response = await http.post( Uri.parse(url), @@ -905,7 +906,7 @@ class DiaryEditBloc extends Bloc { int mealId, String? token, ) async { - String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload'; + String url = '${baseUrl}/api/diary/$diaryID/meal/$mealId/photo/upload'; var request = http.MultipartRequest('POST', Uri.parse(url)); request.headers['Authorization'] = 'Bearer $token'; @@ -958,9 +959,9 @@ class DiaryEditBloc extends Bloc { String? token, ) async { final Uri url = Uri.parse( - '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/sendToModeration', + '${baseUrl}/api/diary/product_nutritional_values/sendToModeration', ); - final Uri serverURL = Uri.parse('${dotenv.env['SERVER_ROOT']!}'); + final Uri serverURL = Uri.parse('${baseUrl}'); String host = serverURL.host; final Map credentials = { 'name': name, @@ -1020,7 +1021,7 @@ class DiaryEditBloc extends Bloc { String comment, int diaryID, ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill'; + String url = baseUrl + '/api/diary/$diaryID/retire/fill'; final Map credentials = { 'comment': comment, }; 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 c2c5dad3..318a7688 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 @@ -122,7 +122,6 @@ class ChangeMeal extends DiaryEditEvent { List get props => [value, meals]; } - class ClearInput extends DiaryEditEvent { ClearInput({required this.value}); @@ -154,18 +153,18 @@ class RefreshEvent extends DiaryEditEvent { } class SendModeration extends DiaryEditEvent { - SendModeration( - {required this.name, - required this.energyOn100gr, - required this.proteinsOn100gr, - required this.fatsOn100gr, - required this.carbohydratesOn100gr,}); + SendModeration({ + required this.name, + required this.energyOn100gr, + required this.proteinsOn100gr, + required this.fatsOn100gr, + required this.carbohydratesOn100gr, + }); String name; String energyOn100gr; String proteinsOn100gr; String fatsOn100gr; String carbohydratesOn100gr; @override - List get props => - [name, energyOn100gr, proteinsOn100gr, fatsOn100gr, carbohydratesOn100gr]; + List get props => [name, energyOn100gr, proteinsOn100gr, fatsOn100gr, carbohydratesOn100gr]; } 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 dfea7c25..e5f942fe 100644 --- a/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart +++ b/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart @@ -1,19 +1,19 @@ // ignore_for_file: unused_local_variable -import 'bloc/diary_edit_bloc.dart'; -import 'models/diary_edit_model.dart'; +import 'package:carousel_slider/carousel_slider.dart'; +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/widgets/custom_edit_drop_down.dart'; +import 'package:eatvio_app/widgets/custom_edit_text_form_field.dart'; +import 'package:eatvio_app/widgets/custom_outlined_button.dart'; +import 'package:eatvio_app/widgets/custom_scale_element.dart'; +import 'package:fl_chart/fl_chart.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:fl_chart/fl_chart.dart'; import 'package:image_picker/image_picker.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:eatvio_app/core/app_export.dart'; -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:carousel_slider/carousel_slider.dart'; + +import 'bloc/diary_edit_bloc.dart'; +import 'models/diary_edit_model.dart'; // ignore: must_be_immutable class DiaryEditScreen extends StatelessWidget { @@ -711,7 +711,7 @@ class DiaryEditScreen extends StatelessWidget { borderRadius: BorderRadiusStyle.roundedBorder5, ), child: Image.network( - dotenv.env['STORAGE_URL']! + photo['path'], + baseUrl + '/storage/' + photo['path'], ), ), Positioned( diff --git a/lib/presentation/diary/diary_edit_screen/models/diary_edit_model.dart b/lib/presentation/diary/diary_edit_screen/models/diary_edit_model.dart index 6f68bc2d..d37abbf4 100644 --- a/lib/presentation/diary/diary_edit_screen/models/diary_edit_model.dart +++ b/lib/presentation/diary/diary_edit_screen/models/diary_edit_model.dart @@ -1,7 +1,7 @@ // ignore_for_file: must_be_immutable -import 'package:equatable/equatable.dart'; import 'package:eatvio_app/data/models/selectionPopupModel/selection_popup_model.dart'; +import 'package:equatable/equatable.dart'; /// This class defines the variables used in the [k0_page], /// and is typically used to hold data that is passed between different parts of the application. diff --git a/lib/presentation/diets/diet_create_screen/bloc/diet_create_bloc.dart b/lib/presentation/diets/diet_create_screen/bloc/diet_create_bloc.dart index a28b79de..65ea65b9 100644 --- a/lib/presentation/diets/diet_create_screen/bloc/diet_create_bloc.dart +++ b/lib/presentation/diets/diet_create_screen/bloc/diet_create_bloc.dart @@ -1,15 +1,15 @@ import 'dart:async'; +import 'dart:convert'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/presentation/diets/diet_create_screen/models/diet_create_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:go_router/go_router.dart'; import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; -import 'dart:convert'; + import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/diets/diet_create_screen/models/diet_create_model.dart'; part 'diet_create_event.dart'; part 'diet_create_state.dart'; @@ -32,21 +32,27 @@ class DietCreateBloc extends Bloc { } if (state is DietCreateLoadedState) { var currentState = state as DietCreateLoadedState; - emit(currentState.copyWith( - dietModelObj: currentState.dietModelObj, - name: currentState.name, - details: currentState.details, - ),); + emit( + currentState.copyWith( + dietModelObj: currentState.dietModelObj, + name: currentState.name, + details: currentState.details, + ), + ); } else { - emit(DietCreateLoadedState( - name: TextEditingController(), - details: TextEditingController(), - ),); + emit( + DietCreateLoadedState( + name: TextEditingController(), + details: TextEditingController(), + ), + ); } } FutureOr _createDiet( - CreateDiet event, Emitter emit,) async { + CreateDiet event, + Emitter emit, + ) async { if (state is DietCreateLoadedState) { var currentState = state as DietCreateLoadedState; @@ -59,7 +65,8 @@ class DietCreateBloc extends Bloc { AppRouter.navigatorKey.currentContext?.goNamed('dietSelectScreen'); } else { print( - 'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}',); + 'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}', + ); } } } @@ -68,7 +75,7 @@ class DietCreateBloc extends Bloc { String? name, String? details, ) async { - String url = '${dotenv.env['SERVER_ROOT']!}/diets/create'; + String url = '${baseUrl}/api/diets/create'; final Map credentials = { 'name': name, diff --git a/lib/presentation/diets/diet_create_screen/bloc/diet_create_state.dart b/lib/presentation/diets/diet_create_screen/bloc/diet_create_state.dart index be825abe..6b42e385 100644 --- a/lib/presentation/diets/diet_create_screen/bloc/diet_create_state.dart +++ b/lib/presentation/diets/diet_create_screen/bloc/diet_create_state.dart @@ -60,6 +60,5 @@ class DietCreateErrorState extends DietCreateState { } class DietCreateInitialState extends DietCreateState { - DietCreateInitialState({required DietCreateModel dietModelObj}) - : super(dietModelObj: dietModelObj); + DietCreateInitialState({required DietCreateModel dietModelObj}) : super(dietModelObj: dietModelObj); } diff --git a/lib/presentation/diets/diet_create_screen/diet_create_screen.dart b/lib/presentation/diets/diet_create_screen/diet_create_screen.dart index 619e8f71..2ade3f80 100644 --- a/lib/presentation/diets/diet_create_screen/diet_create_screen.dart +++ b/lib/presentation/diets/diet_create_screen/diet_create_screen.dart @@ -1,16 +1,18 @@ -import 'bloc/diet_create_bloc.dart'; -import 'models/diet_create_model.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:flutter/material.dart'; +import 'bloc/diet_create_bloc.dart'; +import 'models/diet_create_model.dart'; + class DietCreateScreen extends StatelessWidget { const DietCreateScreen({Key? key}) : super(key: key); static Widget builder(BuildContext context) { final dietID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( - create: (context) => DietCreateBloc(DietCreateState(dietModelObj: DietCreateModel(dietID: dietID.toString())))..add(DietCreateInitialEvent()), - child: DietCreateScreen(),); + create: (context) => DietCreateBloc(DietCreateState(dietModelObj: DietCreateModel(dietID: dietID.toString())))..add(DietCreateInitialEvent()), + child: DietCreateScreen(), + ); } Widget build(BuildContext context) { @@ -43,47 +45,52 @@ class DietCreateScreen extends StatelessWidget { body: Container( width: double.maxFinite, decoration: AppDecoration.fillGray, - child: ListView(children: [ - SizedBox(height: 30.v), - Container( - margin: EdgeInsets.only( - left: 16.h, - right: 20.h, - bottom: 10.h, + child: ListView( + children: [ + SizedBox(height: 30.v), + Container( + margin: EdgeInsets.only( + left: 16.h, + right: 20.h, + bottom: 10.h, + ), + padding: EdgeInsets.all(12.h), + 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), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox(height: 16.0), + TextFormField( + controller: state.name, + decoration: InputDecoration(labelText: 'Заголовок'), + ), + SizedBox(height: 16.0), + TextFormField( + controller: state.details, + decoration: InputDecoration(labelText: 'Описание'), + ), + SizedBox(height: 16.0), + // Здесь нужно добавить виджет для загрузки картинки + ElevatedButton( + onPressed: () => context.read().add(CreateDiet()), + child: Text('Создать'), + ), + ], + ), ), - padding: EdgeInsets.all(12.h), - 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), - ), - ], - ), - child: Column(mainAxisSize: MainAxisSize.min, children: [ - SizedBox(height: 16.0), - TextFormField( - controller: state.name, - decoration: InputDecoration(labelText: 'Заголовок'), - ), - SizedBox(height: 16.0), - TextFormField( - controller: state.details, - decoration: InputDecoration(labelText: 'Описание'), - ), - SizedBox(height: 16.0), - // Здесь нужно добавить виджет для загрузки картинки - ElevatedButton( - onPressed: () => context.read().add(CreateDiet()), - child: Text('Создать'), - ), - ],), - ), - ],), + ], + ), ), ), ); diff --git a/lib/presentation/diets/diet_edit_screen/bloc/diet_edit_bloc.dart b/lib/presentation/diets/diet_edit_screen/bloc/diet_edit_bloc.dart index 22cc1aa2..81e034a1 100644 --- a/lib/presentation/diets/diet_edit_screen/bloc/diet_edit_bloc.dart +++ b/lib/presentation/diets/diet_edit_screen/bloc/diet_edit_bloc.dart @@ -1,18 +1,17 @@ import 'dart:async'; +import 'dart:convert'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/presentation/diets/diet_edit_screen/models/diet_edit_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:go_router/go_router.dart'; import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; -import 'dart:convert'; + import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/diets/diet_edit_screen/models/diet_edit_model.dart'; part 'diet_edit_event.dart'; - part 'diet_edit_state.dart'; /// A bloc that manages the state of a DietEdit according to the event that is dispatched to it. @@ -34,7 +33,7 @@ class DietEditBloc extends Bloc { } final String? dietID = state.dietModelObj?.dietID; final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/diets/show/$dietID'), + Uri.parse(baseUrl + '/api/diets/show/$dietID'), headers: { 'Authorization': 'Bearer $token', }, @@ -44,18 +43,24 @@ class DietEditBloc extends Bloc { if (data is Map) { if (state is DietEditLoadedState) { var currentState = state as DietEditLoadedState; - emit(currentState.copyWith( + emit( + currentState.copyWith( dietModelObj: currentState.dietModelObj, diet: currentState.diet, name: currentState.name, duration: currentState.duration, - details: currentState.details,),); + details: currentState.details, + ), + ); } else { - emit(DietEditLoadedState( + emit( + DietEditLoadedState( diet: data, name: TextEditingController(text: data['name']), details: TextEditingController(text: data['details']), - duration: TextEditingController(text: data['duration']),),); + duration: TextEditingController(text: data['duration']), + ), + ); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку @@ -96,7 +101,7 @@ class DietEditBloc extends Bloc { String? duration, ) async { int id = diet?['id']; - String url = '${dotenv.env['SERVER_ROOT']!}/diets/update/$id'; + String url = '${baseUrl}/api/diets/update/$id'; final Map credentials = { 'id': id, diff --git a/lib/presentation/diets/diet_edit_screen/bloc/diet_edit_state.dart b/lib/presentation/diets/diet_edit_screen/bloc/diet_edit_state.dart index bfc5e245..ab0d2ee3 100644 --- a/lib/presentation/diets/diet_edit_screen/bloc/diet_edit_state.dart +++ b/lib/presentation/diets/diet_edit_screen/bloc/diet_edit_state.dart @@ -22,8 +22,13 @@ class DietEditState extends Equatable { } class DietEditLoadedState extends DietEditState { - DietEditLoadedState( - {this.dietModelObj, this.diet, this.name, this.details, this.duration,}); + DietEditLoadedState({ + this.dietModelObj, + this.diet, + this.name, + this.details, + this.duration, + }); DietEditModel? dietModelObj; Map? diet; @@ -59,6 +64,5 @@ class DietEditErrorState extends DietEditState { } class DietEditInitialState extends DietEditState { - DietEditInitialState({required DietEditModel dietModelObj}) - : super(dietModelObj: dietModelObj); + DietEditInitialState({required DietEditModel dietModelObj}) : super(dietModelObj: dietModelObj); } diff --git a/lib/presentation/diets/diet_edit_screen/diet_edit_screen.dart b/lib/presentation/diets/diet_edit_screen/diet_edit_screen.dart index aa7cf200..d76d79d7 100644 --- a/lib/presentation/diets/diet_edit_screen/diet_edit_screen.dart +++ b/lib/presentation/diets/diet_edit_screen/diet_edit_screen.dart @@ -1,9 +1,9 @@ -import 'bloc/diet_edit_bloc.dart'; -import 'models/diet_edit_model.dart'; +import 'package:cached_network_image/cached_network_image.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:flutter/material.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; + +import 'bloc/diet_edit_bloc.dart'; +import 'models/diet_edit_model.dart'; class DietEditScreen extends StatelessWidget { const DietEditScreen({Key? key}) : super(key: key); @@ -11,8 +11,9 @@ class DietEditScreen extends StatelessWidget { static Widget builder(BuildContext context) { final dietID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( - create: (context) => DietEditBloc(DietEditState(dietModelObj: DietEditModel(dietID: dietID.toString())))..add(DietEditInitialEvent()), - child: DietEditScreen(),); + create: (context) => DietEditBloc(DietEditState(dietModelObj: DietEditModel(dietID: dietID.toString())))..add(DietEditInitialEvent()), + child: DietEditScreen(), + ); } Widget build(BuildContext context) { @@ -71,7 +72,7 @@ class DietEditScreen extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (state.diet?['image'] ?? ''), + imageUrl: baseUrl + '/storage/' + (state.diet?['image'] ?? ''), imageBuilder: (context, imageProvider) => CircleAvatar( backgroundImage: imageProvider, radius: 25, diff --git a/lib/presentation/diets/diet_select_screen/bloc/diet_select_bloc.dart b/lib/presentation/diets/diet_select_screen/bloc/diet_select_bloc.dart index e12eab5e..56dabcf2 100644 --- a/lib/presentation/diets/diet_select_screen/bloc/diet_select_bloc.dart +++ b/lib/presentation/diets/diet_select_screen/bloc/diet_select_bloc.dart @@ -1,17 +1,17 @@ //import 'package:eatvio_app/presentation/auth/auth_screen/auth_screen.dart'; import 'dart:async'; +import 'dart:convert'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/presentation/diets/diet_select_screen/models/diet_select_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/diets/diet_select_screen/models/diet_select_model.dart'; -import 'package:http/http.dart' as http; -import 'dart:convert'; -import 'package:hive/hive.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:image_picker/image_picker.dart'; import 'package:go_router/go_router.dart'; +import 'package:hive/hive.dart'; +import 'package:http/http.dart' as http; +import 'package:image_picker/image_picker.dart'; + +import '/core/app_export.dart'; part 'diet_select_event.dart'; part 'diet_select_state.dart'; @@ -33,7 +33,7 @@ class DietSelectBloc extends Bloc { AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); } final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/diets/index'), + Uri.parse(baseUrl + '/api/diets/index'), headers: { 'Authorization': 'Bearer $token', }, @@ -47,15 +47,19 @@ class DietSelectBloc extends Bloc { if (state is DietSelectLoadedState) { print('Got loaded'); var currentState = state as DietSelectLoadedState; - emit((currentState).copyWith( - posts: data, - myProfileModelObj: currentState.myProfileModelObj, - ),); + emit( + (currentState).copyWith( + posts: data, + myProfileModelObj: currentState.myProfileModelObj, + ), + ); } else { print('Got unloaded'); - emit(DietSelectLoadedState( - posts: data, - ),); + emit( + DietSelectLoadedState( + posts: data, + ), + ); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку diff --git a/lib/presentation/diets/diet_select_screen/bloc/diet_select_state.dart b/lib/presentation/diets/diet_select_screen/bloc/diet_select_state.dart index e7b709db..85b7d5ab 100644 --- a/lib/presentation/diets/diet_select_screen/bloc/diet_select_state.dart +++ b/lib/presentation/diets/diet_select_screen/bloc/diet_select_state.dart @@ -12,14 +12,12 @@ class DietSelectState extends Equatable { } class DietSelectInitialState extends DietSelectState { - DietSelectInitialState({required DietSelectModel myProfileModelObj}) - : super(myProfileModelObj: myProfileModelObj); + DietSelectInitialState({required DietSelectModel myProfileModelObj}) : super(myProfileModelObj: myProfileModelObj); } /// Represents the state of DietSelect in the application. class DietSelectLoadedState extends DietSelectState { - DietSelectLoadedState({this.myProfileModelObj, this.posts}) - : super(myProfileModelObj: null); + DietSelectLoadedState({this.myProfileModelObj, this.posts}) : super(myProfileModelObj: null); DietSelectModel? myProfileModelObj; List? posts; diff --git a/lib/presentation/diets/diet_select_screen/diet_select_screen.dart b/lib/presentation/diets/diet_select_screen/diet_select_screen.dart index 4b026cb2..3f4a8ce8 100644 --- a/lib/presentation/diets/diet_select_screen/diet_select_screen.dart +++ b/lib/presentation/diets/diet_select_screen/diet_select_screen.dart @@ -1,19 +1,20 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart'; +import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; +import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'bloc/diet_select_bloc.dart'; import 'models/diet_select_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter/material.dart'; class DietSelectScreen extends StatelessWidget { static Widget builder(BuildContext context) { return BlocProvider( - create: (context) => DietSelectBloc(DietSelectState(myProfileModelObj: DietSelectModel()))..add(DietSelectInitialEvent()), child: DietSelectScreen(),); + create: (context) => DietSelectBloc(DietSelectState(myProfileModelObj: DietSelectModel()))..add(DietSelectInitialEvent()), + child: DietSelectScreen(), + ); } Widget build(BuildContext context) { @@ -118,50 +119,51 @@ class DietSelectScreen extends StatelessWidget { itemBuilder: (context, index) { final post = state.posts?[index]; return Container( - margin: EdgeInsets.only(bottom: 10), - 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), - ), - ], + margin: EdgeInsets.only(bottom: 10), + 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), + ), + ], + ), + child: ListTile( + leading: CachedNetworkImage( + imageUrl: baseUrl + '/storage/' + post['image'], + imageBuilder: (context, imageProvider) => CircleAvatar( + backgroundImage: imageProvider, + radius: 25, + ), + placeholder: (context, url) => CircularProgressIndicator(), + errorWidget: (context, url, error) => CircleAvatar( + child: Icon(Icons.person), + backgroundColor: Colors.white, + radius: 25, + ), ), - child: ListTile( - leading: CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + post['image'], - imageBuilder: (context, imageProvider) => CircleAvatar( - backgroundImage: imageProvider, - radius: 25, - ), - placeholder: (context, url) => CircularProgressIndicator(), - errorWidget: (context, url, error) => CircleAvatar( - child: Icon(Icons.person), - backgroundColor: Colors.white, - radius: 25, - ), - ), - title: Text( - post?['name'] ?? '', - style: CustomTextStyles.titleMediumSemiBold, - ), - subtitle: Text(post?['details'] ?? ''), + title: Text( + post?['name'] ?? '', + style: CustomTextStyles.titleMediumSemiBold, + ), + subtitle: Text(post?['details'] ?? ''), + onTap: () => GoRouter.of(context).goNamed( + 'dietScreen', + extra: post?['id'].toString(), + ), + trailing: GestureDetector( onTap: () => GoRouter.of(context).goNamed( - 'dietScreen', + 'dietEditScreen', extra: post?['id'].toString(), ), - trailing: GestureDetector( - onTap: () => GoRouter.of(context).goNamed( - 'dietEditScreen', - extra: post?['id'].toString(), - ), - child: Icon(Icons.edit), - ), - ),); + child: Icon(Icons.edit), + ), + ), + ); }, ); } diff --git a/lib/presentation/diets/diet_show_screen/bloc/diet_show_bloc.dart b/lib/presentation/diets/diet_show_screen/bloc/diet_show_bloc.dart index 5fcd3a1d..3d0551a2 100644 --- a/lib/presentation/diets/diet_show_screen/bloc/diet_show_bloc.dart +++ b/lib/presentation/diets/diet_show_screen/bloc/diet_show_bloc.dart @@ -1,18 +1,17 @@ import 'dart:async'; +import 'dart:convert'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/presentation/diets/diet_show_screen/models/diet_show_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:go_router/go_router.dart'; import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; -import 'dart:convert'; + import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/diets/diet_show_screen/models/diet_show_model.dart'; -import 'package:go_router/go_router.dart'; part 'diet_show_event.dart'; - part 'diet_show_state.dart'; /// A bloc that manages the state of a Diet according to the event that is dispatched to it. @@ -34,7 +33,7 @@ class DietBloc extends Bloc { } final String? dietID = state.dietModelObj?.dietID; final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/diets/show/$dietID'), + Uri.parse(baseUrl + '/api/diets/show/$dietID'), headers: { 'Authorization': 'Bearer $token', }, @@ -70,7 +69,7 @@ class DietBloc extends Bloc { } final int id = event.id; final response = await http.post( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/diets/delete/$id'), + Uri.parse(baseUrl + '/api/diets/delete/$id'), headers: { 'Authorization': 'Bearer $token', }, diff --git a/lib/presentation/diets/diet_show_screen/bloc/diet_show_state.dart b/lib/presentation/diets/diet_show_screen/bloc/diet_show_state.dart index 49913f7f..d587263f 100644 --- a/lib/presentation/diets/diet_show_screen/bloc/diet_show_state.dart +++ b/lib/presentation/diets/diet_show_screen/bloc/diet_show_state.dart @@ -28,8 +28,7 @@ class DietLoadedState extends DietState { Map? diet; @override List get props => [dietModelObj, diet]; - DietLoadedState copyWith( - {DietModel? dietModelObj, Map? diet}) { + DietLoadedState copyWith({DietModel? dietModelObj, Map? diet}) { return DietLoadedState( dietModelObj: dietModelObj ?? this.dietModelObj, diet: diet ?? this.diet, @@ -47,6 +46,5 @@ class DietErrorState extends DietState { } class DietInitialState extends DietState { - DietInitialState({required DietModel dietModelObj}) - : super(dietModelObj: dietModelObj); + DietInitialState({required DietModel dietModelObj}) : super(dietModelObj: dietModelObj); } diff --git a/lib/presentation/diets/diet_show_screen/diet_show_screen.dart b/lib/presentation/diets/diet_show_screen/diet_show_screen.dart index 950e47a6..9fae1efd 100644 --- a/lib/presentation/diets/diet_show_screen/diet_show_screen.dart +++ b/lib/presentation/diets/diet_show_screen/diet_show_screen.dart @@ -1,11 +1,10 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:eatvio_app/core/app_export.dart'; +import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'bloc/diet_show_bloc.dart'; import 'models/diet_show_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:flutter/material.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; class DietScreen extends StatelessWidget { const DietScreen({Key? key}) : super(key: key); @@ -13,7 +12,9 @@ class DietScreen extends StatelessWidget { static Widget builder(BuildContext context) { final dietID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( - create: (context) => DietBloc(DietState(dietModelObj: DietModel(dietID: dietID.toString())))..add(DietInitialEvent()), child: DietScreen(),); + create: (context) => DietBloc(DietState(dietModelObj: DietModel(dietID: dietID.toString())))..add(DietInitialEvent()), + child: DietScreen(), + ); } Widget build(BuildContext context) { @@ -68,44 +69,47 @@ class DietScreen extends StatelessWidget { ), ], ), - child: Column(mainAxisSize: MainAxisSize.min, children: [ - CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (state.diet?['image'] ?? ''), - imageBuilder: (context, imageProvider) => CircleAvatar( - backgroundImage: imageProvider, - radius: 25, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + CachedNetworkImage( + imageUrl: baseUrl + '/storage/' + (state.diet?['image'] ?? ''), + imageBuilder: (context, imageProvider) => CircleAvatar( + backgroundImage: imageProvider, + radius: 25, + ), + placeholder: (context, url) => CircularProgressIndicator(), + errorWidget: (context, url, error) => CircleAvatar( + child: Icon(Icons.person), + backgroundColor: Colors.white, + radius: 25, + ), ), - placeholder: (context, url) => CircularProgressIndicator(), - errorWidget: (context, url, error) => CircleAvatar( - child: Icon(Icons.person), - backgroundColor: Colors.white, - radius: 25, + SizedBox(height: 16.0), + Text(state.diet?['name'], style: CustomTextStyles.titleMediumBlack), + SizedBox(height: 8.0), + Text( + state.diet?['details'], ), - ), - SizedBox(height: 16.0), - Text(state.diet?['name'], style: CustomTextStyles.titleMediumBlack), - SizedBox(height: 8.0), - Text( - state.diet?['details'], - ), - SizedBox(height: 16.0), - Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - ElevatedButton( - onPressed: () => GoRouter.of(context).goNamed( - 'dietEditScreen', - extra: state.diet?['id'].toString(), + SizedBox(height: 16.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + ElevatedButton( + onPressed: () => GoRouter.of(context).goNamed( + 'dietEditScreen', + extra: state.diet?['id'].toString(), + ), + child: Text('Редактировать'), ), - child: Text('Редактировать'), - ), - ElevatedButton( - onPressed: () => context.read().add(DeleteEntry(state.diet?['id'])), - child: Text('Удалить'), - ), - ], - ), - ],), + ElevatedButton( + onPressed: () => context.read().add(DeleteEntry(state.diet?['id'])), + child: Text('Удалить'), + ), + ], + ), + ], + ), ), ], ), diff --git a/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_bloc.dart b/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_bloc.dart index 7ddbaca0..624a1ef4 100644 --- a/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_bloc.dart +++ b/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_bloc.dart @@ -1,22 +1,23 @@ import 'dart:async'; +import 'dart:convert'; import 'package:dio/dio.dart'; import 'package:eatvio_app/app_router.dart'; import 'package:eatvio_app/locator_service.dart'; +import 'package:eatvio_app/presentation/feed/blog_post_create_screen/models/blog_post_create_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; import 'package:hive/hive.dart'; import 'package:image_picker/image_picker.dart'; -import 'dart:convert'; + import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/feed/blog_post_create_screen/models/blog_post_create_model.dart'; -import 'package:go_router/go_router.dart'; + part 'blog_post_create_event.dart'; part 'blog_post_create_state.dart'; /// A bloc that manages the state of a BlogPostCreate according to the event that is dispatched to it. -class BlogPostCreateBloc - extends Bloc { +class BlogPostCreateBloc extends Bloc { BlogPostCreateBloc(BlogPostCreateState initialState) : super(initialState) { on(_onInitialize); on(_createBlogPost); @@ -79,8 +80,7 @@ class BlogPostCreateBloc } } - sendBlogPost(String? title, String? youtubeURL, String? description, - XFile? image) async { + sendBlogPost(String? title, String? youtubeURL, String? description, XFile? image) async { String url = '/blog_post/create'; final Map credentials = { @@ -99,8 +99,7 @@ class BlogPostCreateBloc return response; } - FutureOr _uploadImages( - UploadImages event, Emitter emit) { + FutureOr _uploadImages(UploadImages event, Emitter emit) { if (state is BlogPostCreateLoadedState) { var currentState = state as BlogPostCreateLoadedState; emit( diff --git a/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_state.dart b/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_state.dart index 4da3f5a6..33dc59b5 100644 --- a/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_state.dart +++ b/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_state.dart @@ -40,8 +40,7 @@ class BlogPostCreateLoadedState extends BlogPostCreateState { bool isLoading; XFile? image; @override - List get props => - [blog_postModelObj, title, description, youtubeURL]; + List get props => [blog_postModelObj, title, description, youtubeURL]; BlogPostCreateLoadedState copyWith({ BlogPostCreateModel? blog_postModelObj, TextEditingController? title, @@ -73,6 +72,5 @@ class BlogPostCreateErrorState extends BlogPostCreateState { } class BlogPostCreateInitialState extends BlogPostCreateState { - BlogPostCreateInitialState({required BlogPostCreateModel blog_postModelObj}) - : super(blog_postModelObj: blog_postModelObj); + BlogPostCreateInitialState({required BlogPostCreateModel blog_postModelObj}) : super(blog_postModelObj: blog_postModelObj); } diff --git a/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.freezed.dart b/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.freezed.dart index d403e452..13d4b864 100644 --- a/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.freezed.dart +++ b/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.freezed.dart @@ -14,8 +14,7 @@ T _$identity(T value) => value; final _privateConstructorUsedError = UnsupportedError( 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); -BlogPostCreateCredentialsModel _$BlogPostCreateCredentialsModelFromJson( - Map json) { +BlogPostCreateCredentialsModel _$BlogPostCreateCredentialsModelFromJson(Map json) { return _BlogPostCreateCredentialsModel.fromJson(json); } @@ -29,29 +28,19 @@ mixin _$BlogPostCreateCredentialsModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $BlogPostCreateCredentialsModelCopyWith - get copyWith => throw _privateConstructorUsedError; + $BlogPostCreateCredentialsModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $BlogPostCreateCredentialsModelCopyWith<$Res> { - factory $BlogPostCreateCredentialsModelCopyWith( - BlogPostCreateCredentialsModel value, - $Res Function(BlogPostCreateCredentialsModel) then) = - _$BlogPostCreateCredentialsModelCopyWithImpl<$Res, - BlogPostCreateCredentialsModel>; + factory $BlogPostCreateCredentialsModelCopyWith(BlogPostCreateCredentialsModel value, $Res Function(BlogPostCreateCredentialsModel) then) = + _$BlogPostCreateCredentialsModelCopyWithImpl<$Res, BlogPostCreateCredentialsModel>; @useResult - $Res call( - {String title, - String description, - @JsonKey(name: 'youtube_url') String youtubeUrl, - String status}); + $Res call({String title, String description, @JsonKey(name: 'youtube_url') String youtubeUrl, String status}); } /// @nodoc -class _$BlogPostCreateCredentialsModelCopyWithImpl<$Res, - $Val extends BlogPostCreateCredentialsModel> - implements $BlogPostCreateCredentialsModelCopyWith<$Res> { +class _$BlogPostCreateCredentialsModelCopyWithImpl<$Res, $Val extends BlogPostCreateCredentialsModel> implements $BlogPostCreateCredentialsModelCopyWith<$Res> { _$BlogPostCreateCredentialsModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -89,29 +78,18 @@ class _$BlogPostCreateCredentialsModelCopyWithImpl<$Res, } /// @nodoc -abstract class _$$BlogPostCreateCredentialsModelImplCopyWith<$Res> - implements $BlogPostCreateCredentialsModelCopyWith<$Res> { - factory _$$BlogPostCreateCredentialsModelImplCopyWith( - _$BlogPostCreateCredentialsModelImpl value, - $Res Function(_$BlogPostCreateCredentialsModelImpl) then) = +abstract class _$$BlogPostCreateCredentialsModelImplCopyWith<$Res> implements $BlogPostCreateCredentialsModelCopyWith<$Res> { + factory _$$BlogPostCreateCredentialsModelImplCopyWith(_$BlogPostCreateCredentialsModelImpl value, $Res Function(_$BlogPostCreateCredentialsModelImpl) then) = __$$BlogPostCreateCredentialsModelImplCopyWithImpl<$Res>; @override @useResult - $Res call( - {String title, - String description, - @JsonKey(name: 'youtube_url') String youtubeUrl, - String status}); + $Res call({String title, String description, @JsonKey(name: 'youtube_url') String youtubeUrl, String status}); } /// @nodoc -class __$$BlogPostCreateCredentialsModelImplCopyWithImpl<$Res> - extends _$BlogPostCreateCredentialsModelCopyWithImpl<$Res, - _$BlogPostCreateCredentialsModelImpl> +class __$$BlogPostCreateCredentialsModelImplCopyWithImpl<$Res> extends _$BlogPostCreateCredentialsModelCopyWithImpl<$Res, _$BlogPostCreateCredentialsModelImpl> implements _$$BlogPostCreateCredentialsModelImplCopyWith<$Res> { - __$$BlogPostCreateCredentialsModelImplCopyWithImpl( - _$BlogPostCreateCredentialsModelImpl _value, - $Res Function(_$BlogPostCreateCredentialsModelImpl) _then) + __$$BlogPostCreateCredentialsModelImplCopyWithImpl(_$BlogPostCreateCredentialsModelImpl _value, $Res Function(_$BlogPostCreateCredentialsModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -145,17 +123,11 @@ class __$$BlogPostCreateCredentialsModelImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() -class _$BlogPostCreateCredentialsModelImpl - implements _BlogPostCreateCredentialsModel { +class _$BlogPostCreateCredentialsModelImpl implements _BlogPostCreateCredentialsModel { const _$BlogPostCreateCredentialsModelImpl( - {required this.title, - required this.description, - @JsonKey(name: 'youtube_url') required this.youtubeUrl, - this.status = 'active'}); + {required this.title, required this.description, @JsonKey(name: 'youtube_url') required this.youtubeUrl, this.status = 'active'}); - factory _$BlogPostCreateCredentialsModelImpl.fromJson( - Map json) => - _$$BlogPostCreateCredentialsModelImplFromJson(json); + factory _$BlogPostCreateCredentialsModelImpl.fromJson(Map json) => _$$BlogPostCreateCredentialsModelImplFromJson(json); @override final String title; @@ -179,25 +151,20 @@ class _$BlogPostCreateCredentialsModelImpl (other.runtimeType == runtimeType && other is _$BlogPostCreateCredentialsModelImpl && (identical(other.title, title) || other.title == title) && - (identical(other.description, description) || - other.description == description) && - (identical(other.youtubeUrl, youtubeUrl) || - other.youtubeUrl == youtubeUrl) && + (identical(other.description, description) || other.description == description) && + (identical(other.youtubeUrl, youtubeUrl) || other.youtubeUrl == youtubeUrl) && (identical(other.status, status) || other.status == status)); } @JsonKey(ignore: true) @override - int get hashCode => - Object.hash(runtimeType, title, description, youtubeUrl, status); + int get hashCode => Object.hash(runtimeType, title, description, youtubeUrl, status); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$BlogPostCreateCredentialsModelImplCopyWith< - _$BlogPostCreateCredentialsModelImpl> - get copyWith => __$$BlogPostCreateCredentialsModelImplCopyWithImpl< - _$BlogPostCreateCredentialsModelImpl>(this, _$identity); + _$$BlogPostCreateCredentialsModelImplCopyWith<_$BlogPostCreateCredentialsModelImpl> get copyWith => + __$$BlogPostCreateCredentialsModelImplCopyWithImpl<_$BlogPostCreateCredentialsModelImpl>(this, _$identity); @override Map toJson() { @@ -207,16 +174,14 @@ class _$BlogPostCreateCredentialsModelImpl } } -abstract class _BlogPostCreateCredentialsModel - implements BlogPostCreateCredentialsModel { +abstract class _BlogPostCreateCredentialsModel implements BlogPostCreateCredentialsModel { const factory _BlogPostCreateCredentialsModel( {required final String title, required final String description, @JsonKey(name: 'youtube_url') required final String youtubeUrl, final String status}) = _$BlogPostCreateCredentialsModelImpl; - factory _BlogPostCreateCredentialsModel.fromJson(Map json) = - _$BlogPostCreateCredentialsModelImpl.fromJson; + factory _BlogPostCreateCredentialsModel.fromJson(Map json) = _$BlogPostCreateCredentialsModelImpl.fromJson; @override String get title; @@ -229,7 +194,5 @@ abstract class _BlogPostCreateCredentialsModel String get status; @override @JsonKey(ignore: true) - _$$BlogPostCreateCredentialsModelImplCopyWith< - _$BlogPostCreateCredentialsModelImpl> - get copyWith => throw _privateConstructorUsedError; + _$$BlogPostCreateCredentialsModelImplCopyWith<_$BlogPostCreateCredentialsModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.g.dart b/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.g.dart index 5dec0301..f4bfea00 100644 --- a/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.g.dart +++ b/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.g.dart @@ -6,18 +6,14 @@ part of '../../../../features/blog_post_create/models/blog_post_create_credentia // JsonSerializableGenerator // ************************************************************************** -_$BlogPostCreateCredentialsModelImpl - _$$BlogPostCreateCredentialsModelImplFromJson(Map json) => - _$BlogPostCreateCredentialsModelImpl( - title: json['title'] as String, - description: json['description'] as String, - youtubeUrl: json['youtube_url'] as String, - status: json['status'] as String? ?? 'active', - ); +_$BlogPostCreateCredentialsModelImpl _$$BlogPostCreateCredentialsModelImplFromJson(Map json) => _$BlogPostCreateCredentialsModelImpl( + title: json['title'] as String, + description: json['description'] as String, + youtubeUrl: json['youtube_url'] as String, + status: json['status'] as String? ?? 'active', + ); -Map _$$BlogPostCreateCredentialsModelImplToJson( - _$BlogPostCreateCredentialsModelImpl instance) => - { +Map _$$BlogPostCreateCredentialsModelImplToJson(_$BlogPostCreateCredentialsModelImpl instance) => { 'title': instance.title, 'description': instance.description, 'youtube_url': instance.youtubeUrl, diff --git a/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_model.dart b/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_model.dart index 46b21c4e..b571cef7 100644 --- a/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_model.dart +++ b/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_model.dart @@ -8,8 +8,7 @@ import 'package:equatable/equatable.dart'; class BlogPostCreateModel extends Equatable { final String blog_postID; - BlogPostCreateModel({required String blog_postID}) - : blog_postID = blog_postID; + BlogPostCreateModel({required String blog_postID}) : blog_postID = blog_postID; BlogPostCreateModel copyWith(String blog_postID) { return BlogPostCreateModel(blog_postID: blog_postID); diff --git a/lib/presentation/feed/blog_post_edit_screen/bloc/blog_post_edit_bloc.dart b/lib/presentation/feed/blog_post_edit_screen/bloc/blog_post_edit_bloc.dart index 07dc31ca..02e496fa 100644 --- a/lib/presentation/feed/blog_post_edit_screen/bloc/blog_post_edit_bloc.dart +++ b/lib/presentation/feed/blog_post_edit_screen/bloc/blog_post_edit_bloc.dart @@ -1,18 +1,17 @@ import 'dart:async'; +import 'dart:convert'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/presentation/feed/blog_post_edit_screen/models/blog_post_edit_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:go_router/go_router.dart'; import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; -import 'dart:convert'; + import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/feed/blog_post_edit_screen/models/blog_post_edit_model.dart'; -import 'package:go_router/go_router.dart'; part 'blog_post_edit_event.dart'; - part 'blog_post_edit_state.dart'; /// A bloc that manages the state of a BlogPostEdit according to the event that is dispatched to it. @@ -34,7 +33,7 @@ class BlogPostEditBloc extends Bloc { } final String? blog_postID = state.blog_postModelObj?.blog_postID; final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/feed/show/$blog_postID'), + Uri.parse(baseUrl + '/api/feed/show/$blog_postID'), headers: { 'Authorization': 'Bearer $token', }, @@ -65,8 +64,7 @@ class BlogPostEditBloc extends Bloc { } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку - emit(BlogPostEditErrorState( - 'Некоторые необходимые данные отсутствуют.')); + emit(BlogPostEditErrorState('Некоторые необходимые данные отсутствуют.')); } } else { // Статус ответа не равен 200, обрабатываем ошибку @@ -78,8 +76,7 @@ class BlogPostEditBloc extends Bloc { } } - FutureOr _editBlogPost( - EditBlogPost event, Emitter emit) async { + FutureOr _editBlogPost(EditBlogPost event, Emitter emit) async { if (state is BlogPostEditLoadedState) { var currentState = state as BlogPostEditLoadedState; @@ -91,11 +88,9 @@ class BlogPostEditBloc extends Bloc { ); if (response.statusCode == 200) { - AppRouter.navigatorKey.currentContext?.goNamed('blogPostScreen', - extra: currentState.blog_post?['id'].toString()); + AppRouter.navigatorKey.currentContext?.goNamed('blogPostScreen', extra: currentState.blog_post?['id'].toString()); } else { - print( - 'Failed to edit blog post. Status Code: ${response.statusCode} ${response.body}'); + print('Failed to edit blog post. Status Code: ${response.statusCode} ${response.body}'); } } } @@ -107,7 +102,7 @@ class BlogPostEditBloc extends Bloc { String? description, ) async { int id = blog_post?['id']; - String url = '${dotenv.env['SERVER_ROOT']!}/feed/update/$id'; + String url = '${baseUrl}/api/feed/update/$id'; final Map credentials = { 'id': id, diff --git a/lib/presentation/feed/blog_post_edit_screen/bloc/blog_post_edit_state.dart b/lib/presentation/feed/blog_post_edit_screen/bloc/blog_post_edit_state.dart index cc2d5f36..d78db89d 100644 --- a/lib/presentation/feed/blog_post_edit_screen/bloc/blog_post_edit_state.dart +++ b/lib/presentation/feed/blog_post_edit_screen/bloc/blog_post_edit_state.dart @@ -36,8 +36,7 @@ class BlogPostEditLoadedState extends BlogPostEditState { TextEditingController? description; TextEditingController? youtubeURL; @override - List get props => - [blog_postModelObj, blog_post, title, description, youtubeURL]; + List get props => [blog_postModelObj, blog_post, title, description, youtubeURL]; BlogPostEditLoadedState copyWith({ BlogPostEditModel? blog_postModelObj, Map? blog_post, @@ -65,6 +64,5 @@ class BlogPostEditErrorState extends BlogPostEditState { } class BlogPostEditInitialState extends BlogPostEditState { - BlogPostEditInitialState({required BlogPostEditModel blog_postModelObj}) - : super(blog_postModelObj: blog_postModelObj); + BlogPostEditInitialState({required BlogPostEditModel blog_postModelObj}) : super(blog_postModelObj: blog_postModelObj); } diff --git a/lib/presentation/feed/blog_post_edit_screen/blog_post_edit_screen.dart b/lib/presentation/feed/blog_post_edit_screen/blog_post_edit_screen.dart index 7012a55f..ba691376 100644 --- a/lib/presentation/feed/blog_post_edit_screen/blog_post_edit_screen.dart +++ b/lib/presentation/feed/blog_post_edit_screen/blog_post_edit_screen.dart @@ -1,19 +1,17 @@ -import 'bloc/blog_post_edit_bloc.dart'; -import 'models/blog_post_edit_model.dart'; +import 'package:cached_network_image/cached_network_image.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:flutter/material.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; + +import 'bloc/blog_post_edit_bloc.dart'; +import 'models/blog_post_edit_model.dart'; class BlogPostEditScreen extends StatelessWidget { const BlogPostEditScreen({Key? key}) : super(key: key); static Widget builder(BuildContext context, blog_postID) { return BlocProvider( - create: (context) => BlogPostEditBloc(BlogPostEditState( - blog_postModelObj: - BlogPostEditModel(blog_postID: blog_postID.toString()))) - ..add(BlogPostEditInitialEvent()), + create: (context) => + BlogPostEditBloc(BlogPostEditState(blog_postModelObj: BlogPostEditModel(blog_postID: blog_postID.toString())))..add(BlogPostEditInitialEvent()), child: BlogPostEditScreen(), ); } @@ -77,8 +75,7 @@ class BlogPostEditScreen extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + - (state.blog_post?['image'] ?? ''), + imageUrl: baseUrl + '/storage/' + (state.blog_post?['image'] ?? ''), imageBuilder: (context, imageProvider) => CircleAvatar( backgroundImage: imageProvider, radius: 25, @@ -108,8 +105,7 @@ class BlogPostEditScreen extends StatelessWidget { SizedBox(height: 16.0), // Здесь нужно добавить виджет для загрузки картинки ElevatedButton( - onPressed: () => - context.read().add(EditBlogPost()), + onPressed: () => context.read().add(EditBlogPost()), child: Text('Сохранить'), ), ], diff --git a/lib/presentation/feed/blog_post_screen/models/blog_post_model.dart b/lib/presentation/feed/blog_post_screen/models/blog_post_model.dart index 67cbe661..73e9c6ab 100644 --- a/lib/presentation/feed/blog_post_screen/models/blog_post_model.dart +++ b/lib/presentation/feed/blog_post_screen/models/blog_post_model.dart @@ -1,7 +1,7 @@ // ignore_for_file: must_be_immutable -import 'package:equatable/equatable.dart'; import 'package:eatvio_app/presentation/feed/blog_post_screen/models/comment_model.dart'; +import 'package:equatable/equatable.dart'; class BlogPostModel extends Equatable { final String blog_postID; diff --git a/lib/presentation/feed/blog_post_screen/models/comment_model.dart b/lib/presentation/feed/blog_post_screen/models/comment_model.dart index feecc7c9..2b9c7133 100644 --- a/lib/presentation/feed/blog_post_screen/models/comment_model.dart +++ b/lib/presentation/feed/blog_post_screen/models/comment_model.dart @@ -4,12 +4,13 @@ import 'package:eatvio_app/core/app_export.dart'; // ignore_for_file: must_be_immutable class CommentModel { - CommentModel( - {this.userImage, - this.username, - this.dateText, - this.greetingText, - required this.id,}) { + CommentModel({ + this.userImage, + this.username, + this.dateText, + this.greetingText, + required this.id, + }) { userImage = userImage ?? ImageConstant.imageNotFound; username = username; dateText = dateText; diff --git a/lib/presentation/feed/blog_post_screen/widgets/comment_widget.dart b/lib/presentation/feed/blog_post_screen/widgets/comment_widget.dart index ab177fa1..ed2e075c 100644 --- a/lib/presentation/feed/blog_post_screen/widgets/comment_widget.dart +++ b/lib/presentation/feed/blog_post_screen/widgets/comment_widget.dart @@ -1,10 +1,9 @@ // ignore_for_file: must_be_immutable -import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:cached_network_image/cached_network_image.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/presentation/feed/blog_post_screen/models/comment_model.dart'; -import 'package:cached_network_image/cached_network_image.dart'; +import 'package:flutter/material.dart'; class CommentWidget extends StatelessWidget { CommentWidget(this.commentModelObj, {Key? key}) @@ -36,13 +35,11 @@ class CommentWidget extends StatelessWidget { ], ), child: Row( - mainAxisAlignment: MainAxisAlignment - .spaceBetween, // Move the main axis alignment to space between - crossAxisAlignment: - CrossAxisAlignment.center, // Center the items vertically + mainAxisAlignment: MainAxisAlignment.spaceBetween, // Move the main axis alignment to space between + crossAxisAlignment: CrossAxisAlignment.center, // Center the items vertically children: [ CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + commentModelObj.userImage!, + imageUrl: baseUrl + '/storage/' + commentModelObj.userImage!, imageBuilder: (context, imageProvider) => CircleAvatar( backgroundImage: imageProvider, radius: 25, @@ -69,10 +66,7 @@ class CommentWidget extends StatelessWidget { child: Row( children: [ Text( - commentModelObj.username!.length <= 15 - ? commentModelObj.username! - : commentModelObj.username!.substring(0, 15) + - '...', + commentModelObj.username!.length <= 15 ? commentModelObj.username! : commentModelObj.username!.substring(0, 15) + '...', style: theme.textTheme.titleMedium, ), Spacer(), @@ -96,10 +90,11 @@ class CommentWidget extends StatelessWidget { ), ), CustomImageView( - imagePath: ImageConstant.imgSend, - height: 30.v, - width: 30.h, - margin: EdgeInsets.only(left: 5),), + imagePath: ImageConstant.imgSend, + height: 30.v, + width: 30.h, + margin: EdgeInsets.only(left: 5), + ), ], ), ); diff --git a/lib/presentation/feed/feed_screen/widgets/feed_scroll_item.dart b/lib/presentation/feed/feed_screen/widgets/feed_scroll_item.dart index 2c407394..bc3b1613 100644 --- a/lib/presentation/feed/feed_screen/widgets/feed_scroll_item.dart +++ b/lib/presentation/feed/feed_screen/widgets/feed_scroll_item.dart @@ -1,5 +1,5 @@ -import 'package:flutter/material.dart'; import 'package:eatvio_app/core/app_export.dart'; +import 'package:flutter/material.dart'; class ScrollItem extends StatelessWidget { final String title; diff --git a/lib/presentation/feed/feed_screen/widgets/feed_search_view.dart b/lib/presentation/feed/feed_screen/widgets/feed_search_view.dart index cef2304e..bbfff40f 100644 --- a/lib/presentation/feed/feed_screen/widgets/feed_search_view.dart +++ b/lib/presentation/feed/feed_screen/widgets/feed_search_view.dart @@ -1,31 +1,31 @@ -import 'package:flutter/material.dart'; import 'package:eatvio_app/core/app_export.dart'; +import 'package:flutter/material.dart'; class CustomSearchView extends StatelessWidget { - CustomSearchView( - {Key? key, - this.alignment, - this.width, - this.scrollPadding, - this.controller, - this.focusNode, - this.autofocus = false, - this.textStyle, - this.textInputType = TextInputType.text, - this.maxLines, - this.hintText, - this.hintStyle, - this.prefix, - this.prefixConstraints, - this.suffix, - this.suffixConstraints, - this.contentPadding, - this.borderDecoration, - this.fillColor, - this.filled = true, - this.validator, - this.onChanged,}) - : super( + CustomSearchView({ + Key? key, + this.alignment, + this.width, + this.scrollPadding, + this.controller, + this.focusNode, + this.autofocus = false, + this.textStyle, + this.textInputType = TextInputType.text, + this.maxLines, + this.hintText, + this.hintStyle, + this.prefix, + this.prefixConstraints, + this.suffix, + this.suffixConstraints, + this.contentPadding, + this.borderDecoration, + this.fillColor, + this.filled = true, + this.validator, + this.onChanged, + }) : super( key: key, ); @@ -76,15 +76,15 @@ class CustomSearchView extends StatelessWidget { return alignment != null ? Align( alignment: alignment ?? Alignment.center, - child: searchViewWidget(context),) + child: searchViewWidget(context), + ) : searchViewWidget(context); } searchViewWidget(BuildContext context) => SizedBox( width: width ?? double.maxFinite, child: TextFormField( - scrollPadding: - EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), + scrollPadding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), controller: controller, focusNode: focusNode, onTapOutside: (event) => onTapOutside(), @@ -112,8 +112,9 @@ class CustomSearchView extends StatelessWidget { prefixIcon: prefix ?? SizedBox( child: Padding( - padding: EdgeInsets.only(left: 10), - child: Icon(Icons.search),), + padding: EdgeInsets.only(left: 10), + child: Icon(Icons.search), + ), ), prefixIconConstraints: prefixConstraints ?? BoxConstraints( diff --git a/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_bloc.dart b/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_bloc.dart index f78c3ffb..45b6bcd6 100644 --- a/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_bloc.dart +++ b/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_bloc.dart @@ -1,15 +1,16 @@ import 'dart:async'; +import 'dart:convert'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/presentation/glossary/glossary_screen/models/glossary_screen_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:go_router/go_router.dart'; import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; -import 'dart:convert'; + import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/glossary/glossary_screen/models/glossary_screen_model.dart'; -import 'package:go_router/go_router.dart'; + part 'glossary_screen_event.dart'; part 'glossary_screen_state.dart'; @@ -31,7 +32,7 @@ class GlossaryBloc extends Bloc { AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); } final responseProductGroups = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/glossary/getProductGroups'), + Uri.parse(baseUrl + '/api/glossary/getProductGroups'), headers: { 'Authorization': 'Bearer $token', }, @@ -41,18 +42,23 @@ class GlossaryBloc extends Bloc { if (dataProductGroups is List) { if (state is GlossaryLoadedState) { var currentState = state as GlossaryLoadedState; - emit(currentState.copyWith( + emit( + currentState.copyWith( glossaryModelObj: currentState.glossaryModelObj, token: currentState.token, productGroups: currentState.productGroups, - productList: currentState.productList,),); + productList: currentState.productList, + ), + ); } else { - List productGroupsModel = - _fillProductGroups(dataProductGroups); - emit(GlossaryLoadedState( + List productGroupsModel = _fillProductGroups(dataProductGroups); + emit( + GlossaryLoadedState( token: token, productGroups: productGroupsModel, - productList: [],),); + productList: [], + ), + ); await _getProductListById(token, emit, productGroupsModel[0].id); } } else { @@ -61,8 +67,11 @@ class GlossaryBloc extends Bloc { } } else { // Статус ответа не равен 200, обрабатываем ошибку - emit(GlossaryErrorState( - 'Ошибка сервера: ${responseProductGroups.statusCode}',),); + emit( + GlossaryErrorState( + 'Ошибка сервера: ${responseProductGroups.statusCode}', + ), + ); } } catch (e) { // Ошибка при декодировании JSON или другая ошибка выполнения @@ -71,7 +80,9 @@ class GlossaryBloc extends Bloc { } void _changeProductGroup( - ChangeProductGroup event, Emitter emit,) async { + ChangeProductGroup event, + Emitter emit, + ) async { if (state is GlossaryLoadedState) { var currentState = state as GlossaryLoadedState; await _getProductListById(currentState.token, emit, event.id); @@ -79,9 +90,12 @@ class GlossaryBloc extends Bloc { } Future _getProductListById( - token, Emitter emit, int? productGroupID,) async { + token, + Emitter emit, + int? productGroupID, + ) async { final responseProductList = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/glossary/index/$productGroupID'), + Uri.parse(baseUrl + '/api/glossary/index/$productGroupID'), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $token', @@ -90,10 +104,13 @@ class GlossaryBloc extends Bloc { final dataProductList = jsonDecode(responseProductList.body); if (dataProductList is List) { var currentState = state as GlossaryLoadedState; - emit(currentState.copyWith( + emit( + currentState.copyWith( glossaryModelObj: currentState.glossaryModelObj, productGroups: currentState.productGroups, - productList: dataProductList,),); + productList: dataProductList, + ), + ); } else { emit(GlossaryErrorState('Список продуктов некорректного формата')); } diff --git a/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_state.dart b/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_state.dart index a6f8cf52..42119a8c 100644 --- a/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_state.dart +++ b/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_state.dart @@ -22,24 +22,25 @@ class GlossaryState extends Equatable { } class GlossaryLoadedState extends GlossaryState { - GlossaryLoadedState( - {this.glossaryModelObj, - this.productGroups, - this.productList, - this.token,}); + GlossaryLoadedState({ + this.glossaryModelObj, + this.productGroups, + this.productList, + this.token, + }); GlossaryModel? glossaryModelObj; String? token; List? productGroups; List? productList; @override - List get props => - [glossaryModelObj, productGroups, productList, token]; - GlossaryLoadedState copyWith( - {GlossaryModel? glossaryModelObj, - String? token, - List? productGroups, - List? productList,}) { + List get props => [glossaryModelObj, productGroups, productList, token]; + GlossaryLoadedState copyWith({ + GlossaryModel? glossaryModelObj, + String? token, + List? productGroups, + List? productList, + }) { return GlossaryLoadedState( glossaryModelObj: glossaryModelObj ?? this.glossaryModelObj, productGroups: productGroups ?? this.productGroups, @@ -59,6 +60,5 @@ class GlossaryErrorState extends GlossaryState { } class GlossaryInitialState extends GlossaryState { - GlossaryInitialState({required GlossaryModel glossaryModelObj}) - : super(glossaryModelObj: glossaryModelObj); + GlossaryInitialState({required GlossaryModel glossaryModelObj}) : super(glossaryModelObj: glossaryModelObj); } diff --git a/lib/presentation/glossary/glossary_screen/glossary_screen.dart b/lib/presentation/glossary/glossary_screen/glossary_screen.dart index b421b87a..e8453187 100644 --- a/lib/presentation/glossary/glossary_screen/glossary_screen.dart +++ b/lib/presentation/glossary/glossary_screen/glossary_screen.dart @@ -1,20 +1,22 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/presentation/glossary/glossary_screen/widgets/glossary_scroll_item.dart'; +import 'package:eatvio_app/presentation/glossary/glossary_screen/widgets/glossary_search_widget.dart'; +import 'package:eatvio_app/widgets/custom_drop_down.dart'; +import 'package:eatvio_app/widgets/custom_outlined_button.dart'; +import 'package:flutter/material.dart'; + import 'bloc/glossary_screen_bloc.dart'; import 'models/glossary_screen_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:eatvio_app/widgets/custom_outlined_button.dart'; -import 'package:eatvio_app/widgets/custom_drop_down.dart'; -import 'package:eatvio_app/presentation/glossary/glossary_screen/widgets/glossary_search_widget.dart'; -import 'package:eatvio_app/presentation/glossary/glossary_screen/widgets/glossary_scroll_item.dart'; class GlossaryScreen extends StatelessWidget { const GlossaryScreen({Key? key}) : super(key: key); static Widget builder(BuildContext context) { return BlocProvider( - create: (context) => GlossaryBloc(GlossaryState(glossaryModelObj: GlossaryModel()))..add(GlossaryInitialEvent()), child: GlossaryScreen(),); + create: (context) => GlossaryBloc(GlossaryState(glossaryModelObj: GlossaryModel()))..add(GlossaryInitialEvent()), + child: GlossaryScreen(), + ); } Widget build(BuildContext context) { @@ -125,24 +127,26 @@ class GlossaryScreen extends StatelessWidget { ), ], ), - child: Column(children: [ - Align( - alignment: Alignment.centerLeft, - child: Text( - "Поиск по алфавиту", - style: CustomTextStyles.titleMediumSemiBold, + child: Column( + children: [ + Align( + alignment: Alignment.centerLeft, + child: Text( + "Поиск по алфавиту", + style: CustomTextStyles.titleMediumSemiBold, + ), ), - ), - SizedBox( - height: 8, - ), - SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - children: List.generate(33, _fillAlphabet), + SizedBox( + height: 8, ), - ), - ],), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: List.generate(33, _fillAlphabet), + ), + ), + ], + ), ); } @@ -162,42 +166,44 @@ class GlossaryScreen extends StatelessWidget { ), ], ), - child: Column(children: [ - Align( - alignment: Alignment.centerLeft, - child: Text( - "Группа продуктов", - style: CustomTextStyles.titleMediumSemiBold, + child: Column( + children: [ + Align( + alignment: Alignment.centerLeft, + child: Text( + "Группа продуктов", + style: CustomTextStyles.titleMediumSemiBold, + ), ), - ), - SizedBox( - height: 8, - ), - CustomDropDown( - items: state.productGroups, - defaultValue: state.productGroups?[0], - fillColor: Colors.grey[200]!, - hintText: 'Выберите категорию', - borderDecoration: OutlineInputBorder( - borderRadius: const BorderRadius.all(Radius.circular(8)), - borderSide: BorderSide(color: Colors.grey[200]!, width: 1), + SizedBox( + height: 8, ), - contentPadding: EdgeInsets.symmetric( - horizontal: 10, - vertical: 9, + CustomDropDown( + items: state.productGroups, + value: state.productGroups?[0], + fillColor: Colors.grey[200]!, + hintText: 'Выберите категорию', + borderDecoration: OutlineInputBorder( + borderRadius: const BorderRadius.all(Radius.circular(8)), + borderSide: BorderSide(color: Colors.grey[200]!, width: 1), + ), + contentPadding: EdgeInsets.symmetric( + horizontal: 10, + vertical: 9, + ), + onChanged: _changeProductGroup(context, state), + width: MediaQuery.of(context).size.width, // Set a percentage value as per your layout ), - onChanged: _changeProductGroup(context, state), - width: MediaQuery.of(context).size.width, // Set a percentage value as per your layout - ), - SizedBox( - height: 8, - ), - Align(alignment: Alignment.centerLeft, child: Text("*КБЖУ указано за 100гр")), - SizedBox( - height: 8, - ), - _buildProductList(context, state), - ],), + SizedBox( + height: 8, + ), + Align(alignment: Alignment.centerLeft, child: Text("*КБЖУ указано за 100гр")), + SizedBox( + height: 8, + ), + _buildProductList(context, state), + ], + ), ); } @@ -218,23 +224,24 @@ class GlossaryScreen extends StatelessWidget { _buildProductEntry(product, BuildContext context) { return Container( - margin: EdgeInsets.only(bottom: 10), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: const BorderRadius.all(Radius.circular(12)), - boxShadow: [ - BoxShadow( - color: Colors.grey.withOpacity(0.5), - spreadRadius: 1, - blurRadius: 3, - offset: Offset(0, 3), - ), - ], - ), - child: Column(children: [ + margin: EdgeInsets.only(bottom: 10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.all(Radius.circular(12)), + boxShadow: [ + BoxShadow( + color: Colors.grey.withOpacity(0.5), + spreadRadius: 1, + blurRadius: 3, + offset: Offset(0, 3), + ), + ], + ), + child: Column( + children: [ ListTile( trailing: CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (product['image'] ?? ''), + imageUrl: baseUrl + '/storage/' + (product['image'] ?? ''), imageBuilder: (context, imageProvider) => CircleAvatar( backgroundImage: imageProvider, radius: 25, @@ -255,26 +262,34 @@ class GlossaryScreen extends StatelessWidget { padding: const EdgeInsets.all(16.0), child: Column( children: [ - Row(children: [ - Column(children: [ - Text("Ккал - ${product['energy_on_100gr'].toString()}"), - SizedBox(height: 8), - Text("Белки - ${product['proteins_on_100gr'].toString()}"), - ],), - Spacer(), - Padding( - padding: const EdgeInsets.only(right: 24.0), - child: Column(children: [ - Text("Жиры - ${product['fats_on_100gr'].toString()}"), - SizedBox(height: 8), - Text("Углеводы - ${product['carbohydrates_on_100gr'].toString()}"), - ],), - ), - ],), + Row( + children: [ + Column( + children: [ + Text("Ккал - ${product['energy_on_100gr'].toString()}"), + SizedBox(height: 8), + Text("Белки - ${product['proteins_on_100gr'].toString()}"), + ], + ), + Spacer(), + Padding( + padding: const EdgeInsets.only(right: 24.0), + child: Column( + children: [ + Text("Жиры - ${product['fats_on_100gr'].toString()}"), + SizedBox(height: 8), + Text("Углеводы - ${product['carbohydrates_on_100gr'].toString()}"), + ], + ), + ), + ], + ), ], ), ), - ],),); + ], + ), + ); } Widget _fillAlphabet(int index) { diff --git a/lib/presentation/glossary/glossary_screen/widgets/glossary_scroll_item.dart b/lib/presentation/glossary/glossary_screen/widgets/glossary_scroll_item.dart index 2c407394..bc3b1613 100644 --- a/lib/presentation/glossary/glossary_screen/widgets/glossary_scroll_item.dart +++ b/lib/presentation/glossary/glossary_screen/widgets/glossary_scroll_item.dart @@ -1,5 +1,5 @@ -import 'package:flutter/material.dart'; import 'package:eatvio_app/core/app_export.dart'; +import 'package:flutter/material.dart'; class ScrollItem extends StatelessWidget { final String title; diff --git a/lib/presentation/glossary/glossary_screen/widgets/glossary_search_widget.dart b/lib/presentation/glossary/glossary_screen/widgets/glossary_search_widget.dart index cef2304e..bbfff40f 100644 --- a/lib/presentation/glossary/glossary_screen/widgets/glossary_search_widget.dart +++ b/lib/presentation/glossary/glossary_screen/widgets/glossary_search_widget.dart @@ -1,31 +1,31 @@ -import 'package:flutter/material.dart'; import 'package:eatvio_app/core/app_export.dart'; +import 'package:flutter/material.dart'; class CustomSearchView extends StatelessWidget { - CustomSearchView( - {Key? key, - this.alignment, - this.width, - this.scrollPadding, - this.controller, - this.focusNode, - this.autofocus = false, - this.textStyle, - this.textInputType = TextInputType.text, - this.maxLines, - this.hintText, - this.hintStyle, - this.prefix, - this.prefixConstraints, - this.suffix, - this.suffixConstraints, - this.contentPadding, - this.borderDecoration, - this.fillColor, - this.filled = true, - this.validator, - this.onChanged,}) - : super( + CustomSearchView({ + Key? key, + this.alignment, + this.width, + this.scrollPadding, + this.controller, + this.focusNode, + this.autofocus = false, + this.textStyle, + this.textInputType = TextInputType.text, + this.maxLines, + this.hintText, + this.hintStyle, + this.prefix, + this.prefixConstraints, + this.suffix, + this.suffixConstraints, + this.contentPadding, + this.borderDecoration, + this.fillColor, + this.filled = true, + this.validator, + this.onChanged, + }) : super( key: key, ); @@ -76,15 +76,15 @@ class CustomSearchView extends StatelessWidget { return alignment != null ? Align( alignment: alignment ?? Alignment.center, - child: searchViewWidget(context),) + child: searchViewWidget(context), + ) : searchViewWidget(context); } searchViewWidget(BuildContext context) => SizedBox( width: width ?? double.maxFinite, child: TextFormField( - scrollPadding: - EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), + scrollPadding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), controller: controller, focusNode: focusNode, onTapOutside: (event) => onTapOutside(), @@ -112,8 +112,9 @@ class CustomSearchView extends StatelessWidget { prefixIcon: prefix ?? SizedBox( child: Padding( - padding: EdgeInsets.only(left: 10), - child: Icon(Icons.search),), + padding: EdgeInsets.only(left: 10), + child: Icon(Icons.search), + ), ), prefixIconConstraints: prefixConstraints ?? BoxConstraints( diff --git a/lib/presentation/plans/plan_create_screen/bloc/plan_create_bloc.dart b/lib/presentation/plans/plan_create_screen/bloc/plan_create_bloc.dart index fd30edd0..3cab0f65 100644 --- a/lib/presentation/plans/plan_create_screen/bloc/plan_create_bloc.dart +++ b/lib/presentation/plans/plan_create_screen/bloc/plan_create_bloc.dart @@ -1,15 +1,16 @@ import 'dart:async'; +import 'dart:convert'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/presentation/plans/plan_create_screen/models/plan_create_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:go_router/go_router.dart'; import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; -import 'dart:convert'; + import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/plans/plan_create_screen/models/plan_create_model.dart'; -import 'package:go_router/go_router.dart'; + part 'plan_create_event.dart'; part 'plan_create_state.dart'; @@ -31,21 +32,27 @@ class PlanCreateBloc extends Bloc { } if (state is PlanCreateLoadedState) { var currentState = state as PlanCreateLoadedState; - emit(currentState.copyWith( - planModelObj: currentState.planModelObj, - name: currentState.name, - details: currentState.details, - ),); + emit( + currentState.copyWith( + planModelObj: currentState.planModelObj, + name: currentState.name, + details: currentState.details, + ), + ); } else { - emit(PlanCreateLoadedState( - name: TextEditingController(), - details: TextEditingController(), - ),); + emit( + PlanCreateLoadedState( + name: TextEditingController(), + details: TextEditingController(), + ), + ); } } FutureOr _createPlan( - CreatePlan event, Emitter emit,) async { + CreatePlan event, + Emitter emit, + ) async { if (state is PlanCreateLoadedState) { var currentState = state as PlanCreateLoadedState; @@ -58,7 +65,8 @@ class PlanCreateBloc extends Bloc { AppRouter.navigatorKey.currentContext?.goNamed('planSelectScreen'); } else { print( - 'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}',); + 'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}', + ); } } } @@ -67,7 +75,7 @@ class PlanCreateBloc extends Bloc { String? name, String? details, ) async { - String url = '${dotenv.env['SERVER_ROOT']!}/plans/create'; + String url = '${baseUrl}/api/plans/create'; final Map credentials = { 'name': name, diff --git a/lib/presentation/plans/plan_create_screen/bloc/plan_create_state.dart b/lib/presentation/plans/plan_create_screen/bloc/plan_create_state.dart index 93e4aaf2..4e98812c 100644 --- a/lib/presentation/plans/plan_create_screen/bloc/plan_create_state.dart +++ b/lib/presentation/plans/plan_create_screen/bloc/plan_create_state.dart @@ -60,6 +60,5 @@ class PlanCreateErrorState extends PlanCreateState { } class PlanCreateInitialState extends PlanCreateState { - PlanCreateInitialState({required PlanCreateModel planModelObj}) - : super(planModelObj: planModelObj); + PlanCreateInitialState({required PlanCreateModel planModelObj}) : super(planModelObj: planModelObj); } diff --git a/lib/presentation/plans/plan_create_screen/plan_create_screen.dart b/lib/presentation/plans/plan_create_screen/plan_create_screen.dart index 81262591..165be86b 100644 --- a/lib/presentation/plans/plan_create_screen/plan_create_screen.dart +++ b/lib/presentation/plans/plan_create_screen/plan_create_screen.dart @@ -1,16 +1,18 @@ -import 'bloc/plan_create_bloc.dart'; -import 'models/plan_create_model.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:flutter/material.dart'; +import 'bloc/plan_create_bloc.dart'; +import 'models/plan_create_model.dart'; + class PlanCreateScreen extends StatelessWidget { const PlanCreateScreen({Key? key}) : super(key: key); static Widget builder(BuildContext context) { final planID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( - create: (context) => PlanCreateBloc(PlanCreateState(planModelObj: PlanCreateModel(planID: planID.toString())))..add(PlanCreateInitialEvent()), - child: PlanCreateScreen(),); + create: (context) => PlanCreateBloc(PlanCreateState(planModelObj: PlanCreateModel(planID: planID.toString())))..add(PlanCreateInitialEvent()), + child: PlanCreateScreen(), + ); } Widget build(BuildContext context) { @@ -65,24 +67,27 @@ class PlanCreateScreen extends StatelessWidget { ), ], ), - child: Column(mainAxisSize: MainAxisSize.min, children: [ - SizedBox(height: 16.0), - TextFormField( - controller: state.name, - decoration: InputDecoration(labelText: 'Заголовок'), - ), - SizedBox(height: 16.0), - TextFormField( - controller: state.details, - decoration: InputDecoration(labelText: 'Описание'), - ), - SizedBox(height: 16.0), - // Здесь нужно добавить виджет для загрузки картинки - ElevatedButton( - onPressed: () => context.read().add(CreatePlan()), - child: Text('Создать'), - ), - ],), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox(height: 16.0), + TextFormField( + controller: state.name, + decoration: InputDecoration(labelText: 'Заголовок'), + ), + SizedBox(height: 16.0), + TextFormField( + controller: state.details, + decoration: InputDecoration(labelText: 'Описание'), + ), + SizedBox(height: 16.0), + // Здесь нужно добавить виджет для загрузки картинки + ElevatedButton( + onPressed: () => context.read().add(CreatePlan()), + child: Text('Создать'), + ), + ], + ), ), ], ), diff --git a/lib/presentation/plans/plan_edit_screen/bloc/plan_edit_bloc.dart b/lib/presentation/plans/plan_edit_screen/bloc/plan_edit_bloc.dart index e150c8bc..5987b6bd 100644 --- a/lib/presentation/plans/plan_edit_screen/bloc/plan_edit_bloc.dart +++ b/lib/presentation/plans/plan_edit_screen/bloc/plan_edit_bloc.dart @@ -1,18 +1,17 @@ import 'dart:async'; +import 'dart:convert'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/presentation/plans/plan_edit_screen/models/plan_edit_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:go_router/go_router.dart'; import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; -import 'dart:convert'; + import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/plans/plan_edit_screen/models/plan_edit_model.dart'; -import 'package:go_router/go_router.dart'; part 'plan_edit_event.dart'; - part 'plan_edit_state.dart'; /// A bloc that manages the state of a PlanEdit according to the event that is dispatched to it. @@ -34,7 +33,7 @@ class PlanEditBloc extends Bloc { } final String? planID = state.planModelObj?.planID; final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/plans/show/$planID'), + Uri.parse(baseUrl + '/api/plans/show/$planID'), headers: { 'Authorization': 'Bearer $token', }, @@ -44,18 +43,24 @@ class PlanEditBloc extends Bloc { if (data is Map) { if (state is PlanEditLoadedState) { var currentState = state as PlanEditLoadedState; - emit(currentState.copyWith( + emit( + currentState.copyWith( planModelObj: currentState.planModelObj, plan: currentState.plan, name: currentState.name, duration: currentState.duration, - details: currentState.details,),); + details: currentState.details, + ), + ); } else { - emit(PlanEditLoadedState( + emit( + PlanEditLoadedState( plan: data, name: TextEditingController(text: data['name']), details: TextEditingController(text: data['details']), - duration: TextEditingController(text: data['duration'].toString()),),); + duration: TextEditingController(text: data['duration'].toString()), + ), + ); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку @@ -96,7 +101,7 @@ class PlanEditBloc extends Bloc { String? duration, ) async { int id = plan?['id']; - String url = '${dotenv.env['SERVER_ROOT']!}/plans/update/$id'; + String url = '${baseUrl}/api/plans/update/$id'; final Map credentials = { 'id': id, diff --git a/lib/presentation/plans/plan_edit_screen/bloc/plan_edit_state.dart b/lib/presentation/plans/plan_edit_screen/bloc/plan_edit_state.dart index 66769622..e3cf6b85 100644 --- a/lib/presentation/plans/plan_edit_screen/bloc/plan_edit_state.dart +++ b/lib/presentation/plans/plan_edit_screen/bloc/plan_edit_state.dart @@ -22,8 +22,13 @@ class PlanEditState extends Equatable { } class PlanEditLoadedState extends PlanEditState { - PlanEditLoadedState( - {this.planModelObj, this.plan, this.name, this.details, this.duration,}); + PlanEditLoadedState({ + this.planModelObj, + this.plan, + this.name, + this.details, + this.duration, + }); PlanEditModel? planModelObj; Map? plan; @@ -59,6 +64,5 @@ class PlanEditErrorState extends PlanEditState { } class PlanEditInitialState extends PlanEditState { - PlanEditInitialState({required PlanEditModel planModelObj}) - : super(planModelObj: planModelObj); + PlanEditInitialState({required PlanEditModel planModelObj}) : super(planModelObj: planModelObj); } diff --git a/lib/presentation/plans/plan_edit_screen/plan_edit_screen.dart b/lib/presentation/plans/plan_edit_screen/plan_edit_screen.dart index abea8b9a..c7005746 100644 --- a/lib/presentation/plans/plan_edit_screen/plan_edit_screen.dart +++ b/lib/presentation/plans/plan_edit_screen/plan_edit_screen.dart @@ -1,9 +1,9 @@ -import 'bloc/plan_edit_bloc.dart'; -import 'models/plan_edit_model.dart'; +import 'package:cached_network_image/cached_network_image.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:flutter/material.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; + +import 'bloc/plan_edit_bloc.dart'; +import 'models/plan_edit_model.dart'; class PlanEditScreen extends StatelessWidget { const PlanEditScreen({Key? key}) : super(key: key); @@ -11,8 +11,9 @@ class PlanEditScreen extends StatelessWidget { static Widget builder(BuildContext context) { final planID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( - create: (context) => PlanEditBloc(PlanEditState(planModelObj: PlanEditModel(planID: planID.toString())))..add(PlanEditInitialEvent()), - child: PlanEditScreen(),); + create: (context) => PlanEditBloc(PlanEditState(planModelObj: PlanEditModel(planID: planID.toString())))..add(PlanEditInitialEvent()), + child: PlanEditScreen(), + ); } Widget build(BuildContext context) { @@ -71,7 +72,7 @@ class PlanEditScreen extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (state.plan?['image'] ?? ''), + imageUrl: baseUrl + '/storage/' + (state.plan?['image'] ?? ''), imageBuilder: (context, imageProvider) => CircleAvatar( backgroundImage: imageProvider, radius: 25, diff --git a/lib/presentation/plans/plan_select_screen/bloc/plan_select_bloc.dart b/lib/presentation/plans/plan_select_screen/bloc/plan_select_bloc.dart index e65409f1..dcf60700 100644 --- a/lib/presentation/plans/plan_select_screen/bloc/plan_select_bloc.dart +++ b/lib/presentation/plans/plan_select_screen/bloc/plan_select_bloc.dart @@ -1,17 +1,17 @@ //import 'package:eatvio_app/presentation/auth/auth_screen/auth_screen.dart'; import 'dart:async'; +import 'dart:convert'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/presentation/plans/plan_select_screen/models/plan_select_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/plans/plan_select_screen/models/plan_select_model.dart'; -import 'package:http/http.dart' as http; -import 'dart:convert'; -import 'package:hive/hive.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:image_picker/image_picker.dart'; import 'package:go_router/go_router.dart'; +import 'package:hive/hive.dart'; +import 'package:http/http.dart' as http; +import 'package:image_picker/image_picker.dart'; + +import '/core/app_export.dart'; part 'plan_select_event.dart'; part 'plan_select_state.dart'; @@ -33,7 +33,7 @@ class PlanSelectBloc extends Bloc { AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); } final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/plans/index'), + Uri.parse(baseUrl + '/api/plans/index'), ); print('Got response'); if (response.statusCode == 200) { @@ -44,15 +44,19 @@ class PlanSelectBloc extends Bloc { if (state is PlanSelectLoadedState) { print('Got loaded'); var currentState = state as PlanSelectLoadedState; - emit((currentState).copyWith( - posts: data, - myProfileModelObj: currentState.myProfileModelObj, - ),); + emit( + (currentState).copyWith( + posts: data, + myProfileModelObj: currentState.myProfileModelObj, + ), + ); } else { print('Got unloaded'); - emit(PlanSelectLoadedState( - posts: data, - ),); + emit( + PlanSelectLoadedState( + posts: data, + ), + ); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку diff --git a/lib/presentation/plans/plan_select_screen/bloc/plan_select_state.dart b/lib/presentation/plans/plan_select_screen/bloc/plan_select_state.dart index 5ab68c28..2c8561b0 100644 --- a/lib/presentation/plans/plan_select_screen/bloc/plan_select_state.dart +++ b/lib/presentation/plans/plan_select_screen/bloc/plan_select_state.dart @@ -12,14 +12,12 @@ class PlanSelectState extends Equatable { } class PlanSelectInitialState extends PlanSelectState { - PlanSelectInitialState({required PlanSelectModel myProfileModelObj}) - : super(myProfileModelObj: myProfileModelObj); + PlanSelectInitialState({required PlanSelectModel myProfileModelObj}) : super(myProfileModelObj: myProfileModelObj); } /// Represents the state of PlanSelect in the application. class PlanSelectLoadedState extends PlanSelectState { - PlanSelectLoadedState({this.myProfileModelObj, this.posts}) - : super(myProfileModelObj: null); + PlanSelectLoadedState({this.myProfileModelObj, this.posts}) : super(myProfileModelObj: null); PlanSelectModel? myProfileModelObj; List? posts; diff --git a/lib/presentation/plans/plan_select_screen/plan_select_screen.dart b/lib/presentation/plans/plan_select_screen/plan_select_screen.dart index 022e4e2e..1508c75e 100644 --- a/lib/presentation/plans/plan_select_screen/plan_select_screen.dart +++ b/lib/presentation/plans/plan_select_screen/plan_select_screen.dart @@ -1,19 +1,20 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart'; +import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; +import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'bloc/plan_select_bloc.dart'; import 'models/plan_select_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter/material.dart'; class PlanSelectScreen extends StatelessWidget { static Widget builder(BuildContext context) { return BlocProvider( - create: (context) => PlanSelectBloc(PlanSelectState(myProfileModelObj: PlanSelectModel()))..add(PlanSelectInitialEvent()), child: PlanSelectScreen(),); + create: (context) => PlanSelectBloc(PlanSelectState(myProfileModelObj: PlanSelectModel()))..add(PlanSelectInitialEvent()), + child: PlanSelectScreen(), + ); } Widget build(BuildContext context) { @@ -133,7 +134,7 @@ class PlanSelectScreen extends StatelessWidget { ), child: ListTile( leading: CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + post['image'], + imageUrl: baseUrl + '/storage/' + post['image'], imageBuilder: (context, imageProvider) => CircleAvatar( backgroundImage: imageProvider, radius: 25, diff --git a/lib/presentation/plans/plan_show_screen/bloc/plan_show_bloc.dart b/lib/presentation/plans/plan_show_screen/bloc/plan_show_bloc.dart index e920db89..ad9a7a43 100644 --- a/lib/presentation/plans/plan_show_screen/bloc/plan_show_bloc.dart +++ b/lib/presentation/plans/plan_show_screen/bloc/plan_show_bloc.dart @@ -1,18 +1,17 @@ import 'dart:async'; +import 'dart:convert'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/presentation/plans/plan_show_screen/models/plan_show_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:go_router/go_router.dart'; import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; -import 'dart:convert'; + import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/plans/plan_show_screen/models/plan_show_model.dart'; -import 'package:go_router/go_router.dart'; part 'plan_show_event.dart'; - part 'plan_show_state.dart'; /// A bloc that manages the state of a Plan according to the event that is dispatched to it. @@ -34,7 +33,7 @@ class PlanBloc extends Bloc { } final String? planID = state.planModelObj?.planID; final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/plans/show/$planID'), + Uri.parse(baseUrl + '/api/plans/show/$planID'), headers: { 'Authorization': 'Bearer $token', }, @@ -70,7 +69,7 @@ class PlanBloc extends Bloc { } final int id = event.id; final response = await http.post( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/plans/delete/$id'), + Uri.parse(baseUrl + '/api/plans/delete/$id'), headers: { 'Authorization': 'Bearer $token', }, diff --git a/lib/presentation/plans/plan_show_screen/bloc/plan_show_state.dart b/lib/presentation/plans/plan_show_screen/bloc/plan_show_state.dart index cefb6cf6..50527102 100644 --- a/lib/presentation/plans/plan_show_screen/bloc/plan_show_state.dart +++ b/lib/presentation/plans/plan_show_screen/bloc/plan_show_state.dart @@ -28,8 +28,7 @@ class PlanLoadedState extends PlanState { Map? plan; @override List get props => [planModelObj, plan]; - PlanLoadedState copyWith( - {PlanModel? planModelObj, Map? plan}) { + PlanLoadedState copyWith({PlanModel? planModelObj, Map? plan}) { return PlanLoadedState( planModelObj: planModelObj ?? this.planModelObj, plan: plan ?? this.plan, @@ -47,6 +46,5 @@ class PlanErrorState extends PlanState { } class PlanInitialState extends PlanState { - PlanInitialState({required PlanModel planModelObj}) - : super(planModelObj: planModelObj); + PlanInitialState({required PlanModel planModelObj}) : super(planModelObj: planModelObj); } diff --git a/lib/presentation/plans/plan_show_screen/plan_show_screen.dart b/lib/presentation/plans/plan_show_screen/plan_show_screen.dart index 98cefd46..bf618680 100644 --- a/lib/presentation/plans/plan_show_screen/plan_show_screen.dart +++ b/lib/presentation/plans/plan_show_screen/plan_show_screen.dart @@ -1,12 +1,10 @@ - +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:eatvio_app/core/app_export.dart'; +import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'bloc/plan_show_bloc.dart'; import 'models/plan_show_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:flutter/material.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; class PlanScreen extends StatelessWidget { const PlanScreen({Key? key}) : super(key: key); @@ -14,7 +12,9 @@ class PlanScreen extends StatelessWidget { static Widget builder(BuildContext context) { final planID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( - create: (context) => PlanBloc(PlanState(planModelObj: PlanModel(planID: planID.toString())))..add(PlanInitialEvent()), child: PlanScreen(),); + create: (context) => PlanBloc(PlanState(planModelObj: PlanModel(planID: planID.toString())))..add(PlanInitialEvent()), + child: PlanScreen(), + ); } Widget build(BuildContext context) { @@ -69,43 +69,46 @@ class PlanScreen extends StatelessWidget { ), ], ), - child: Column(mainAxisSize: MainAxisSize.min, children: [ - CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (state.plan?['image'] ?? ''), - imageBuilder: (context, imageProvider) => CircleAvatar( - backgroundImage: imageProvider, - radius: 25, - ), - placeholder: (context, url) => CircularProgressIndicator(), - errorWidget: (context, url, error) => CircleAvatar( - child: Icon(Icons.person), - backgroundColor: Colors.white, - radius: 25, - ), - ), - SizedBox(height: 16.0), - Text(state.plan?['name'], style: CustomTextStyles.titleMediumBlack), - SizedBox(height: 8.0), - Text( - state.plan?['details'], - ), - SizedBox(height: 16.0), - Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - ElevatedButton( - onPressed: () { - // Действие для редактирования - }, - child: Text('Редактировать'), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + CachedNetworkImage( + imageUrl: baseUrl + '/storage/' + (state.plan?['image'] ?? ''), + imageBuilder: (context, imageProvider) => CircleAvatar( + backgroundImage: imageProvider, + radius: 25, ), - ElevatedButton( - onPressed: () => context.read().add(DeleteEntry(state.plan?['id'])), - child: Text('Удалить'), + placeholder: (context, url) => CircularProgressIndicator(), + errorWidget: (context, url, error) => CircleAvatar( + child: Icon(Icons.person), + backgroundColor: Colors.white, + radius: 25, ), - ], - ), - ],), + ), + SizedBox(height: 16.0), + Text(state.plan?['name'], style: CustomTextStyles.titleMediumBlack), + SizedBox(height: 8.0), + Text( + state.plan?['details'], + ), + SizedBox(height: 16.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + ElevatedButton( + onPressed: () { + // Действие для редактирования + }, + child: Text('Редактировать'), + ), + ElevatedButton( + onPressed: () => context.read().add(DeleteEntry(state.plan?['id'])), + child: Text('Удалить'), + ), + ], + ), + ], + ), ), ], ), 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 806768cf..8b01f618 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,17 +1,17 @@ //import 'package:eatvio_app/presentation/auth/auth_screen/auth_screen.dart'; import 'dart:async'; +import 'dart:convert'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/presentation/profile/my_profile_screen/models/my_profile_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -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:flutter_dotenv/flutter_dotenv.dart'; -import 'package:image_picker/image_picker.dart'; import 'package:go_router/go_router.dart'; +import 'package:hive/hive.dart'; +import 'package:http/http.dart' as http; +import 'package:image_picker/image_picker.dart'; + +import '/core/app_export.dart'; part 'my_profile_event.dart'; part 'my_profile_state.dart'; @@ -36,7 +36,7 @@ class MyProfileBloc extends Bloc { //final token = // "9|laravel_sanctum_KFXbccDcWEvTPfJmV99EQv1ne AggmpR2TidVGDPN34fa201a"; final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/profile/index'), + Uri.parse(baseUrl + '/api/profile/index'), headers: { 'Authorization': 'Bearer $token', }, @@ -74,20 +74,16 @@ class MyProfileBloc extends Bloc { waistCircumferenceController: TextEditingController(), hipCircumferenceController: TextEditingController(), weightController: TextEditingController(), - chestCircumferenceFormController: - currentState.chestCircumferenceFormController, - waistCircumferenceFormController: - currentState.waistCircumferenceFormController, - hipCircumferenceFormController: - currentState.hipCircumferenceFormController, + chestCircumferenceFormController: currentState.chestCircumferenceFormController, + waistCircumferenceFormController: currentState.waistCircumferenceFormController, + hipCircumferenceFormController: currentState.hipCircumferenceFormController, firstNameFormController: currentState.firstNameFormController, lastNameFormController: currentState.lastNameFormController, countryFormController: currentState.countryFormController, cityFormController: currentState.cityFormController, heightFormController: currentState.heightFormController, upPressureFormController: currentState.upPressureFormController, - downPressureFormController: - currentState.downPressureFormController, + downPressureFormController: currentState.downPressureFormController, allergiesFormController: currentState.allergiesFormController, pillsFormController: currentState.pillsFormController, favoriteFormController: currentState.favoriteFormController, @@ -181,8 +177,7 @@ class MyProfileBloc extends Bloc { waistCircumferenceController: TextEditingController(), hipCircumferenceController: TextEditingController(), hypoFormController: data['userDetails']['has_hypo'].toString(), - hyperFormController: - data['userDetails']['has_hyper'].toString(), + hyperFormController: data['userDetails']['has_hyper'].toString(), chestCircumferenceFormController: TextEditingController( text: data['userDetails']['chest_circumference']?.toString(), ), @@ -201,12 +196,9 @@ class MyProfileBloc extends Bloc { firstNameFormController: TextEditingController( text: data['userDetails']['first_name'], ), - lastNameFormController: TextEditingController( - text: data['userDetails']['last_name']), - countryFormController: - TextEditingController(text: data['userDetails']['country']), - cityFormController: - TextEditingController(text: data['userDetails']['city']), + lastNameFormController: TextEditingController(text: data['userDetails']['last_name']), + countryFormController: TextEditingController(text: data['userDetails']['country']), + cityFormController: TextEditingController(text: data['userDetails']['city']), heightFormController: TextEditingController( text: data['userDetails']['height']?.toString(), ), @@ -234,8 +226,7 @@ class MyProfileBloc extends Bloc { additionalFormController: TextEditingController( text: data['userDetails']['additional_info'], ), - dateFormController: TextEditingController( - text: data['userDetails']['birthdate']), + dateFormController: TextEditingController(text: data['userDetails']['birthdate']), selectedCity: data['userDetails']['city'], selectedCountry: data['userDetails']['country'], selectedActivity: determineActivityLevel( @@ -282,11 +273,12 @@ class MyProfileBloc extends Bloc { var currentState = state as MyProfileLoadedState; await uploadImageToServer(event.image.path, currentState.token); + this.add(MyProfileInitialEvent()); } } Future uploadImageToServer(String imagePath, String? token) async { - String url = '${dotenv.env['SERVER_ROOT']!}/profile/photo/upload'; + String url = '${baseUrl}/api/profile/photo/upload'; print(url); var request = http.MultipartRequest('POST', Uri.parse(url)); request.headers['Authorization'] = 'Bearer $token'; diff --git a/lib/presentation/profile/my_profile_screen/bloc/my_profile_state.dart b/lib/presentation/profile/my_profile_screen/bloc/my_profile_state.dart index 7c66b4c3..85c254d1 100644 --- a/lib/presentation/profile/my_profile_screen/bloc/my_profile_state.dart +++ b/lib/presentation/profile/my_profile_screen/bloc/my_profile_state.dart @@ -12,49 +12,48 @@ class MyProfileState extends Equatable { } class MyProfileInitialState extends MyProfileState { - MyProfileInitialState({required MyProfileModel myProfileModelObj}) - : super(myProfileModelObj: myProfileModelObj); + MyProfileInitialState({required MyProfileModel myProfileModelObj}) : super(myProfileModelObj: myProfileModelObj); } /// Represents the state of MyProfile in the application. class MyProfileLoadedState extends MyProfileState { - MyProfileLoadedState( - {this.chestCircumferenceController, - this.waistCircumferenceController, - this.hipCircumferenceController, - this.myProfileModelObj, - this.weightController, - this.user, - this.userDetails, - this.chartPoints, - this.chartDates, - this.plans, - this.token, - this.selectedCountry, - this.selectedCity, - this.selectedActivity, - this.chestCircumferenceFormController, - this.waistCircumferenceFormController, - this.hipCircumferenceFormController, - this.firstNameFormController, - this.lastNameFormController, - this.countryFormController, - this.dateFormController, - this.cityFormController, - this.heightFormController, - this.weightFormController, - this.upPressureFormController, - this.downPressureFormController, - this.allergiesFormController, - this.pillsFormController, - this.sportsFormController, - this.favoriteFormController, - this.unfavoriteFormController, - this.additionalFormController, - this.hypoFormController, - this.hyperFormController, - this.circumferences,}) - : super(myProfileModelObj: null); + MyProfileLoadedState({ + this.chestCircumferenceController, + this.waistCircumferenceController, + this.hipCircumferenceController, + this.myProfileModelObj, + this.weightController, + this.user, + this.userDetails, + this.chartPoints, + this.chartDates, + this.plans, + this.token, + this.selectedCountry, + this.selectedCity, + this.selectedActivity, + this.chestCircumferenceFormController, + this.waistCircumferenceFormController, + this.hipCircumferenceFormController, + this.firstNameFormController, + this.lastNameFormController, + this.countryFormController, + this.dateFormController, + this.cityFormController, + this.heightFormController, + this.weightFormController, + this.upPressureFormController, + this.downPressureFormController, + this.allergiesFormController, + this.pillsFormController, + this.sportsFormController, + this.favoriteFormController, + this.unfavoriteFormController, + this.additionalFormController, + this.hypoFormController, + this.hyperFormController, + this.circumferences, + }) : super(myProfileModelObj: null); MyProfileModel? myProfileModelObj; Map? user; @@ -174,42 +173,27 @@ class MyProfileLoadedState extends MyProfileState { chartPoints: chartPoints ?? this.chartPoints, chartDates: chartDates ?? this.chartDates, weightController: weightController ?? this.weightController, - chestCircumferenceController: - chestCircumferenceController ?? this.chestCircumferenceController, - waistCircumferenceController: - waistCircumferenceController ?? this.waistCircumferenceController, - hipCircumferenceController: - hipCircumferenceController ?? this.hipCircumferenceController, - chestCircumferenceFormController: chestCircumferenceFormController ?? - this.chestCircumferenceFormController, - waistCircumferenceFormController: waistCircumferenceFormController ?? - this.waistCircumferenceFormController, - hipCircumferenceFormController: - hipCircumferenceFormController ?? this.hipCircumferenceFormController, - firstNameFormController: - firstNameFormController ?? this.firstNameFormController, - lastNameFormController: - lastNameFormController ?? this.lastNameFormController, - countryFormController: - countryFormController ?? this.countryFormController, + chestCircumferenceController: chestCircumferenceController ?? this.chestCircumferenceController, + waistCircumferenceController: waistCircumferenceController ?? this.waistCircumferenceController, + hipCircumferenceController: hipCircumferenceController ?? this.hipCircumferenceController, + chestCircumferenceFormController: chestCircumferenceFormController ?? this.chestCircumferenceFormController, + waistCircumferenceFormController: waistCircumferenceFormController ?? this.waistCircumferenceFormController, + hipCircumferenceFormController: hipCircumferenceFormController ?? this.hipCircumferenceFormController, + firstNameFormController: firstNameFormController ?? this.firstNameFormController, + lastNameFormController: lastNameFormController ?? this.lastNameFormController, + countryFormController: countryFormController ?? this.countryFormController, dateFormController: dateFormController ?? this.dateFormController, cityFormController: cityFormController ?? this.cityFormController, heightFormController: heightFormController ?? this.heightFormController, weightFormController: weightFormController ?? this.weightFormController, - upPressureFormController: - upPressureFormController ?? this.upPressureFormController, - downPressureFormController: - downPressureFormController ?? this.downPressureFormController, - allergiesFormController: - allergiesFormController ?? this.allergiesFormController, + upPressureFormController: upPressureFormController ?? this.upPressureFormController, + downPressureFormController: downPressureFormController ?? this.downPressureFormController, + allergiesFormController: allergiesFormController ?? this.allergiesFormController, pillsFormController: pillsFormController ?? this.pillsFormController, sportsFormController: sportsFormController ?? this.sportsFormController, - favoriteFormController: - favoriteFormController ?? this.favoriteFormController, - unfavoriteFormController: - unfavoriteFormController ?? this.unfavoriteFormController, - additionalFormController: - additionalFormController ?? this.additionalFormController, + favoriteFormController: favoriteFormController ?? this.favoriteFormController, + unfavoriteFormController: unfavoriteFormController ?? this.unfavoriteFormController, + additionalFormController: additionalFormController ?? this.additionalFormController, token: token ?? this.token, selectedCountry: selectedCountry ?? this.selectedCountry, selectedCity: selectedCity ?? this.selectedCity, 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 8df32943..3aa1f640 100644 --- a/lib/presentation/profile/my_profile_screen/my_profile_screen.dart +++ b/lib/presentation/profile/my_profile_screen/my_profile_screen.dart @@ -1,21 +1,21 @@ -import 'package:go_router/go_router.dart'; +import 'dart:convert'; +import 'dart:math'; -import 'bloc/my_profile_bloc.dart'; -import 'models/my_profile_model.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:carousel_slider/carousel_slider.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart'; import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:carousel_slider/carousel_slider.dart'; -import 'package:image_picker/image_picker.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter/services.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:http/http.dart' as http; import 'package:fl_chart/fl_chart.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:go_router/go_router.dart'; +import 'package:http/http.dart' as http; +import 'package:image_picker/image_picker.dart'; import 'package:intl/intl.dart'; -import 'dart:math'; -import 'dart:convert'; + +import 'bloc/my_profile_bloc.dart'; +import 'models/my_profile_model.dart'; class MyProfileScreen extends StatelessWidget { static Widget builder(BuildContext context) { @@ -96,6 +96,27 @@ class MyProfileScreen extends StatelessWidget { ), SizedBox(height: 15.v), Container( + 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), + ), + ], + ), + child: _buildCarousel(context, state), + ), + SizedBox(height: 15.v), + if (!state.plans!.isEmpty) + Container( padding: EdgeInsets.symmetric( horizontal: 24.h, vertical: 12.v, @@ -112,32 +133,13 @@ class MyProfileScreen extends StatelessWidget { ), ], ), - child: _buildCarousel(context, state),), - SizedBox(height: 15.v), - if (!state.plans!.isEmpty) - Container( - 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), - ), - ], - ), - child: _buildPlans( - context, - state.plans?.map((plan) => plan['name']).toList(), - state.plans?.map((plan) => plan['image']).toList(), - state.plans?.map((plan) => plan['state']).toList(), - ),), + child: _buildPlans( + context, + state.plans?.map((plan) => plan['name']).toList(), + state.plans?.map((plan) => plan['image']).toList(), + state.plans?.map((plan) => plan['state']).toList(), + ), + ), SizedBox(height: 5.v), ], ), @@ -154,7 +156,7 @@ class MyProfileScreen extends StatelessWidget { GestureDetector( onTap: () => addImage(context), child: CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (state.user?['profile_photo_path'] ?? ''), + imageUrl: baseUrl + '/storage/' + (state.user?['profile_photo_path'] ?? ''), imageBuilder: (context, imageProvider) => CircleAvatar( backgroundImage: imageProvider, radius: 60, @@ -176,11 +178,9 @@ class MyProfileScreen extends StatelessWidget { addImage(BuildContext context) async { final picker = ImagePicker(); - List? images = await picker.pickMultiImage(); - if (images.isNotEmpty) { - for (var image in images) { - context.read().add(UploadAvatar(image)); - } + XFile? image = await picker.pickImage(source: ImageSource.gallery); + if (image != null) { + context.read().add(UploadAvatar(image)); } } @@ -199,8 +199,9 @@ class MyProfileScreen extends StatelessWidget { switch (chartType) { case 1: // График веса return GestureDetector( - onTap: () => _editWeight(context, state), - child: Column(children: [ + onTap: () => _editWeight(context, state), + child: Column( + children: [ Text( "weight_chart".tr, style: CustomTextStyles.titleMediumBlack.copyWith( @@ -213,26 +214,34 @@ class MyProfileScreen extends StatelessWidget { state.chartPoints?.values.map((e) => e['weight']).toList().map((i) => i.toDouble()).toList() ?? [0.0, 0.0, 0.0, 0.0], state.chartDates, ), - ],),); - case 2: // График ИМТ - return Column(children: [ - Text( - "bodymass_chart".tr, - style: CustomTextStyles.titleMediumBlack.copyWith( - color: appTheme.black900, - ), + ], ), - SizedBox(height: 50.v), - _buildChart( + ); + case 2: // График ИМТ + return Column( + children: [ + Text( + "bodymass_chart".tr, + style: CustomTextStyles.titleMediumBlack.copyWith( + color: appTheme.black900, + ), + ), + SizedBox(height: 50.v), + _buildChart( context, - _bodyMassIndex(state.chartPoints?.values.map((e) => e['weight']).toList().map((i) => i.toDouble()).toList() ?? [0.0, 0.0, 0.0, 0.0], - state.userDetails?['height'].toInt() ?? 160,), - state.chartDates,), - ],); + _bodyMassIndex( + state.chartPoints?.values.map((e) => e['weight']).toList().map((i) => i.toDouble()).toList() ?? [0.0, 0.0, 0.0, 0.0], + state.userDetails?['height'].toInt() ?? 160, + ), + state.chartDates, + ), + ], + ); case 3: //График обхватов return GestureDetector( - onTap: () => _editCircumference(context, state), - child: Column(children: [ + onTap: () => _editCircumference(context, state), + child: Column( + children: [ Text( "circumferences_chart".tr, style: CustomTextStyles.titleMediumBlack.copyWith( @@ -242,7 +251,9 @@ class MyProfileScreen extends StatelessWidget { SizedBox(height: 30.v), _buildCircumferenceChart(context, state.circumferences, state.chartDates), _buildChartLegend(), - ],),); + ], + ), + ); default: return Text('text', style: TextStyle(fontSize: 16.0)); } @@ -636,79 +647,108 @@ class MyProfileScreen extends StatelessWidget { /// Section Widget _buildPlans(BuildContext context, List? plans, List? imagePaths, List? states) { return Padding( - padding: EdgeInsets.only(left: 7.h), - child: Column(children: [ + padding: EdgeInsets.only(left: 7.h), + child: Column( + children: [ Padding( - padding: EdgeInsets.only(left: 15.h), - child: Text("plans_complete".tr, style: CustomTextStyles.titleMediumBlack.copyWith(color: appTheme.black900)),), + padding: EdgeInsets.only(left: 15.h), + child: Text("plans_complete".tr, style: CustomTextStyles.titleMediumBlack.copyWith(color: appTheme.black900)), + ), SizedBox(height: 5.v), Container( - decoration: AppDecoration.outlineBlueGray.copyWith(borderRadius: BorderRadiusStyle.roundedBorder5), - child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + decoration: AppDecoration.outlineBlueGray.copyWith(borderRadius: BorderRadiusStyle.roundedBorder5), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ SizedBox( - height: 105.v, - width: 343.h, - child: Stack(alignment: Alignment.bottomCenter, children: [ + height: 105.v, + width: 343.h, + child: Stack( + alignment: Alignment.bottomCenter, + children: [ Align( - alignment: Alignment.topCenter, - child: ListView.builder( - itemCount: plans?.length ?? 0, - itemBuilder: (context, i) { - String state = states?[i]; - var boxColor = appTheme.greenA700; - switch (states?[i]) { - case 'active': - boxColor = appTheme.greenA700; - break; - case 'archived': // График ИМТ - boxColor = appTheme.gray400; - break; - case 'draft': - boxColor = appTheme.deepOrange900; - break; - case 'in_progress': //График обхватов - boxColor = appTheme.lightGreen300; - break; - } - return SizedBox( - height: 40.v, - width: 343.h, - child: Stack(alignment: Alignment.bottomRight, children: [ - Align( - alignment: Alignment.topCenter, - child: Container( - margin: EdgeInsets.only(bottom: 11.v), - padding: EdgeInsets.symmetric(horizontal: 6.h, vertical: 4.v), - decoration: AppDecoration.fillGray.copyWith(borderRadius: BorderRadiusStyle.roundedBorder5), - child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Padding( - padding: EdgeInsets.only(bottom: 1.v), - child: Text(plans![i], style: CustomTextStyles.titleSmallBluegray800Bold),), - Container( - height: 19.v, - width: 100.h, - decoration: BoxDecoration(color: boxColor, borderRadius: BorderRadius.circular(5.h)),), - ],),),), - Align( - alignment: Alignment.center, - child: Container( - margin: EdgeInsets.only(bottom: 12.h), - child: Image.network( - dotenv.env['STORAGE_URL']! + imagePaths?[i], - height: 25.adaptSize, - width: 25.adaptSize, - ),),), - Align( - alignment: Alignment.bottomRight, - child: Container( - width: 70.h, - margin: EdgeInsets.only(bottom: 14.h, right: 22.h), - child: Text("$state".tr, maxLines: 3, overflow: TextOverflow.ellipsis, style: theme.textTheme.titleSmall),),), - ],),); - },),), - ],),), - ],),), - ],),); + alignment: Alignment.topCenter, + child: ListView.builder( + itemCount: plans?.length ?? 0, + itemBuilder: (context, i) { + String state = states?[i]; + var boxColor = appTheme.greenA700; + switch (states?[i]) { + case 'active': + boxColor = appTheme.greenA700; + break; + case 'archived': // График ИМТ + boxColor = appTheme.gray400; + break; + case 'draft': + boxColor = appTheme.deepOrange900; + break; + case 'in_progress': //График обхватов + boxColor = appTheme.lightGreen300; + break; + } + return SizedBox( + height: 40.v, + width: 343.h, + child: Stack( + alignment: Alignment.bottomRight, + children: [ + Align( + alignment: Alignment.topCenter, + child: Container( + margin: EdgeInsets.only(bottom: 11.v), + padding: EdgeInsets.symmetric(horizontal: 6.h, vertical: 4.v), + decoration: AppDecoration.fillGray.copyWith(borderRadius: BorderRadiusStyle.roundedBorder5), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Padding( + padding: EdgeInsets.only(bottom: 1.v), + child: Text(plans![i], style: CustomTextStyles.titleSmallBluegray800Bold), + ), + Container( + height: 19.v, + width: 100.h, + decoration: BoxDecoration(color: boxColor, borderRadius: BorderRadius.circular(5.h)), + ), + ], + ), + ), + ), + Align( + alignment: Alignment.center, + child: Container( + margin: EdgeInsets.only(bottom: 12.h), + child: Image.network( + baseUrl + '/storage/' + imagePaths?[i], + height: 25.adaptSize, + width: 25.adaptSize, + ), + ), + ), + Align( + alignment: Alignment.bottomRight, + child: Container( + width: 70.h, + margin: EdgeInsets.only(bottom: 14.h, right: 22.h), + child: Text("$state".tr, maxLines: 3, overflow: TextOverflow.ellipsis, style: theme.textTheme.titleSmall), + ), + ), + ], + ), + ); + }, + ), + ), + ], + ), + ), + ], + ), + ), + ], + ), + ); } List _bodyMassIndex(List weightPoints, int height) { @@ -729,48 +769,49 @@ class MyProfileScreen extends StatelessWidget { title: Center(child: Text("Добавить замер")), content: SizedBox( - width: 200, // Ширина диалогового окна - height: 300, // Высота диалогового окна - child: ListView( - children: [ - Padding( - padding: EdgeInsets.symmetric(vertical: 5.v), - child: Text("chest_circumference".tr, style: theme.textTheme.bodyLarge), - ), - SizedBox(height: 5.v), - CustomTextFormField( - controller: state.chestCircumferenceController, - keyboardType: TextInputType.number, - inputFormatters: [ - FilteringTextInputFormatter.digitsOnly, // Ограничение ввода только цифрами - ], - ), - Padding( - padding: EdgeInsets.symmetric(vertical: 15.v), - child: Text("waist_circumference".tr, style: theme.textTheme.bodyLarge), - ), - SizedBox(height: 5.v), - CustomTextFormField( - controller: state.waistCircumferenceController, - keyboardType: TextInputType.number, - inputFormatters: [ - FilteringTextInputFormatter.digitsOnly, // Ограничение ввода только цифрами - ], - ), - Padding( - padding: EdgeInsets.symmetric(vertical: 15.v), - child: Text("hip_circumference".tr, style: theme.textTheme.bodyLarge), - ), - SizedBox(height: 5.v), - CustomTextFormField( - controller: state.hipCircumferenceController, - keyboardType: TextInputType.number, - inputFormatters: [ - FilteringTextInputFormatter.digitsOnly, // Ограничение ввода только цифрами - ], - ), - ], - ),), + width: 200, // Ширина диалогового окна + height: 300, // Высота диалогового окна + child: ListView( + children: [ + Padding( + padding: EdgeInsets.symmetric(vertical: 5.v), + child: Text("chest_circumference".tr, style: theme.textTheme.bodyLarge), + ), + SizedBox(height: 5.v), + CustomTextFormField( + controller: state.chestCircumferenceController, + keyboardType: TextInputType.number, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, // Ограничение ввода только цифрами + ], + ), + Padding( + padding: EdgeInsets.symmetric(vertical: 15.v), + child: Text("waist_circumference".tr, style: theme.textTheme.bodyLarge), + ), + SizedBox(height: 5.v), + CustomTextFormField( + controller: state.waistCircumferenceController, + keyboardType: TextInputType.number, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, // Ограничение ввода только цифрами + ], + ), + Padding( + padding: EdgeInsets.symmetric(vertical: 15.v), + child: Text("hip_circumference".tr, style: theme.textTheme.bodyLarge), + ), + SizedBox(height: 5.v), + CustomTextFormField( + controller: state.hipCircumferenceController, + keyboardType: TextInputType.number, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, // Ограничение ввода только цифрами + ], + ), + ], + ), + ), actions: [ TextButton( onPressed: onTapOk(context), @@ -778,10 +819,12 @@ class MyProfileScreen extends StatelessWidget { ), TextButton( onPressed: sendEditData(state, context), - child: Text("Изменить", - style: CustomTextStyles.titleMediumBlack.copyWith( - color: Colors.blue, - ),), + child: Text( + "Изменить", + style: CustomTextStyles.titleMediumBlack.copyWith( + color: Colors.blue, + ), + ), ), ], backgroundColor: Colors.white, @@ -806,7 +849,7 @@ class MyProfileScreen extends StatelessWidget { try { final token = state.token; final response = await http.post( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/profile/addCircumference'), + Uri.parse(baseUrl + '/api/profile/addCircumference'), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $token', @@ -824,6 +867,7 @@ class MyProfileScreen extends StatelessWidget { // Обработка ошибок при отправке запроса print("Ошибка при отправке запроса: $e"); } + Navigator.pop(context); }; } @@ -859,10 +903,12 @@ class MyProfileScreen extends StatelessWidget { ), TextButton( onPressed: () => saveWeight(state, context), - child: Text("Изменить", - style: CustomTextStyles.titleMediumBlack.copyWith( - color: Colors.blue, - ),), + child: Text( + "Изменить", + style: CustomTextStyles.titleMediumBlack.copyWith( + color: Colors.blue, + ), + ), ), ], backgroundColor: Colors.white, @@ -895,7 +941,7 @@ class MyProfileScreen extends StatelessWidget { try { final token = state.token; final response = await http.post( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/profile/addWeight'), + Uri.parse(baseUrl + '/api/profile/addWeight'), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $token', diff --git a/lib/presentation/profile/my_profile_screen/my_settings_screen.dart b/lib/presentation/profile/my_profile_screen/my_settings_screen.dart index cb3aeb60..4cd47b18 100644 --- a/lib/presentation/profile/my_profile_screen/my_settings_screen.dart +++ b/lib/presentation/profile/my_profile_screen/my_settings_screen.dart @@ -1,22 +1,24 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart'; +import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; +import 'package:eatvio_app/widgets/custom_about_list.dart'; +import 'package:eatvio_app/widgets/custom_expandable_list.dart'; +import 'package:eatvio_app/widgets/custom_language_drop_down.dart'; +import 'package:eatvio_app/widgets/custom_notification_screen.dart'; +import 'package:eatvio_app/widgets/custom_section_title.dart'; +import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'bloc/my_profile_bloc.dart'; import 'models/my_profile_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/custom_about_list.dart'; -import 'package:eatvio_app/widgets/custom_expandable_list.dart'; -import 'package:eatvio_app/widgets/custom_notification_screen.dart'; -import 'package:eatvio_app/widgets/custom_section_title.dart'; -import 'package:eatvio_app/widgets/custom_language_drop_down.dart'; -import 'package:flutter/material.dart'; class MySettingsScreen extends StatelessWidget { static Widget builder(BuildContext context) { return BlocProvider( - create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent()), child: MySettingsScreen(),); + create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent()), + child: MySettingsScreen(), + ); } Widget build(BuildContext context) { @@ -45,7 +47,6 @@ class MySettingsScreen extends StatelessWidget { } _buildSetingsScreen(BuildContext context, MyProfileLoadedState state) { - return Scaffold( appBar: AppBar( toolbarHeight: 0, @@ -64,30 +65,32 @@ class MySettingsScreen extends StatelessWidget { children: [ SizedBox(height: 30), Container( - 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), - ), - ], - ), - child: CustomAppBar( - height: 54.v, - leadingWidth: 28.h, - leading: AppbarLeadingImage( - imagePath: ImageConstant.imgArrowLeft, - margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), - onTap: () => GoRouter.of(context).pop(), + 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), ), - title: Padding( - padding: EdgeInsets.only(left: 20.h), - child: Row(children: [AppbarSubtitle(text: state.user?['name'], margin: EdgeInsets.only(left: 80.h, top: 12.v, bottom: 9.v))]),), - ),), + ], + ), + child: CustomAppBar( + height: 54.v, + leadingWidth: 28.h, + leading: AppbarLeadingImage( + imagePath: ImageConstant.imgArrowLeft, + margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), + onTap: () => GoRouter.of(context).pop(), + ), + title: Padding( + padding: EdgeInsets.only(left: 20.h), + child: Row(children: [AppbarSubtitle(text: state.user?['name'], margin: EdgeInsets.only(left: 80.h, top: 12.v, bottom: 9.v))]), + ), + ), + ), SizedBox(height: 20), Container( padding: EdgeInsets.symmetric( diff --git a/lib/presentation/recipe/recipe_create_screen/bloc/recipe_create_bloc.dart b/lib/presentation/recipe/recipe_create_screen/bloc/recipe_create_bloc.dart index ebb0ec06..c0b0e2ee 100644 --- a/lib/presentation/recipe/recipe_create_screen/bloc/recipe_create_bloc.dart +++ b/lib/presentation/recipe/recipe_create_screen/bloc/recipe_create_bloc.dart @@ -1,15 +1,16 @@ import 'dart:async'; +import 'dart:convert'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/presentation/recipe/recipe_create_screen/models/recipe_create_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:go_router/go_router.dart'; import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; -import 'dart:convert'; + import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/recipe/recipe_create_screen/models/recipe_create_model.dart'; -import 'package:go_router/go_router.dart'; + part 'recipe_create_event.dart'; part 'recipe_create_state.dart'; @@ -34,7 +35,8 @@ class RecipeCreateBloc extends Bloc { } if (state is RecipeCreateLoadedState) { var currentState = state as RecipeCreateLoadedState; - emit(currentState.copyWith( + emit( + currentState.copyWith( recipeModelObj: currentState.recipeModelObj, title: currentState.title, token: currentState.token, @@ -42,62 +44,79 @@ class RecipeCreateBloc extends Bloc { video_url: currentState.video_url, steps: currentState.steps, stepDescriptions: currentState.stepDescriptions, - tags: currentState.tags,),); + tags: currentState.tags, + ), + ); } else { final Map step = { 'description': '', 'image': '', }; - emit(RecipeCreateLoadedState( + emit( + RecipeCreateLoadedState( token: token, title: TextEditingController(), description: TextEditingController(), video_url: TextEditingController(), tags: TextEditingController(), stepDescriptions: [TextEditingController()], - steps: [step],),); + steps: [step], + ), + ); } } FutureOr _addStep( - AddStep event, Emitter emit,) async { + AddStep event, + Emitter emit, + ) async { if (state is RecipeCreateLoadedState) { var currentState = state as RecipeCreateLoadedState; List? updatedSteps = currentState.steps; - List? updatedStepDescriptions = - currentState.stepDescriptions; + List? updatedStepDescriptions = currentState.stepDescriptions; updatedSteps!.add({ 'description': '', 'image': '', }); updatedStepDescriptions!.add(TextEditingController()); - emit(currentState.copyWith( - steps: updatedSteps, stepDescriptions: updatedStepDescriptions,),); + emit( + currentState.copyWith( + steps: updatedSteps, + stepDescriptions: updatedStepDescriptions, + ), + ); await _reloadScreen(event, emit); } } FutureOr _removeStep( - RemoveStep event, Emitter emit,) async { + RemoveStep event, + Emitter emit, + ) async { if (state is RecipeCreateLoadedState) { var currentState = state as RecipeCreateLoadedState; List? updatedSteps = currentState.steps; - List? updatedStepDescriptions = - currentState.stepDescriptions; + List? updatedStepDescriptions = currentState.stepDescriptions; updatedSteps!.removeAt(event.id); updatedStepDescriptions!.removeAt(event.id); - emit(currentState.copyWith( - steps: updatedSteps, stepDescriptions: updatedStepDescriptions,),); + emit( + currentState.copyWith( + steps: updatedSteps, + stepDescriptions: updatedStepDescriptions, + ), + ); await _reloadScreen(event, emit); } } FutureOr _createRecipe( - CreateRecipe event, Emitter emit,) async { + CreateRecipe event, + Emitter emit, + ) async { if (state is RecipeCreateLoadedState) { var currentState = state as RecipeCreateLoadedState; @@ -112,14 +131,19 @@ class RecipeCreateBloc extends Bloc { AppRouter.navigatorKey.currentContext?.goNamed('recipeSelectScreen'); } else { print( - 'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}',); + 'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}', + ); } } } - FutureOr sendRecipe(String? title, String? video_url, - String? description, List? steps,) async { - String url = '${dotenv.env['SERVER_ROOT']!}/recipe/create'; + FutureOr sendRecipe( + String? title, + String? video_url, + String? description, + List? steps, + ) async { + String url = '${baseUrl}/api/recipe/create'; final Map credentials = { 'title': title, 'description': description, @@ -141,7 +165,9 @@ class RecipeCreateBloc extends Bloc { } FutureOr _reloadScreen( - RecipeCreateEvent? event, Emitter emit,) async { + RecipeCreateEvent? event, + Emitter emit, + ) async { print('Reloading..'); final box = await Hive.openBox('token'); final token = box.get('token'); @@ -150,7 +176,8 @@ class RecipeCreateBloc extends Bloc { } if (state is RecipeCreateLoadedState) { var currentState = state as RecipeCreateLoadedState; - emit(currentState.copyWith( + emit( + currentState.copyWith( recipeModelObj: currentState.recipeModelObj, title: currentState.title, token: currentState.token, @@ -158,7 +185,9 @@ class RecipeCreateBloc extends Bloc { video_url: currentState.video_url, steps: currentState.steps, stepDescriptions: currentState.stepDescriptions, - tags: currentState.tags,),); + tags: currentState.tags, + ), + ); } } } diff --git a/lib/presentation/recipe/recipe_create_screen/bloc/recipe_create_state.dart b/lib/presentation/recipe/recipe_create_screen/bloc/recipe_create_state.dart index 4865bf38..d58773af 100644 --- a/lib/presentation/recipe/recipe_create_screen/bloc/recipe_create_state.dart +++ b/lib/presentation/recipe/recipe_create_screen/bloc/recipe_create_state.dart @@ -22,15 +22,16 @@ class RecipeCreateState extends Equatable { } class RecipeCreateLoadedState extends RecipeCreateState { - RecipeCreateLoadedState( - {this.recipeModelObj, - this.token, - this.title, - this.description, - this.video_url, - this.tags, - this.stepDescriptions, - this.steps,}); + RecipeCreateLoadedState({ + this.recipeModelObj, + this.token, + this.title, + this.description, + this.video_url, + this.tags, + this.stepDescriptions, + this.steps, + }); RecipeCreateModel? recipeModelObj; String? token; @@ -62,14 +63,15 @@ class RecipeCreateLoadedState extends RecipeCreateState { List? stepDescriptions, }) { return RecipeCreateLoadedState( - recipeModelObj: recipeModelObj ?? this.recipeModelObj, - title: title ?? this.title, - description: description ?? this.description, - video_url: video_url ?? this.video_url, - token: token ?? this.token, - steps: steps ?? this.steps, - tags: tags ?? this.tags, - stepDescriptions: stepDescriptions ?? this.stepDescriptions,); + recipeModelObj: recipeModelObj ?? this.recipeModelObj, + title: title ?? this.title, + description: description ?? this.description, + video_url: video_url ?? this.video_url, + token: token ?? this.token, + steps: steps ?? this.steps, + tags: tags ?? this.tags, + stepDescriptions: stepDescriptions ?? this.stepDescriptions, + ); } } @@ -83,6 +85,5 @@ class RecipeCreateErrorState extends RecipeCreateState { } class RecipeCreateInitialState extends RecipeCreateState { - RecipeCreateInitialState({required RecipeCreateModel recipeModelObj}) - : super(recipeModelObj: recipeModelObj); + RecipeCreateInitialState({required RecipeCreateModel recipeModelObj}) : super(recipeModelObj: recipeModelObj); } diff --git a/lib/presentation/recipe/recipe_create_screen/recipe_create_screen.dart b/lib/presentation/recipe/recipe_create_screen/recipe_create_screen.dart index 5afb1645..0f8f3f53 100644 --- a/lib/presentation/recipe/recipe_create_screen/recipe_create_screen.dart +++ b/lib/presentation/recipe/recipe_create_screen/recipe_create_screen.dart @@ -1,14 +1,14 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart'; +import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; +import 'package:eatvio_app/widgets/custom_outlined_button.dart'; +import 'package:eatvio_app/widgets/custom_text_form_field.dart'; +import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'bloc/recipe_create_bloc.dart'; import 'models/recipe_create_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:flutter/material.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:eatvio_app/widgets/custom_outlined_button.dart'; class RecipeCreateScreen extends StatelessWidget { const RecipeCreateScreen({Key? key}) : super(key: key); @@ -16,9 +16,10 @@ class RecipeCreateScreen extends StatelessWidget { static Widget builder(BuildContext context) { final recipeID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( - create: (context) => - RecipeCreateBloc(RecipeCreateState(recipeModelObj: RecipeCreateModel(recipeID: recipeID.toString())))..add(RecipeCreateInitialEvent()), - child: RecipeCreateScreen(),); + create: (context) => + RecipeCreateBloc(RecipeCreateState(recipeModelObj: RecipeCreateModel(recipeID: recipeID.toString())))..add(RecipeCreateInitialEvent()), + child: RecipeCreateScreen(), + ); } Widget build(BuildContext context) { @@ -53,29 +54,33 @@ class RecipeCreateScreen extends StatelessWidget { } return RefreshIndicator( - onRefresh: refreshPage(context), - child: Scaffold( - appBar: AppBar( - toolbarHeight: 0, - automaticallyImplyLeading: false, - ), - resizeToAvoidBottomInset: false, - body: Container( - width: double.maxFinite, - decoration: BoxDecoration(color: Colors.grey[200]), - child: ListView(children: [ - _buldAppBar(context), - SizedBox(height: 20.v), - _buildRecipeInfo(state, context), - SizedBox(height: 20.v), - Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: steps, - ), - SizedBox(height: 20.v), - _buildAdditional(context, state), - ],), - ),),); + onRefresh: refreshPage(context), + child: Scaffold( + appBar: AppBar( + toolbarHeight: 0, + automaticallyImplyLeading: false, + ), + resizeToAvoidBottomInset: false, + body: Container( + width: double.maxFinite, + decoration: BoxDecoration(color: Colors.grey[200]), + child: ListView( + children: [ + _buldAppBar(context), + SizedBox(height: 20.v), + _buildRecipeInfo(state, context), + SizedBox(height: 20.v), + Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: steps, + ), + SizedBox(height: 20.v), + _buildAdditional(context, state), + ], + ), + ), + ), + ); } _buldAppBar(BuildContext context) { @@ -102,10 +107,11 @@ class RecipeCreateScreen extends StatelessWidget { onTap: onTapBack(context), ), title: Align( - alignment: Alignment.center, - child: AppbarSubtitle( - text: "Добавление рецепта", - ),), + alignment: Alignment.center, + child: AppbarSubtitle( + text: "Добавление рецепта", + ), + ), ), ); } @@ -130,41 +136,44 @@ class RecipeCreateScreen extends StatelessWidget { ), ], ), - child: Column(mainAxisSize: MainAxisSize.min, children: [ - SizedBox(height: 16.0), - Align(alignment: Alignment.centerLeft, child: Text("Изображение")), - _buildAddPhoto(context, state), - SizedBox(height: 16.0), - Align(alignment: Alignment.centerLeft, child: Text("Название рецепта")), - CustomTextFormField( - controller: state.title, - hintText: "Введите название рецепта", - fillColor: appTheme.gray50, - borderDecoration: OutlineInputBorder( - borderRadius: BorderRadius.circular(5.h), - borderSide: BorderSide( - color: appTheme.gray50, - width: 1, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox(height: 16.0), + Align(alignment: Alignment.centerLeft, child: Text("Изображение")), + _buildAddPhoto(context, state), + SizedBox(height: 16.0), + Align(alignment: Alignment.centerLeft, child: Text("Название рецепта")), + CustomTextFormField( + controller: state.title, + hintText: "Введите название рецепта", + fillColor: appTheme.gray50, + borderDecoration: OutlineInputBorder( + borderRadius: BorderRadius.circular(5.h), + borderSide: BorderSide( + color: appTheme.gray50, + width: 1, + ), ), ), - ), - SizedBox(height: 16.0), - Align(alignment: Alignment.centerLeft, child: Text("Описание")), - CustomTextFormField( - controller: state.description, - hintText: "Введите описание рецепта", - maxLines: 4, - fillColor: appTheme.gray50, - borderDecoration: OutlineInputBorder( - borderRadius: BorderRadius.circular(5.h), - borderSide: BorderSide( - color: appTheme.gray50, - width: 1, + SizedBox(height: 16.0), + Align(alignment: Alignment.centerLeft, child: Text("Описание")), + CustomTextFormField( + controller: state.description, + hintText: "Введите описание рецепта", + maxLines: 4, + fillColor: appTheme.gray50, + borderDecoration: OutlineInputBorder( + borderRadius: BorderRadius.circular(5.h), + borderSide: BorderSide( + color: appTheme.gray50, + width: 1, + ), ), ), - ), - SizedBox(height: 16.0), - ],), + SizedBox(height: 16.0), + ], + ), ); } @@ -254,71 +263,74 @@ class RecipeCreateScreen extends StatelessWidget { ), ], ), - child: Column(mainAxisSize: MainAxisSize.min, children: [ - Align( - alignment: Alignment.centerLeft, - child: Text( - "Шаг ${i + 1}", - style: CustomTextStyles.titleMediumSemiBold, - ), - ), - SizedBox(height: 8.0), - CustomTextFormField( - controller: state.stepDescriptions?[i], - hintText: "Введите описание шага", - maxLines: 4, - fillColor: appTheme.gray50, - borderDecoration: OutlineInputBorder( - borderRadius: BorderRadius.circular(5.h), - borderSide: BorderSide( - color: appTheme.gray50, - width: 1, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Align( + alignment: Alignment.centerLeft, + child: Text( + "Шаг ${i + 1}", + style: CustomTextStyles.titleMediumSemiBold, ), ), - ), - SizedBox(height: 16.0), - _buildAddPhoto(context, state), - SizedBox(height: 16.0), - if (isFirstStep && isLastStep) - CustomOutlinedButton( - onPressed: () => context.read().add(AddStep()), - text: "Добавить шаг", - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - ), - if (isLastStep && !isFirstStep) // Добавляем кнопку "Добавить шаг" только для последнего шага - Column( - children: [ - SizedBox(height: 16.0), - Row( - children: [ - Flexible( - flex: 5, - child: CustomOutlinedButton( - onPressed: () => context.read().add(AddStep()), - text: "Добавить шаг", - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - ), - ), - SizedBox(width: 8), // Add some spacing between the buttons - Flexible( - flex: 1, - child: CustomOutlinedButton( - text: "х", - onPressed: () => context.read().add(RemoveStep(i)), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - ), - ), - ], + SizedBox(height: 8.0), + CustomTextFormField( + controller: state.stepDescriptions?[i], + hintText: "Введите описание шага", + maxLines: 4, + fillColor: appTheme.gray50, + borderDecoration: OutlineInputBorder( + borderRadius: BorderRadius.circular(5.h), + borderSide: BorderSide( + color: appTheme.gray50, + width: 1, ), - ], + ), ), - if (!isLastStep && !isFirstStep) - CustomOutlinedButton( - onPressed: () => context.read().add(RemoveStep(i)), - text: "x", - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - ), - ],), + SizedBox(height: 16.0), + _buildAddPhoto(context, state), + SizedBox(height: 16.0), + if (isFirstStep && isLastStep) + CustomOutlinedButton( + onPressed: () => context.read().add(AddStep()), + text: "Добавить шаг", + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + ), + if (isLastStep && !isFirstStep) // Добавляем кнопку "Добавить шаг" только для последнего шага + Column( + children: [ + SizedBox(height: 16.0), + Row( + children: [ + Flexible( + flex: 5, + child: CustomOutlinedButton( + onPressed: () => context.read().add(AddStep()), + text: "Добавить шаг", + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + ), + ), + SizedBox(width: 8), // Add some spacing between the buttons + Flexible( + flex: 1, + child: CustomOutlinedButton( + text: "х", + onPressed: () => context.read().add(RemoveStep(i)), + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + ), + ), + ], + ), + ], + ), + if (!isLastStep && !isFirstStep) + CustomOutlinedButton( + onPressed: () => context.read().add(RemoveStep(i)), + text: "x", + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + ), + ], + ), ); } @@ -342,40 +354,43 @@ class RecipeCreateScreen extends StatelessWidget { ), ], ), - child: Column(mainAxisSize: MainAxisSize.min, children: [ - Align(alignment: Alignment.centerLeft, child: Text("Теги")), - CustomTextFormField( - controller: state.tags, - hintText: "Введите теги, через запятую", - fillColor: appTheme.gray50, - borderDecoration: OutlineInputBorder( - borderRadius: BorderRadius.circular(5.h), - borderSide: BorderSide( - color: appTheme.gray50, - width: 1, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Align(alignment: Alignment.centerLeft, child: Text("Теги")), + CustomTextFormField( + controller: state.tags, + hintText: "Введите теги, через запятую", + fillColor: appTheme.gray50, + borderDecoration: OutlineInputBorder( + borderRadius: BorderRadius.circular(5.h), + borderSide: BorderSide( + color: appTheme.gray50, + width: 1, + ), ), ), - ), - SizedBox(height: 8.0), - Align(alignment: Alignment.centerLeft, child: Text("Ссылка на видео (необязательно)")), - CustomTextFormField( - controller: state.video_url, - hintText: "YouTube", - fillColor: appTheme.gray50, - borderDecoration: OutlineInputBorder( - borderRadius: BorderRadius.circular(5.h), - borderSide: BorderSide( - color: appTheme.gray50, - width: 1, + SizedBox(height: 8.0), + Align(alignment: Alignment.centerLeft, child: Text("Ссылка на видео (необязательно)")), + CustomTextFormField( + controller: state.video_url, + hintText: "YouTube", + fillColor: appTheme.gray50, + borderDecoration: OutlineInputBorder( + borderRadius: BorderRadius.circular(5.h), + borderSide: BorderSide( + color: appTheme.gray50, + width: 1, + ), ), ), - ), - SizedBox(height: 16.0), - CustomOutlinedButton( - text: "Добавить рецепт", - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - ), - ],), + SizedBox(height: 16.0), + CustomOutlinedButton( + text: "Добавить рецепт", + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + ), + ], + ), ); } diff --git a/lib/presentation/recipe/recipe_edit_screen/bloc/recipe_edit_bloc.dart b/lib/presentation/recipe/recipe_edit_screen/bloc/recipe_edit_bloc.dart index 00dbfcd3..560c75ee 100644 --- a/lib/presentation/recipe/recipe_edit_screen/bloc/recipe_edit_bloc.dart +++ b/lib/presentation/recipe/recipe_edit_screen/bloc/recipe_edit_bloc.dart @@ -1,18 +1,17 @@ import 'dart:async'; +import 'dart:convert'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/presentation/recipe/recipe_edit_screen/models/recipe_edit_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:go_router/go_router.dart'; import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; -import 'dart:convert'; + import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/recipe/recipe_edit_screen/models/recipe_edit_model.dart'; -import 'package:go_router/go_router.dart'; part 'recipe_edit_event.dart'; - part 'recipe_edit_state.dart'; /// A bloc that manages the state of a RecipeEdit according to the event that is dispatched to it. @@ -37,7 +36,7 @@ class RecipeEditBloc extends Bloc { } final String? recipeID = state.recipeModelObj?.recipeID; final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipe/show/$recipeID'), + Uri.parse(baseUrl + '/api/recipes/show/$recipeID'), headers: { 'Authorization': 'Bearer $token', }, @@ -47,7 +46,8 @@ class RecipeEditBloc extends Bloc { if (data is Map) { if (state is RecipeEditLoadedState) { var currentState = state as RecipeEditLoadedState; - emit(currentState.copyWith( + emit( + currentState.copyWith( recipeModelObj: currentState.recipeModelObj, title: currentState.title, token: currentState.token, @@ -56,7 +56,9 @@ class RecipeEditBloc extends Bloc { video_url: currentState.video_url, steps: currentState.steps, stepDescriptions: currentState.stepDescriptions, - tags: currentState.tags,),); + tags: currentState.tags, + ), + ); } else { final Map defaultStep = { 'description': '', @@ -75,17 +77,19 @@ class RecipeEditBloc extends Bloc { } } - emit(RecipeEditLoadedState( - token: token, - recipe: data, - title: TextEditingController(text: data['title']), - description: TextEditingController(text: data['description']), - video_url: TextEditingController(text: data['video_url']), - tagsController: TextEditingController(), - tags: await _fetchTags(data['id']), - stepDescriptions: stepDescriptions, - steps: steps, - ),); + emit( + RecipeEditLoadedState( + token: token, + recipe: data, + title: TextEditingController(text: data['title']), + description: TextEditingController(text: data['description']), + video_url: TextEditingController(text: data['video_url']), + tagsController: TextEditingController(), + tags: await _fetchTags(data['id']), + stepDescriptions: stepDescriptions, + steps: steps, + ), + ); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку @@ -161,7 +165,7 @@ class RecipeEditBloc extends Bloc { String? description, ) async { int id = recipe?['id']; - String url = '${dotenv.env['SERVER_ROOT']!}/recipe/update/$id'; + String url = '${baseUrl}/api/recipe/update/$id'; final Map credentials = { 'id': id, @@ -195,7 +199,7 @@ class RecipeEditBloc extends Bloc { } final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipe/getTags/$id'), + Uri.parse(baseUrl + '/api/recipes/getTags/$id'), headers: { 'Authorization': 'Bearer $token', }, @@ -213,7 +217,8 @@ class RecipeEditBloc extends Bloc { } if (state is RecipeEditLoadedState) { var currentState = state as RecipeEditLoadedState; - emit(currentState.copyWith( + emit( + currentState.copyWith( recipeModelObj: currentState.recipeModelObj, recipe: currentState.recipe, title: currentState.title, @@ -222,7 +227,9 @@ class RecipeEditBloc extends Bloc { video_url: currentState.video_url, steps: currentState.steps, stepDescriptions: currentState.stepDescriptions, - tags: currentState.tags,),); + tags: currentState.tags, + ), + ); } } } diff --git a/lib/presentation/recipe/recipe_edit_screen/bloc/recipe_edit_state.dart b/lib/presentation/recipe/recipe_edit_screen/bloc/recipe_edit_state.dart index e9086e60..57df9f28 100644 --- a/lib/presentation/recipe/recipe_edit_screen/bloc/recipe_edit_state.dart +++ b/lib/presentation/recipe/recipe_edit_screen/bloc/recipe_edit_state.dart @@ -22,17 +22,18 @@ class RecipeEditState extends Equatable { } class RecipeEditLoadedState extends RecipeEditState { - RecipeEditLoadedState( - {this.recipeModelObj, - this.token, - this.recipe, - this.title, - this.description, - this.video_url, - this.tagsController, - this.stepDescriptions, - this.tags, - this.steps,}); + RecipeEditLoadedState({ + this.recipeModelObj, + this.token, + this.recipe, + this.title, + this.description, + this.video_url, + this.tagsController, + this.stepDescriptions, + this.tags, + this.steps, + }); RecipeEditModel? recipeModelObj; Map? recipe; @@ -45,8 +46,7 @@ class RecipeEditLoadedState extends RecipeEditState { List? tags; List? stepDescriptions; @override - List get props => - [recipeModelObj, recipe, title, description, video_url]; + List get props => [recipeModelObj, recipe, title, description, video_url]; RecipeEditLoadedState copyWith({ RecipeEditModel? recipeModelObj, Map? recipe, @@ -84,6 +84,5 @@ class RecipeEditErrorState extends RecipeEditState { } class RecipeEditInitialState extends RecipeEditState { - RecipeEditInitialState({required RecipeEditModel recipeModelObj}) - : super(recipeModelObj: recipeModelObj); + RecipeEditInitialState({required RecipeEditModel recipeModelObj}) : super(recipeModelObj: recipeModelObj); } diff --git a/lib/presentation/recipe/recipe_edit_screen/recipe_edit_screen.dart b/lib/presentation/recipe/recipe_edit_screen/recipe_edit_screen.dart index 6621fc8d..e3dbcbe6 100644 --- a/lib/presentation/recipe/recipe_edit_screen/recipe_edit_screen.dart +++ b/lib/presentation/recipe/recipe_edit_screen/recipe_edit_screen.dart @@ -1,16 +1,15 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart'; +import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; +import 'package:eatvio_app/widgets/custom_outlined_button.dart'; +import 'package:eatvio_app/widgets/custom_text_form_field.dart'; +import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'bloc/recipe_edit_bloc.dart'; import 'models/recipe_edit_model.dart'; -import 'package:flutter/material.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:eatvio_app/widgets/custom_outlined_button.dart'; class RecipeEditScreen extends StatelessWidget { const RecipeEditScreen({Key? key}) : super(key: key); @@ -18,8 +17,9 @@ class RecipeEditScreen extends StatelessWidget { static Widget builder(BuildContext context) { final recipeID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( - create: (context) => RecipeEditBloc(RecipeEditState(recipeModelObj: RecipeEditModel(recipeID: recipeID.toString())))..add(RecipeEditInitialEvent()), - child: RecipeEditScreen(),); + create: (context) => RecipeEditBloc(RecipeEditState(recipeModelObj: RecipeEditModel(recipeID: recipeID.toString())))..add(RecipeEditInitialEvent()), + child: RecipeEditScreen(), + ); } Widget build(BuildContext context) { @@ -109,10 +109,11 @@ class RecipeEditScreen extends StatelessWidget { onTap: onTapBack(context), ), title: Align( - alignment: Alignment.center, - child: AppbarSubtitle( - text: "Редактирование рецепта", - ),), + alignment: Alignment.center, + child: AppbarSubtitle( + text: "Редактирование рецепта", + ), + ), ), ); } @@ -137,52 +138,55 @@ class RecipeEditScreen extends StatelessWidget { ), ], ), - child: Column(mainAxisSize: MainAxisSize.min, children: [ - SizedBox(height: 16.0), - Align(alignment: Alignment.centerLeft, child: Text("Изображение")), - if (state.recipe?['image'] != null) - CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (state.recipe?['image']), - width: double.infinity, - // Установите ширину равной ширине родительского элемента - height: 200.0, - fit: BoxFit.cover, - placeholder: (context, url) => CircularProgressIndicator(), - errorWidget: (context, url, error) => Icon(Icons.error), - ) - else - _buildAddPhoto(context, state), - SizedBox(height: 16.0), - Align(alignment: Alignment.centerLeft, child: Text("Название рецепта")), - CustomTextFormField( - controller: state.title, - hintText: "Введите название рецепта", - fillColor: appTheme.gray50, - borderDecoration: OutlineInputBorder( - borderRadius: BorderRadius.circular(5.h), - borderSide: BorderSide( - color: appTheme.gray50, - width: 1, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox(height: 16.0), + Align(alignment: Alignment.centerLeft, child: Text("Изображение")), + if (state.recipe?['image'] != null) + CachedNetworkImage( + imageUrl: baseUrl + '/storage/' + (state.recipe?['image']), + width: double.infinity, + // Установите ширину равной ширине родительского элемента + height: 200.0, + fit: BoxFit.cover, + placeholder: (context, url) => CircularProgressIndicator(), + errorWidget: (context, url, error) => Icon(Icons.error), + ) + else + _buildAddPhoto(context, state), + SizedBox(height: 16.0), + Align(alignment: Alignment.centerLeft, child: Text("Название рецепта")), + CustomTextFormField( + controller: state.title, + hintText: "Введите название рецепта", + fillColor: appTheme.gray50, + borderDecoration: OutlineInputBorder( + borderRadius: BorderRadius.circular(5.h), + borderSide: BorderSide( + color: appTheme.gray50, + width: 1, + ), ), ), - ), - SizedBox(height: 16.0), - Align(alignment: Alignment.centerLeft, child: Text("Описание")), - CustomTextFormField( - controller: state.description, - hintText: "Введите описание рецепта", - maxLines: 4, - fillColor: appTheme.gray50, - borderDecoration: OutlineInputBorder( - borderRadius: BorderRadius.circular(5.h), - borderSide: BorderSide( - color: appTheme.gray50, - width: 1, + SizedBox(height: 16.0), + Align(alignment: Alignment.centerLeft, child: Text("Описание")), + CustomTextFormField( + controller: state.description, + hintText: "Введите описание рецепта", + maxLines: 4, + fillColor: appTheme.gray50, + borderDecoration: OutlineInputBorder( + borderRadius: BorderRadius.circular(5.h), + borderSide: BorderSide( + color: appTheme.gray50, + width: 1, + ), ), ), - ), - SizedBox(height: 16.0), - ],), + SizedBox(height: 16.0), + ], + ), ); } @@ -272,83 +276,86 @@ class RecipeEditScreen extends StatelessWidget { ), ], ), - child: Column(mainAxisSize: MainAxisSize.min, children: [ - Align( - alignment: Alignment.centerLeft, - child: Text( - "Шаг ${i + 1}", - style: CustomTextStyles.titleMediumSemiBold, - ), - ), - SizedBox(height: 8.0), - CustomTextFormField( - controller: state.stepDescriptions?[i], - hintText: "Введите описание шага", - maxLines: 4, - fillColor: appTheme.gray50, - borderDecoration: OutlineInputBorder( - borderRadius: BorderRadius.circular(5.h), - borderSide: BorderSide( - color: appTheme.gray50, - width: 1, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Align( + alignment: Alignment.centerLeft, + child: Text( + "Шаг ${i + 1}", + style: CustomTextStyles.titleMediumSemiBold, ), ), - ), - SizedBox(height: 16.0), - if (state.steps?[i]['image'] != null) - CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (state.steps?[i]['image']), - width: double.infinity, - // Установите ширину равной ширине родительского элемента - height: 200.0, - // Задайте постоянную высоту элемента - fit: BoxFit.cover, - placeholder: (context, url) => CircularProgressIndicator(), - errorWidget: (context, url, error) => Icon(Icons.error), - ) - else - _buildAddPhoto(context, state), - SizedBox(height: 16.0), - if (isFirstStep && isLastStep) - CustomOutlinedButton( - onPressed: () => context.read().add(AddStep()), - text: "Добавить шаг", - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - ), - if (isLastStep && !isFirstStep) // Добавляем кнопку "Добавить шаг" только для последнего шага - Column( - children: [ - SizedBox(height: 16.0), - Row( - children: [ - Flexible( - flex: 5, - child: CustomOutlinedButton( - onPressed: () => context.read().add(AddStep()), - text: "Добавить шаг", - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - ), - ), - SizedBox(width: 8), // Add some spacing between the buttons - Flexible( - flex: 1, - child: CustomOutlinedButton( - text: "х", - onPressed: () => context.read().add(RemoveStep(i)), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - ), - ), - ], + SizedBox(height: 8.0), + CustomTextFormField( + controller: state.stepDescriptions?[i], + hintText: "Введите описание шага", + maxLines: 4, + fillColor: appTheme.gray50, + borderDecoration: OutlineInputBorder( + borderRadius: BorderRadius.circular(5.h), + borderSide: BorderSide( + color: appTheme.gray50, + width: 1, ), - ], + ), ), - if (!isLastStep && !isFirstStep) - CustomOutlinedButton( - onPressed: () => context.read().add(RemoveStep(i)), - text: "x", - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - ), - ],), + SizedBox(height: 16.0), + if (state.steps?[i]['image'] != null) + CachedNetworkImage( + imageUrl: baseUrl + '/storage/' + (state.steps?[i]['image']), + width: double.infinity, + // Установите ширину равной ширине родительского элемента + height: 200.0, + // Задайте постоянную высоту элемента + fit: BoxFit.cover, + placeholder: (context, url) => CircularProgressIndicator(), + errorWidget: (context, url, error) => Icon(Icons.error), + ) + else + _buildAddPhoto(context, state), + SizedBox(height: 16.0), + if (isFirstStep && isLastStep) + CustomOutlinedButton( + onPressed: () => context.read().add(AddStep()), + text: "Добавить шаг", + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + ), + if (isLastStep && !isFirstStep) // Добавляем кнопку "Добавить шаг" только для последнего шага + Column( + children: [ + SizedBox(height: 16.0), + Row( + children: [ + Flexible( + flex: 5, + child: CustomOutlinedButton( + onPressed: () => context.read().add(AddStep()), + text: "Добавить шаг", + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + ), + ), + SizedBox(width: 8), // Add some spacing between the buttons + Flexible( + flex: 1, + child: CustomOutlinedButton( + text: "х", + onPressed: () => context.read().add(RemoveStep(i)), + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + ), + ), + ], + ), + ], + ), + if (!isLastStep && !isFirstStep) + CustomOutlinedButton( + onPressed: () => context.read().add(RemoveStep(i)), + text: "x", + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + ), + ], + ), ); } @@ -372,29 +379,32 @@ class RecipeEditScreen extends StatelessWidget { ), ], ), - child: Column(mainAxisSize: MainAxisSize.min, children: [ - Align(alignment: Alignment.centerLeft, child: Text("Теги")), - _buildEditableTags(state.tags), - SizedBox(height: 8.0), - Align(alignment: Alignment.centerLeft, child: Text("Ссылка на видео (необязательно)")), - CustomTextFormField( - controller: state.video_url, - hintText: "YouTube", - fillColor: appTheme.gray50, - borderDecoration: OutlineInputBorder( - borderRadius: BorderRadius.circular(5.h), - borderSide: BorderSide( - color: appTheme.gray50, - width: 1, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Align(alignment: Alignment.centerLeft, child: Text("Теги")), + _buildEditableTags(state.tags), + SizedBox(height: 8.0), + Align(alignment: Alignment.centerLeft, child: Text("Ссылка на видео (необязательно)")), + CustomTextFormField( + controller: state.video_url, + hintText: "YouTube", + fillColor: appTheme.gray50, + borderDecoration: OutlineInputBorder( + borderRadius: BorderRadius.circular(5.h), + borderSide: BorderSide( + color: appTheme.gray50, + width: 1, + ), ), ), - ), - SizedBox(height: 16.0), - CustomOutlinedButton( - text: "Добавить рецепт", - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - ), - ],), + SizedBox(height: 16.0), + CustomOutlinedButton( + text: "Добавить рецепт", + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + ), + ], + ), ); } diff --git a/lib/presentation/recipe/recipe_select_screen/bloc/recipe_select_bloc.dart b/lib/presentation/recipe/recipe_select_screen/bloc/recipe_select_bloc.dart index 6f5bdfda..399e20f8 100644 --- a/lib/presentation/recipe/recipe_select_screen/bloc/recipe_select_bloc.dart +++ b/lib/presentation/recipe/recipe_select_screen/bloc/recipe_select_bloc.dart @@ -1,16 +1,16 @@ import 'dart:async'; +import 'package:dio/dio.dart'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/locator_service.dart'; +import 'package:eatvio_app/presentation/recipe/recipe_select_screen/models/recipe_select_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/recipe/recipe_select_screen/models/recipe_select_model.dart'; -import 'package:http/http.dart' as http; -import 'dart:convert'; -import 'package:hive/hive.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:image_picker/image_picker.dart'; import 'package:go_router/go_router.dart'; +import 'package:hive/hive.dart'; +import 'package:image_picker/image_picker.dart'; + +import '/core/app_export.dart'; part 'recipe_select_event.dart'; part 'recipe_select_state.dart'; @@ -31,27 +31,29 @@ class RecipeSelectBloc extends Bloc { if (token == null) { AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); } - final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipe/index'), - ); + final response = await sl().get(baseUrl + '/api/recipes/index'); print('Got response'); if (response.statusCode == 200) { print('Got 200'); - final data = jsonDecode(response.body); + final data = response.data['data']; if (data is List) { print('Got List'); if (state is RecipeSelectLoadedState) { print('Got loaded'); var currentState = state as RecipeSelectLoadedState; - emit((currentState).copyWith( - posts: data, - myProfileModelObj: currentState.myProfileModelObj, - ),); + emit( + (currentState).copyWith( + posts: data, + myProfileModelObj: currentState.myProfileModelObj, + ), + ); } else { print('Got unloaded'); - emit(RecipeSelectLoadedState( - posts: data, - ),); + emit( + RecipeSelectLoadedState( + posts: data, + ), + ); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку diff --git a/lib/presentation/recipe/recipe_select_screen/bloc/recipe_select_state.dart b/lib/presentation/recipe/recipe_select_screen/bloc/recipe_select_state.dart index feb87b2e..d320f903 100644 --- a/lib/presentation/recipe/recipe_select_screen/bloc/recipe_select_state.dart +++ b/lib/presentation/recipe/recipe_select_screen/bloc/recipe_select_state.dart @@ -12,14 +12,12 @@ class RecipeSelectState extends Equatable { } class RecipeSelectInitialState extends RecipeSelectState { - RecipeSelectInitialState({required RecipeSelectModel myProfileModelObj}) - : super(myProfileModelObj: myProfileModelObj); + RecipeSelectInitialState({required RecipeSelectModel myProfileModelObj}) : super(myProfileModelObj: myProfileModelObj); } /// Represents the state of RecipeSelect in the application. class RecipeSelectLoadedState extends RecipeSelectState { - RecipeSelectLoadedState({this.myProfileModelObj, this.posts}) - : super(myProfileModelObj: null); + RecipeSelectLoadedState({this.myProfileModelObj, this.posts}) : super(myProfileModelObj: null); RecipeSelectModel? myProfileModelObj; List? posts; diff --git a/lib/presentation/recipe/recipe_select_screen/recipe_select_screen.dart b/lib/presentation/recipe/recipe_select_screen/recipe_select_screen.dart index fa0a9506..29e47b36 100644 --- a/lib/presentation/recipe/recipe_select_screen/recipe_select_screen.dart +++ b/lib/presentation/recipe/recipe_select_screen/recipe_select_screen.dart @@ -1,20 +1,20 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart'; +import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; +import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'bloc/recipe_select_bloc.dart'; import 'models/recipe_select_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter/material.dart'; class RecipeSelectScreen extends StatelessWidget { static Widget builder(BuildContext context) { return BlocProvider( - create: (context) => RecipeSelectBloc(RecipeSelectState(myProfileModelObj: RecipeSelectModel()))..add(RecipeSelectInitialEvent()), - child: RecipeSelectScreen(),); + create: (context) => RecipeSelectBloc(RecipeSelectState(myProfileModelObj: RecipeSelectModel()))..add(RecipeSelectInitialEvent()), + child: RecipeSelectScreen(), + ); } Widget build(BuildContext context) { @@ -112,55 +112,57 @@ class RecipeSelectScreen extends StatelessWidget { _buildRecipeList(BuildContext context, RecipeSelectLoadedState state) { return ListView.builder( + physics: NeverScrollableScrollPhysics(), shrinkWrap: true, // Add this line itemCount: state.posts?.length ?? 0, itemBuilder: (context, index) { final post = state.posts?[index]; return Container( - margin: EdgeInsets.only(bottom: 10), - 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), - ), - ], + margin: EdgeInsets.only(bottom: 10), + 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), + ), + ], + ), + child: ListTile( + leading: CachedNetworkImage( + imageUrl: baseUrl + '/storage/' + post['image'], + imageBuilder: (context, imageProvider) => CircleAvatar( + backgroundImage: imageProvider, + radius: 25, + ), + placeholder: (context, url) => CircularProgressIndicator(), + errorWidget: (context, url, error) => CircleAvatar( + child: Icon(Icons.person), + backgroundColor: Colors.white, + radius: 25, + ), ), - child: ListTile( - leading: CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + post['image'], - imageBuilder: (context, imageProvider) => CircleAvatar( - backgroundImage: imageProvider, - radius: 25, - ), - placeholder: (context, url) => CircularProgressIndicator(), - errorWidget: (context, url, error) => CircleAvatar( - child: Icon(Icons.person), - backgroundColor: Colors.white, - radius: 25, - ), - ), - title: Text( - post?['title'] ?? '', - style: CustomTextStyles.titleMediumSemiBold, - ), - subtitle: Text(post?['description'] ?? ''), + title: Text( + post?['title'] ?? '', + style: CustomTextStyles.titleMediumSemiBold, + ), + subtitle: Text(post?['description'] ?? ''), + onTap: () => GoRouter.of(context).goNamed( + 'recipeScreen', + extra: post?['id'].toString(), + ), + trailing: GestureDetector( onTap: () => GoRouter.of(context).goNamed( - 'recipeScreen', + 'recipeEditScreen', extra: post?['id'].toString(), ), - trailing: GestureDetector( - onTap: () => GoRouter.of(context).goNamed( - 'recipeEditScreen', - extra: post?['id'].toString(), - ), - child: Icon(Icons.edit), - ), - ),); + child: Icon(Icons.edit), + ), + ), + ); }, ); } diff --git a/lib/presentation/recipe/recipe_show_screen/bloc/recipe_show_bloc.dart b/lib/presentation/recipe/recipe_show_screen/bloc/recipe_show_bloc.dart index ed9b6efe..ac2d9a9a 100644 --- a/lib/presentation/recipe/recipe_show_screen/bloc/recipe_show_bloc.dart +++ b/lib/presentation/recipe/recipe_show_screen/bloc/recipe_show_bloc.dart @@ -1,20 +1,19 @@ import 'dart:async'; +import 'dart:convert'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/presentation/feed/blog_post_screen/models/comment_model.dart'; +import 'package:eatvio_app/presentation/recipe/recipe_show_screen/models/recipe_show_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:go_router/go_router.dart'; import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; import 'package:intl/intl.dart'; -import 'dart:convert'; + import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/recipe/recipe_show_screen/models/recipe_show_model.dart'; -import 'package:eatvio_app/presentation/feed/blog_post_screen/models/comment_model.dart'; -import 'package:go_router/go_router.dart'; part 'recipe_show_event.dart'; - part 'recipe_show_state.dart'; /// A bloc that manages the state of a Recipe according to the event that is dispatched to it. @@ -37,7 +36,7 @@ class RecipeBloc extends Bloc { } final String? recipeID = state.recipeModelObj?.recipeID; final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipe/show/$recipeID'), + Uri.parse(baseUrl + '/api/recipes/show/$recipeID'), headers: { 'Authorization': 'Bearer $token', }, @@ -47,23 +46,29 @@ class RecipeBloc extends Bloc { if (data is Map) { if (state is RecipeLoadedState) { var currentState = state as RecipeLoadedState; - emit(currentState.copyWith( + emit( + currentState.copyWith( recipeModelObj: currentState.recipeModelObj, recipe: currentState.recipe, token: currentState.token, commentController: currentState.commentController, comments: currentState.comments, steps: currentState.steps, - author: currentState.author,),); + author: currentState.author, + ), + ); } else { - emit(RecipeLoadedState( + emit( + RecipeLoadedState( token: token, recipe: data, steps: data['steps'], author: await _fetchAuthor(data['id']), comments: fillCommentList(await _fetchComments(data['id'])), tags: await _fetchTags(data['id']), - commentController: TextEditingController(),),); + commentController: TextEditingController(), + ), + ); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку @@ -87,7 +92,7 @@ class RecipeBloc extends Bloc { } final int id = event.id; final response = await http.post( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipe/delete/$id'), + Uri.parse(baseUrl + '/api/recipes/delete/$id'), headers: { 'Authorization': 'Bearer $token', }, @@ -125,7 +130,7 @@ class RecipeBloc extends Bloc { } final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipe/getAuthor/$id'), + Uri.parse(baseUrl + '/api/recipes/getAuthor/$id'), headers: { 'Authorization': 'Bearer $token', }, @@ -141,7 +146,7 @@ class RecipeBloc extends Bloc { AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); } final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipe/getComments/$id'), + Uri.parse(baseUrl + '/api/recipes/getComments/$id'), headers: { 'Authorization': 'Bearer $token', }, @@ -159,7 +164,7 @@ class RecipeBloc extends Bloc { } final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipe/getTags/$id'), + Uri.parse(baseUrl + '/api/recipes/getTags/$id'), headers: { 'Authorization': 'Bearer $token', }, @@ -171,30 +176,35 @@ class RecipeBloc extends Bloc { List fillCommentList(List comments) { List list = []; for (int i = 0; i < comments.length; i++) { - list.add(CommentModel( + list.add( + CommentModel( id: comments[i]['id'].toString(), userImage: comments[i]['profile_photo_path'], username: comments[i]['name'], dateText: DateFormat('dd.MM').format(DateTime.parse(comments[i]['updated_at'])), - greetingText: comments[i]['body'],),); + greetingText: comments[i]['body'], + ), + ); } return list; } Future _sendCommentData(String? token, String body, int id) async { - String url = dotenv.env['SERVER_ROOT']! + '/recipe/createComment/$id'; + String url = baseUrl + '/api/recipes/createComment/$id'; final Map credentials = { 'id': id, 'body': body, }; - var response = await http.post(Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - body: json.encode(credentials), - encoding: utf8,); + var response = await http.post( + Uri.parse(url), + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer $token', + }, + body: json.encode(credentials), + encoding: utf8, + ); return response; } diff --git a/lib/presentation/recipe/recipe_show_screen/bloc/recipe_show_state.dart b/lib/presentation/recipe/recipe_show_screen/bloc/recipe_show_state.dart index efc80d69..335ac202 100644 --- a/lib/presentation/recipe/recipe_show_screen/bloc/recipe_show_state.dart +++ b/lib/presentation/recipe/recipe_show_screen/bloc/recipe_show_state.dart @@ -22,15 +22,16 @@ class RecipeState extends Equatable { } class RecipeLoadedState extends RecipeState { - RecipeLoadedState( - {this.recipeModelObj, - this.recipe, - this.author, - this.comments, - this.token, - this.commentController, - this.tags, - this.steps,}); + RecipeLoadedState({ + this.recipeModelObj, + this.recipe, + this.author, + this.comments, + this.token, + this.commentController, + this.tags, + this.steps, + }); RecipeModel? recipeModelObj; Map? recipe; @@ -50,15 +51,16 @@ class RecipeLoadedState extends RecipeState { commentController, steps, ]; - RecipeLoadedState copyWith( - {RecipeModel? recipeModelObj, - Map? recipe, - Map? author, - TextEditingController? commentController, - String? token, - List? tags, - List? steps, - List? comments,}) { + RecipeLoadedState copyWith({ + RecipeModel? recipeModelObj, + Map? recipe, + Map? author, + TextEditingController? commentController, + String? token, + List? tags, + List? steps, + List? comments, + }) { return RecipeLoadedState( recipeModelObj: recipeModelObj ?? this.recipeModelObj, recipe: recipe ?? this.recipe, @@ -82,6 +84,5 @@ class RecipeErrorState extends RecipeState { } class RecipeInitialState extends RecipeState { - RecipeInitialState({required RecipeModel recipeModelObj}) - : super(recipeModelObj: recipeModelObj); + RecipeInitialState({required RecipeModel recipeModelObj}) : super(recipeModelObj: recipeModelObj); } diff --git a/lib/presentation/recipe/recipe_show_screen/recipe_show_screen.dart b/lib/presentation/recipe/recipe_show_screen/recipe_show_screen.dart index 30fd4e9d..c42813d4 100644 --- a/lib/presentation/recipe/recipe_show_screen/recipe_show_screen.dart +++ b/lib/presentation/recipe/recipe_show_screen/recipe_show_screen.dart @@ -1,15 +1,14 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/presentation/feed/blog_post_screen/widgets/comment_widget.dart'; +import 'package:eatvio_app/widgets/custom_edit_text_form_field.dart'; +import 'package:eatvio_app/widgets/custom_outlined_button.dart'; +import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; +import 'package:intl/intl.dart'; import 'bloc/recipe_show_bloc.dart'; import 'models/recipe_show_model.dart'; -import 'package:eatvio_app/presentation/feed/blog_post_screen/widgets/comment_widget.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:flutter/material.dart'; -import 'package:intl/intl.dart'; -import 'package:eatvio_app/widgets/custom_edit_text_form_field.dart'; -import 'package:eatvio_app/widgets/custom_outlined_button.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; class RecipeScreen extends StatelessWidget { const RecipeScreen({Key? key}) : super(key: key); @@ -17,8 +16,9 @@ class RecipeScreen extends StatelessWidget { static Widget builder(BuildContext context) { final recipeID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( - create: (context) => RecipeBloc(RecipeState(recipeModelObj: RecipeModel(recipeID: recipeID.toString())))..add(RecipeInitialEvent()), - child: RecipeScreen(),); + create: (context) => RecipeBloc(RecipeState(recipeModelObj: RecipeModel(recipeID: recipeID.toString())))..add(RecipeInitialEvent()), + child: RecipeScreen(), + ); } Widget build(BuildContext context) { @@ -52,32 +52,33 @@ class RecipeScreen extends StatelessWidget { } } return Scaffold( - appBar: AppBar( - toolbarHeight: 0, - automaticallyImplyLeading: false, + appBar: AppBar( + toolbarHeight: 0, + automaticallyImplyLeading: false, + ), + resizeToAvoidBottomInset: false, + body: Container( + width: double.maxFinite, + decoration: AppDecoration.fillGray, + child: ListView( + children: [ + SizedBox(height: 15.v), + _buildHeaderRow(context, state), + SizedBox(height: 15.v), + _buildRecipeData(context, state), + SizedBox(height: 15.v), + Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: steps, + ), + SizedBox(height: 15.v), + _buildTextField(context, state), + SizedBox(height: 15.v), + _buildCommentSection(context, state), + ], ), - resizeToAvoidBottomInset: false, - body: Container( - width: double.maxFinite, - decoration: AppDecoration.fillGray, - child: ListView( - children: [ - SizedBox(height: 15.v), - _buildHeaderRow(context, state), - SizedBox(height: 15.v), - _buildRecipeData(context, state), - SizedBox(height: 15.v), - Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: steps, - ), - SizedBox(height: 15.v), - _buildTextField(context, state), - SizedBox(height: 15.v), - _buildCommentSection(context, state), - ], - ), - ),); + ), + ); } _buildHeaderRow(BuildContext context, RecipeLoadedState state) { @@ -119,7 +120,7 @@ class RecipeScreen extends StatelessWidget { ), ), CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (state.author?['profile_photo_path'] ?? ''), + imageUrl: baseUrl + '/storage/' + (state.author?['profile_photo_path'] ?? ''), imageBuilder: (context, imageProvider) => CircleAvatar( backgroundImage: imageProvider, radius: 25, @@ -159,75 +160,86 @@ class RecipeScreen extends StatelessWidget { ), ], ), - child: Column(mainAxisSize: MainAxisSize.min, children: [ - Row( - children: [ - Text( - state.recipe?['title'], - style: CustomTextStyles.titleMediumBlack, - ), - Spacer(), - PopupMenuButton( - onSelected: (value) => tapMenu(value, context, state), - itemBuilder: (BuildContext context) => >[ - PopupMenuItem( - value: 'edit', - child: Text('Редактировать'), - ), - PopupMenuItem( - value: 'delete', - child: Text('Удалить'), - ), - ], - ), - ], - ), - SizedBox(height: 8.0), - _buildImage(state), - SizedBox(height: 16.0), - Text( - state.recipe?['description'], - style: CustomTextStyles.bodyMediumBluegray800, - ), - SizedBox(height: 16.0), - Align( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Text( + state.recipe?['title'], + style: CustomTextStyles.titleMediumBlack, + ), + Spacer(), + PopupMenuButton( + onSelected: (value) => tapMenu(value, context, state), + itemBuilder: (BuildContext context) => >[ + PopupMenuItem( + value: 'edit', + child: Text('Редактировать'), + ), + PopupMenuItem( + value: 'delete', + child: Text('Удалить'), + ), + ], + ), + ], + ), + SizedBox(height: 8.0), + _buildImage(state), + SizedBox(height: 16.0), + Text( + state.recipe?['description'], + style: CustomTextStyles.bodyMediumBluegray800, + ), + SizedBox(height: 16.0), + Align( alignment: Alignment.topLeft, child: Text( DateFormat('dd.MM.yyyy').format(DateTime.parse(state.recipe?['updated_at'])), style: theme.textTheme.bodyMedium, - ),), - SizedBox(height: 16.0), - _buildTags(state.tags), - SizedBox(height: 16.0), - Row(children: [ - Padding( - padding: EdgeInsets.only(left: 24), - child: Row(children: [ - Padding( - padding: EdgeInsets.only(right: 8), - child: Icon(Icons.favorite_outline), - ), - Text( - "Нравится", - style: CustomTextStyles.titleMediumSemiBold, - ), - ],), + ), ), - Spacer(), - Padding( - padding: EdgeInsets.only(right: 24), - child: Row(children: [ - Padding( - padding: const EdgeInsets.only(right: 8), - child: Icon(Icons.share_outlined), + SizedBox(height: 16.0), + _buildTags(state.tags), + SizedBox(height: 16.0), + Row( + children: [ + Padding( + padding: EdgeInsets.only(left: 24), + child: Row( + children: [ + Padding( + padding: EdgeInsets.only(right: 8), + child: Icon(Icons.favorite_outline), + ), + Text( + "Нравится", + style: CustomTextStyles.titleMediumSemiBold, + ), + ], ), - Text( - "Поделиться", - style: CustomTextStyles.titleMediumSemiBold, + ), + Spacer(), + Padding( + padding: EdgeInsets.only(right: 24), + child: Row( + children: [ + Padding( + padding: const EdgeInsets.only(right: 8), + child: Icon(Icons.share_outlined), + ), + Text( + "Поделиться", + style: CustomTextStyles.titleMediumSemiBold, + ), + ], ), - ],),), - ],), - ],), + ), + ], + ), + ], + ), ); } @@ -245,7 +257,7 @@ class RecipeScreen extends StatelessWidget { _buildImage(RecipeLoadedState state) { return CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (state.recipe?['image'] ?? ''), + imageUrl: baseUrl + '/storage/' + (state.recipe?['image'] ?? ''), imageBuilder: (context, imageProvider) => Stack( children: [ ClipRRect( @@ -431,28 +443,31 @@ class RecipeScreen extends StatelessWidget { ), ], ), - child: Column(mainAxisSize: MainAxisSize.min, children: [ - Align( - alignment: Alignment.centerLeft, - child: Text( - "Шаг ${i + 1}", - style: CustomTextStyles.titleMediumSemiBold, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Align( + alignment: Alignment.centerLeft, + child: Text( + "Шаг ${i + 1}", + style: CustomTextStyles.titleMediumSemiBold, + ), ), - ), - SizedBox(height: 16.0), - CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (state.steps?[i]['image']), - width: double.infinity, - // Установите ширину равной ширине родительского элемента - height: 200.0, - // Задайте постоянную высоту элемента - fit: BoxFit.cover, - placeholder: (context, url) => CircularProgressIndicator(), - errorWidget: (context, url, error) => Icon(Icons.error), - ), - SizedBox(height: 16.0), - Text(state.steps?[i]['description']), - ],), + SizedBox(height: 16.0), + CachedNetworkImage( + imageUrl: baseUrl + '/storage/' + (state.steps?[i]['image']), + width: double.infinity, + // Установите ширину равной ширине родительского элемента + height: 200.0, + // Задайте постоянную высоту элемента + fit: BoxFit.cover, + placeholder: (context, url) => CircularProgressIndicator(), + errorWidget: (context, url, error) => Icon(Icons.error), + ), + SizedBox(height: 16.0), + Text(state.steps?[i]['description']), + ], + ), ); } } diff --git a/lib/presentation/recipe/recipe_show_screen/widgets/comment_widget.dart b/lib/presentation/recipe/recipe_show_screen/widgets/comment_widget.dart index ab177fa1..ed2e075c 100644 --- a/lib/presentation/recipe/recipe_show_screen/widgets/comment_widget.dart +++ b/lib/presentation/recipe/recipe_show_screen/widgets/comment_widget.dart @@ -1,10 +1,9 @@ // ignore_for_file: must_be_immutable -import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:cached_network_image/cached_network_image.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/presentation/feed/blog_post_screen/models/comment_model.dart'; -import 'package:cached_network_image/cached_network_image.dart'; +import 'package:flutter/material.dart'; class CommentWidget extends StatelessWidget { CommentWidget(this.commentModelObj, {Key? key}) @@ -36,13 +35,11 @@ class CommentWidget extends StatelessWidget { ], ), child: Row( - mainAxisAlignment: MainAxisAlignment - .spaceBetween, // Move the main axis alignment to space between - crossAxisAlignment: - CrossAxisAlignment.center, // Center the items vertically + mainAxisAlignment: MainAxisAlignment.spaceBetween, // Move the main axis alignment to space between + crossAxisAlignment: CrossAxisAlignment.center, // Center the items vertically children: [ CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + commentModelObj.userImage!, + imageUrl: baseUrl + '/storage/' + commentModelObj.userImage!, imageBuilder: (context, imageProvider) => CircleAvatar( backgroundImage: imageProvider, radius: 25, @@ -69,10 +66,7 @@ class CommentWidget extends StatelessWidget { child: Row( children: [ Text( - commentModelObj.username!.length <= 15 - ? commentModelObj.username! - : commentModelObj.username!.substring(0, 15) + - '...', + commentModelObj.username!.length <= 15 ? commentModelObj.username! : commentModelObj.username!.substring(0, 15) + '...', style: theme.textTheme.titleMedium, ), Spacer(), @@ -96,10 +90,11 @@ class CommentWidget extends StatelessWidget { ), ), CustomImageView( - imagePath: ImageConstant.imgSend, - height: 30.v, - width: 30.h, - margin: EdgeInsets.only(left: 5),), + imagePath: ImageConstant.imgSend, + height: 30.v, + width: 30.h, + margin: EdgeInsets.only(left: 5), + ), ], ), ); diff --git a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart deleted file mode 100644 index 1ade5821..00000000 --- a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart +++ /dev/null @@ -1,150 +0,0 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/additional_information_bloc.dart'; -import 'models/additional_information_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter/material.dart'; -import 'dart:convert'; -import 'package:hive/hive.dart'; -import 'package:http/http.dart' as http; - -class AdditionalInformationScreen extends StatelessWidget { - const AdditionalInformationScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => - AdditionalInformationBloc(AdditionalInformationState(additionalInformationModelObj: AdditionalInformationModel(userRegistrationSheet: sheet))) - ..add(AdditionalInformationInitialEvent()), - child: AdditionalInformationScreen(),); - } - - @override - Widget build(BuildContext context) { - return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), - child: Column(children: [ - SizedBox(height: 7.v), - Container( - height: 16.v, - width: 343.h, - decoration: BoxDecoration( - color: theme.colorScheme.onPrimary, - borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.h),), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: 1, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation(appTheme.blueA400),),),), - SizedBox(height: 20.v), - SizedBox(height: 73.v), - _buildTextFormField(context), - Spacer(), - BlocBuilder(builder: (context, state) { - return NextStepButton( - text: "finish".tr.toUpperCase(), - margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapFinish(state, context),); - },), - ],),),); - } - - onTapFinish(AdditionalInformationState state, BuildContext context) { - return () async { - UserRegistrationSheet sheet = state.additionalInformationModelObj!.userRegistrationSheet; - sheet.additionalInfo = state.editTextController!.text; - - final response = await http.post(Uri.parse(dotenv.env['SERVER_ROOT']! + '/register'), - headers: {'Content-Type': 'application/json', 'Accept': 'application/json'}, body: jsonEncode(sheet.toJson()), encoding: utf8,); - - var res = await jsonDecode(response.body); - if (response.statusCode == 200) { - final box = await Hive.openBox('token'); - final token = res['token']; - box.put('token', token); - GoRouter.of(context).goNamed('myProfileScreen'); - } else { - showErrorMessage(context, res['message']); - } - }; - } - - /// Section Widget - _buildAppBar(BuildContext context) { - return CustomAppBar( - leadingWidth: 31.h, - leading: - AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 18.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), - centerTitle: true, - title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); - } - - onTapBack(BuildContext context) { - return () { - onTapArrowLeft(context); - }; - } - - /// Section Widget - _buildTextFormField(BuildContext context) { - return SizedBox( - height: 315.v, - width: 343.h, - child: Stack(alignment: Alignment.center, children: [ - Align( - alignment: Alignment.center, - child: Column(mainAxisSize: MainAxisSize.min, children: [ - Container( - width: 294.h, - margin: EdgeInsets.only(left: 24.h, right: 23.h), - child: Text("enter_additional_information".tr, - maxLines: 2, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: CustomTextStyles.titleMediumSegoeUI,),), - SizedBox(height: 10.v), - BlocSelector( - selector: (state) => state.editTextController, - builder: (context, editTextController) { - return CustomTextFormField( - controller: editTextController, - hintText: "У меня крепкое здоровье, но последнее время часто утомляюсь, однако, это мне не мешает радоваться жизни", - textInputAction: TextInputAction.done, - maxLines: 8,); - },), - ],),), - ],),); - } - - /// Navigates to the previous screen. - onTapArrowLeft(BuildContext context) { - GoRouter.of(context).pop(); - } - - /// Displays an alert dialog when the action is triggered. - /// The dialog box contains a title and a message with the `Теперь вы можете пользоваться полным функционалом приложения` - showErrorMessage(BuildContext context, String text) { - showDialog( - context: context, - builder: (_) => AlertDialog( - title: const Text('Ошибка'), - content: Text(text), - actions: [TextButton(onPressed: onTapOk(context), child: const Text('Ok'))], - ),); - } - - onTapOk(BuildContext context) { - return () { - Navigator.pop(context); - }; - } -} diff --git a/lib/presentation/registration/additional_information_screen/bloc/additional_information_bloc.dart b/lib/presentation/registration/additional_information_screen/bloc/additional_information_bloc.dart deleted file mode 100644 index b2405c57..00000000 --- a/lib/presentation/registration/additional_information_screen/bloc/additional_information_bloc.dart +++ /dev/null @@ -1,22 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/additional_information_screen/models/additional_information_model.dart'; -part 'additional_information_event.dart'; -part 'additional_information_state.dart'; - -/// A bloc that manages the state of a AdditionalInformation according to the event that is dispatched to it. -class AdditionalInformationBloc - extends Bloc { - AdditionalInformationBloc(AdditionalInformationState initialState) - : super(initialState) { - on(_onInitialize); - } - - _onInitialize( - AdditionalInformationInitialEvent event, - Emitter emit, - ) async { - emit(state.copyWith(editTextController: TextEditingController())); - } -} diff --git a/lib/presentation/registration/additional_information_screen/bloc/additional_information_event.dart b/lib/presentation/registration/additional_information_screen/bloc/additional_information_event.dart deleted file mode 100644 index 71494f83..00000000 --- a/lib/presentation/registration/additional_information_screen/bloc/additional_information_event.dart +++ /dev/null @@ -1,16 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'additional_information_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///AdditionalInformation widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class AdditionalInformationEvent extends Equatable {} - -/// Event that is dispatched when the AdditionalInformation widget is first created. -class AdditionalInformationInitialEvent extends AdditionalInformationEvent { - @override - List get props => []; -} diff --git a/lib/presentation/registration/additional_information_screen/bloc/additional_information_state.dart b/lib/presentation/registration/additional_information_screen/bloc/additional_information_state.dart deleted file mode 100644 index 08dd10c4..00000000 --- a/lib/presentation/registration/additional_information_screen/bloc/additional_information_state.dart +++ /dev/null @@ -1,31 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'additional_information_bloc.dart'; - -/// Represents the state of AdditionalInformation in the application. -class AdditionalInformationState extends Equatable { - AdditionalInformationState({ - this.editTextController, - this.additionalInformationModelObj, - }); - - TextEditingController? editTextController; - - AdditionalInformationModel? additionalInformationModelObj; - - @override - List get props => [ - editTextController, - additionalInformationModelObj, - ]; - AdditionalInformationState copyWith({ - TextEditingController? editTextController, - AdditionalInformationModel? additionalInformationModelObj, - }) { - return AdditionalInformationState( - editTextController: editTextController ?? this.editTextController, - additionalInformationModelObj: - additionalInformationModelObj ?? this.additionalInformationModelObj, - ); - } -} diff --git a/lib/presentation/registration/additional_information_screen/models/additional_information_model.dart b/lib/presentation/registration/additional_information_screen/models/additional_information_model.dart deleted file mode 100644 index ff001d96..00000000 --- a/lib/presentation/registration/additional_information_screen/models/additional_information_model.dart +++ /dev/null @@ -1,20 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; - -/// This class defines the variables used in the [additional_information_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class AdditionalInformationModel extends Equatable { - UserRegistrationSheet userRegistrationSheet; - AdditionalInformationModel({required this.userRegistrationSheet}); - - AdditionalInformationModel copyWith() { - return AdditionalInformationModel( - userRegistrationSheet: userRegistrationSheet, - ); - } - - @override - List get props => [userRegistrationSheet]; -} diff --git a/lib/presentation/registration/allergies_screen/allergies_screen.dart b/lib/presentation/registration/allergies_screen/allergies_screen.dart deleted file mode 100644 index 30e218c2..00000000 --- a/lib/presentation/registration/allergies_screen/allergies_screen.dart +++ /dev/null @@ -1,119 +0,0 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/allergies_bloc.dart'; -import 'models/allergies_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; - -class AllergiesScreen extends StatefulWidget { - const AllergiesScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => AllergiesBloc(AllergiesState(allergiesModelObj: AllergiesModel(userRegistrationSheet: sheet)))..add(AllergiesInitialEvent()), - child: AllergiesScreen(),); - } - - @override - State createState() => _AllergiesScreenState(); -} - -class _AllergiesScreenState extends State { - @override - Widget build(BuildContext context) { - return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), - child: Column(children: [ - SizedBox(height: 7.v), - Container( - height: 16.v, - width: 343.h, - decoration: BoxDecoration( - color: theme.colorScheme.onPrimary, - borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.h),), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: 0.76, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation(appTheme.blueA400),),),), - SizedBox(height: 22.v), - Text("allergies_presence".tr, style: theme.textTheme.headlineSmall), - Spacer(flex: 36), - _buildTextFormField(context), - Spacer(flex: 54), - BlocBuilder(builder: (context, state) { - return NextStepButton( - text: "continue".tr.toUpperCase(), - margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapContinue(state, context),); - },), - BlocBuilder(builder: (context, state) { - return GestureDetector( - onTap: onTapSkip(state, context), - child: Text("skip".tr, style: theme.textTheme.bodyLarge), - ); - },), - ],),),); - } - - onTapSkip(AllergiesState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.allergiesModelObj!.userRegistrationSheet; - GoRouter.of(context).goNamed('medicineIntakeScreen', extra: sheet); - }; - } - - onTapContinue(AllergiesState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.allergiesModelObj!.userRegistrationSheet; - sheet.aboutAllergy = state.enterInformationController!.text; - GoRouter.of(context).goNamed('medicineIntakeScreen', extra: sheet); - }; - } - - /// Section Widget - _buildAppBar(BuildContext context) { - return CustomAppBar( - leadingWidth: 31.h, - leading: - AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 18.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), - centerTitle: true, - title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); - } - - onTapBack(BuildContext context) { - return () { - onTapArrowLeft(context); - }; - } - - /// Section Widget - _buildTextFormField(BuildContext context) { - return Column(children: [ - Text("fill_in_information".tr, style: CustomTextStyles.titleMediumSegoeUI), - SizedBox(height: 2.v), - BlocSelector( - selector: (state) => state.enterInformationController, - builder: (context, enterInformationController) { - return CustomTextFormField( - controller: enterInformationController, hintText: "enter_information".tr, textInputAction: TextInputAction.done, maxLines: 8,); - },), - ],); - } - - /// Navigates to the previous screen. - onTapArrowLeft(BuildContext context) { - GoRouter.of(context).pop(); - } -} diff --git a/lib/presentation/registration/allergies_screen/bloc/allergies_bloc.dart b/lib/presentation/registration/allergies_screen/bloc/allergies_bloc.dart deleted file mode 100644 index f4cf7a22..00000000 --- a/lib/presentation/registration/allergies_screen/bloc/allergies_bloc.dart +++ /dev/null @@ -1,20 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/allergies_screen/models/allergies_model.dart'; -part 'allergies_event.dart'; -part 'allergies_state.dart'; - -/// A bloc that manages the state of a Allergies according to the event that is dispatched to it. -class AllergiesBloc extends Bloc { - AllergiesBloc(AllergiesState initialState) : super(initialState) { - on(_onInitialize); - } - - _onInitialize( - AllergiesInitialEvent event, - Emitter emit, - ) async { - emit(state.copyWith(enterInformationController: TextEditingController())); - } -} diff --git a/lib/presentation/registration/allergies_screen/bloc/allergies_event.dart b/lib/presentation/registration/allergies_screen/bloc/allergies_event.dart deleted file mode 100644 index 8892cc35..00000000 --- a/lib/presentation/registration/allergies_screen/bloc/allergies_event.dart +++ /dev/null @@ -1,16 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'allergies_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///Allergies widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class AllergiesEvent extends Equatable {} - -/// Event that is dispatched when the Allergies widget is first created. -class AllergiesInitialEvent extends AllergiesEvent { - @override - List get props => []; -} diff --git a/lib/presentation/registration/allergies_screen/bloc/allergies_state.dart b/lib/presentation/registration/allergies_screen/bloc/allergies_state.dart deleted file mode 100644 index a63c52d8..00000000 --- a/lib/presentation/registration/allergies_screen/bloc/allergies_state.dart +++ /dev/null @@ -1,31 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'allergies_bloc.dart'; - -/// Represents the state of Allergies in the application. -class AllergiesState extends Equatable { - AllergiesState({ - this.enterInformationController, - this.allergiesModelObj, - }); - - TextEditingController? enterInformationController; - - AllergiesModel? allergiesModelObj; - - @override - List get props => [ - enterInformationController, - allergiesModelObj, - ]; - AllergiesState copyWith({ - TextEditingController? enterInformationController, - AllergiesModel? allergiesModelObj, - }) { - return AllergiesState( - enterInformationController: - enterInformationController ?? this.enterInformationController, - allergiesModelObj: allergiesModelObj ?? this.allergiesModelObj, - ); - } -} diff --git a/lib/presentation/registration/allergies_screen/models/allergies_model.dart b/lib/presentation/registration/allergies_screen/models/allergies_model.dart deleted file mode 100644 index ebd20063..00000000 --- a/lib/presentation/registration/allergies_screen/models/allergies_model.dart +++ /dev/null @@ -1,20 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; - -/// This class defines the variables used in the [allergies_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class AllergiesModel extends Equatable { - UserRegistrationSheet userRegistrationSheet; - AllergiesModel({required this.userRegistrationSheet}); - - AllergiesModel copyWith() { - return AllergiesModel( - userRegistrationSheet: userRegistrationSheet, - ); - } - - @override - List get props => [userRegistrationSheet]; -} diff --git a/lib/presentation/registration/app_navigation_screen/app_navigation_screen.dart b/lib/presentation/registration/app_navigation_screen/app_navigation_screen.dart deleted file mode 100644 index cbf92f01..00000000 --- a/lib/presentation/registration/app_navigation_screen/app_navigation_screen.dart +++ /dev/null @@ -1,233 +0,0 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/app_navigation_bloc.dart'; -import 'models/app_navigation_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:flutter/material.dart'; - -class AppNavigationScreen extends StatefulWidget { - const AppNavigationScreen({Key? key}) - : super( - key: key, - ); - - static Widget builder(BuildContext context) { - return BlocProvider( - create: (context) => AppNavigationBloc(AppNavigationState( - appNavigationModelObj: AppNavigationModel(), - ),) - ..add(AppNavigationInitialEvent()), - child: AppNavigationScreen(), - ); - } - - @override - State createState() => _AppNavigationScreenState(); -} - -class _AppNavigationScreenState extends State { - @override - Widget build(BuildContext context) { - mediaQueryData = MediaQuery.of(context); - - return BlocBuilder( - builder: (context, state) { - return SafeArea( - child: Scaffold( - backgroundColor: Color(0XFFFFFFFF), - body: SizedBox( - width: double.maxFinite, - child: Column( - children: [ - _buildAppNavigation(context), - Expanded( - child: SingleChildScrollView( - child: Container( - decoration: BoxDecoration( - color: Color(0XFFFFFFFF), - ), - child: Column( - children: [ - _buildScreenTitle( - context, - screenTitle: "date_of_birth".tr, - onTapScreenTitle: () => GoRouter.of(context).goNamed('dateOfBirthScreen'), - ), - _buildScreenTitle( - context, - screenTitle: "city_of_living".tr, - onTapScreenTitle: () => GoRouter.of(context).goNamed('cityOfLivingScreen'), - ), - _buildScreenTitle( - context, - screenTitle: "body_circumferences".tr, - onTapScreenTitle: () => GoRouter.of(context).goNamed('bodyCircumferencesScreen'), - ), - _buildScreenTitle( - context, - screenTitle: "weight".tr, - onTapScreenTitle: () => GoRouter.of(context).goNamed('weightScreen'), - ), - _buildScreenTitle( - context, - screenTitle: "allergies".tr, - onTapScreenTitle: () => GoRouter.of(context).goNamed('allergiesScreen'), - ), - _buildScreenTitle( - context, - screenTitle: "medicine_intake".tr, - onTapScreenTitle: () => GoRouter.of(context).goNamed('medicineIntakeScreen'), - ), - _buildScreenTitle( - context, - screenTitle: "splash_screen".tr, - onTapScreenTitle: () => GoRouter.of(context).goNamed('splashScreen'), - ), - _buildScreenTitle( - context, - screenTitle: "gender".tr, - onTapScreenTitle: () => GoRouter.of(context).goNamed('genderScreen'), - ), - _buildScreenTitle( - context, - screenTitle: "blood_pressure".tr, - onTapScreenTitle: () => GoRouter.of(context).goNamed('bloodPressureScreen'), - ), - _buildScreenTitle( - context, - screenTitle: "favorite_sports".tr, - onTapScreenTitle: () => GoRouter.of(context).goNamed('favoriteSportsScreen'), - ), - _buildScreenTitle( - context, - screenTitle: "favorite_foods".tr, - onTapScreenTitle: () => GoRouter.of(context).goNamed('favoriteFoodsScreen'), - ), - _buildScreenTitle( - context, - screenTitle: "schedule".tr, - onTapScreenTitle: () => GoRouter.of(context).goNamed('scheduleScreen'), - ), - _buildScreenTitle( - context, - screenTitle: "additional_information".tr, - onTapScreenTitle: () => GoRouter.of(context).goNamed('additionalInformationScreen'), - ), - _buildScreenTitle( - context, - screenTitle: "language_select".tr, - onTapScreenTitle: () => GoRouter.of(context).goNamed('languageSelectScreen'), - ), - _buildScreenTitle( - context, - screenTitle: "auth".tr, - onTapScreenTitle: () => GoRouter.of(context).goNamed('authScreen'), - ), - ], - ), - ), - ), - ), - ], - ), - ), - ), - ); - }, - ); - } - - /// Section Widget - _buildAppNavigation(BuildContext context) { - return Container( - decoration: BoxDecoration( - color: Color(0XFFFFFFFF), - ), - child: Column( - children: [ - SizedBox(height: 10.v), - Align( - alignment: Alignment.centerLeft, - child: Padding( - padding: EdgeInsets.symmetric(horizontal: 20.h), - child: Text( - "App Navigation".tr, - textAlign: TextAlign.center, - style: TextStyle( - color: Color(0XFF000000), - fontSize: 20.fSize, - fontWeight: FontWeight.w400, - ), - ), - ), - ), - SizedBox(height: 10.v), - Align( - alignment: Alignment.centerLeft, - child: Padding( - padding: EdgeInsets.only(left: 20.h), - child: Text( - "Check your app's UI from the below demo screens of your app.".tr, - textAlign: TextAlign.center, - style: TextStyle( - color: Color(0XFF888888), - fontSize: 16.fSize, - fontWeight: FontWeight.w400, - ), - ), - ), - ), - SizedBox(height: 5.v), - Divider( - height: 1.v, - thickness: 1.v, - color: Color(0XFF000000), - ), - ], - ), - ); - } - - /// Common widget - _buildScreenTitle( - BuildContext context, { - required String screenTitle, - Function? onTapScreenTitle, - }) { - return GestureDetector( - onTap: onTapScreenTitle!.call(), - child: Container( - decoration: BoxDecoration( - color: Color(0XFFFFFFFF), - ), - child: Column( - children: [ - SizedBox(height: 10.v), - Align( - alignment: Alignment.centerLeft, - child: Padding( - padding: EdgeInsets.symmetric(horizontal: 20.h), - child: Text( - screenTitle, - textAlign: TextAlign.center, - style: TextStyle( - color: Color(0XFF000000), - fontSize: 20.fSize, - fontWeight: FontWeight.w400, - ), - ), - ), - ), - SizedBox(height: 10.v), - SizedBox(height: 5.v), - Divider( - height: 1.v, - thickness: 1.v, - color: Color(0XFF888888), - ), - ], - ), - ), - ); - } -} diff --git a/lib/presentation/registration/app_navigation_screen/bloc/app_navigation_bloc.dart b/lib/presentation/registration/app_navigation_screen/bloc/app_navigation_bloc.dart deleted file mode 100644 index adb51100..00000000 --- a/lib/presentation/registration/app_navigation_screen/bloc/app_navigation_bloc.dart +++ /dev/null @@ -1,18 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/app_navigation_screen/models/app_navigation_model.dart'; -part 'app_navigation_event.dart'; -part 'app_navigation_state.dart'; - -/// A bloc that manages the state of a AppNavigation according to the event that is dispatched to it. -class AppNavigationBloc extends Bloc { - AppNavigationBloc(AppNavigationState initialState) : super(initialState) { - on(_onInitialize); - } - - _onInitialize( - AppNavigationInitialEvent event, - Emitter emit, - ) async {} -} diff --git a/lib/presentation/registration/app_navigation_screen/bloc/app_navigation_event.dart b/lib/presentation/registration/app_navigation_screen/bloc/app_navigation_event.dart deleted file mode 100644 index 649738e6..00000000 --- a/lib/presentation/registration/app_navigation_screen/bloc/app_navigation_event.dart +++ /dev/null @@ -1,16 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'app_navigation_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///AppNavigation widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class AppNavigationEvent extends Equatable {} - -/// Event that is dispatched when the AppNavigation widget is first created. -class AppNavigationInitialEvent extends AppNavigationEvent { - @override - List get props => []; -} diff --git a/lib/presentation/registration/app_navigation_screen/bloc/app_navigation_state.dart b/lib/presentation/registration/app_navigation_screen/bloc/app_navigation_state.dart deleted file mode 100644 index 2ee33461..00000000 --- a/lib/presentation/registration/app_navigation_screen/bloc/app_navigation_state.dart +++ /dev/null @@ -1,21 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'app_navigation_bloc.dart'; - -/// Represents the state of AppNavigation in the application. -class AppNavigationState extends Equatable { - AppNavigationState({this.appNavigationModelObj}); - - AppNavigationModel? appNavigationModelObj; - - @override - List get props => [ - appNavigationModelObj, - ]; - AppNavigationState copyWith({AppNavigationModel? appNavigationModelObj}) { - return AppNavigationState( - appNavigationModelObj: - appNavigationModelObj ?? this.appNavigationModelObj, - ); - } -} diff --git a/lib/presentation/registration/app_navigation_screen/models/app_navigation_model.dart b/lib/presentation/registration/app_navigation_screen/models/app_navigation_model.dart deleted file mode 100644 index 73fd71d7..00000000 --- a/lib/presentation/registration/app_navigation_screen/models/app_navigation_model.dart +++ /dev/null @@ -1,16 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; - -/// This class defines the variables used in the [app_navigation_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class AppNavigationModel extends Equatable { - AppNavigationModel(); - - AppNavigationModel copyWith() { - return AppNavigationModel(); - } - - @override - List get props => []; -} diff --git a/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_bloc.dart b/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_bloc.dart deleted file mode 100644 index 47416549..00000000 --- a/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_bloc.dart +++ /dev/null @@ -1,61 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/blood_pressure_screen/models/blood_pressure_model.dart'; -part 'blood_pressure_event.dart'; -part 'blood_pressure_state.dart'; - -/// A bloc that manages the state of a BloodPressure according to the event that is dispatched to it. -class BloodPressureBloc extends Bloc { - BloodPressureBloc(BloodPressureState initialState) : super(initialState) { - on(_onInitialize); - on(_changeHypoDropDown); - on(_changeHyperDropDown); - } - - _changeHyperDropDown( - ChangeHyperDropDownEvent event, - Emitter emit, - ) { - if (event.value.id == 1) { - state.bloodPressureModelObj!.userRegistrationSheet.hasHyper = '1'; - } else { - state.bloodPressureModelObj!.userRegistrationSheet.hasHyper = '0'; - } - emit(state.copyWith(selectedHyperValue: event.value)); - } - - _changeHypoDropDown( - ChangeHypoDownEvent event, - Emitter emit, - ) { - if (event.value.id == 1) { - state.bloodPressureModelObj!.userRegistrationSheet.hasHypo = '1'; - } else { - state.bloodPressureModelObj!.userRegistrationSheet.hasHypo = '0'; - } - emit(state.copyWith(selectedHypoValue: event.value)); - } - - List fillDropdownItemList() { - return [ - SelectionPopupModel( - id: 1, - title: "Да", - ), - SelectionPopupModel(id: 2, title: "Нет", isSelected: true), - ]; - } - - _onInitialize( - BloodPressureInitialEvent event, - Emitter emit, - ) async { - emit(state.copyWith( - upPressureController: TextEditingController(), - downPressureController: TextEditingController(),),); - emit(state.copyWith( - bloodPressureModelObj: state.bloodPressureModelObj - ?.copyWith(dropdownItemList: fillDropdownItemList()),),); - } -} diff --git a/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_event.dart b/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_event.dart deleted file mode 100644 index 677d2436..00000000 --- a/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_event.dart +++ /dev/null @@ -1,39 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'blood_pressure_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///BloodPressure widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class BloodPressureEvent extends Equatable {} - -/// Event that is dispatched when the BloodPressure widget is first created. -class BloodPressureInitialEvent extends BloodPressureEvent { - @override - List get props => []; -} - -///event for dropdown selection -class ChangeHyperDropDownEvent extends BloodPressureEvent { - ChangeHyperDropDownEvent({required this.value}); - - SelectionPopupModel value; - - @override - List get props => [ - value, - ]; -} - -class ChangeHypoDownEvent extends BloodPressureEvent { - ChangeHypoDownEvent({required this.value}); - - SelectionPopupModel value; - - @override - List get props => [ - value, - ]; -} diff --git a/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_state.dart b/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_state.dart deleted file mode 100644 index d1db1c49..00000000 --- a/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_state.dart +++ /dev/null @@ -1,50 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'blood_pressure_bloc.dart'; - -/// Represents the state of BloodPressure in the application. -class BloodPressureState extends Equatable { - BloodPressureState({ - this.upPressureController, - this.downPressureController, - this.selectedHyperValue, - this.selectedHypoValue, - this.bloodPressureModelObj, - }); - - TextEditingController? upPressureController; - - TextEditingController? downPressureController; - - SelectionPopupModel? selectedHypoValue; - - SelectionPopupModel? selectedHyperValue; - - BloodPressureModel? bloodPressureModelObj; - - @override - List get props => [ - upPressureController, - downPressureController, - selectedHyperValue, - selectedHypoValue, - bloodPressureModelObj, - ]; - BloodPressureState copyWith({ - TextEditingController? upPressureController, - TextEditingController? downPressureController, - SelectionPopupModel? selectedHyperValue, - SelectionPopupModel? selectedHypoValue, - BloodPressureModel? bloodPressureModelObj, - }) { - return BloodPressureState( - upPressureController: upPressureController ?? this.upPressureController, - downPressureController: - downPressureController ?? this.downPressureController, - selectedHyperValue: selectedHyperValue ?? this.selectedHyperValue, - selectedHypoValue: selectedHypoValue ?? this.selectedHypoValue, - bloodPressureModelObj: - bloodPressureModelObj ?? this.bloodPressureModelObj, - ); - } -} diff --git a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart b/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart deleted file mode 100644 index 1aabdbd4..00000000 --- a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart +++ /dev/null @@ -1,241 +0,0 @@ -import 'package:eatvio_app/app_router.dart'; -import 'package:go_router/go_router.dart'; - -import 'bloc/blood_pressure_bloc.dart'; -import 'package:flutter/services.dart'; -import 'models/blood_pressure_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/custom_drop_down.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; - -class BloodPressureScreen extends StatefulWidget { - const BloodPressureScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => - BloodPressureBloc(BloodPressureState(bloodPressureModelObj: BloodPressureModel(userRegistrationSheet: sheet)))..add(BloodPressureInitialEvent()), - child: BloodPressureScreen(),); - } - - @override - State createState() => _BloodPressureScreenState(); -} - -class _BloodPressureScreenState extends State { - @override - Widget build(BuildContext context) { - final digitsOnly = FilteringTextInputFormatter.digitsOnly; - return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 12.h, vertical: 9.v), - child: Column(children: [ - SizedBox(height: 7.v), - Container( - height: 16.v, - width: 343.h, - padding: EdgeInsets.symmetric(horizontal: 4.h), - // Apply padding directly to the Container - decoration: BoxDecoration( - color: theme.colorScheme.onPrimary, - borderRadius: BorderRadius.circular(8.h), - border: Border.all( - color: theme.colorScheme.primary, - width: 1.h, - ), - ), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: 0.62, - backgroundColor: theme.colorScheme.onPrimary, - valueColor: AlwaysStoppedAnimation(appTheme.blueA400), - ), - ), - ), - SizedBox(height: 21.v), - SizedBox( - width: 224.h, - child: Text("your_blood_pressure".tr, - maxLines: 2, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: theme.textTheme.headlineSmall,),), - SizedBox(height: 21.v), - Container( - margin: EdgeInsets.only(right: 1.h), - padding: EdgeInsets.symmetric(horizontal: 3.h), - child: Column(children: [ - Text("up_pressure".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 2.v), - BlocSelector( - selector: (state) => state.upPressureController, - builder: (context, upPressureController) { - return CustomTextFormField(inputFormatters: [digitsOnly], controller: upPressureController, hintText: "90".tr); - },), - ],),), - SizedBox(height: 21.v), - Container( - margin: EdgeInsets.only(right: 1.h), - padding: EdgeInsets.symmetric(horizontal: 3.h), - child: Column(children: [ - Text("down_pressure".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 2.v), - BlocSelector( - selector: (state) => state.downPressureController, - builder: (context, downPressureController) { - return CustomTextFormField(inputFormatters: [digitsOnly], controller: downPressureController, hintText: "90".tr); - },), - ],),), - SizedBox(height: 22.v), - Text("do_you_have_hypotension_tendency".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 2.v), - Padding( - padding: EdgeInsets.symmetric(horizontal: 4.h), - child: BlocSelector( - selector: (state) => state.bloodPressureModelObj, - builder: (context, bloodPressureModelObj) { - return CustomDropDown( - icon: Container( - margin: EdgeInsets.fromLTRB(30.h, 11.v, 13.h, 11.v), - decoration: BoxDecoration(borderRadius: BorderRadius.circular(1.h)), - child: CustomImageView(imagePath: ImageConstant.imgFavorite, height: 12.adaptSize, width: 12.adaptSize),), - hintText: "Не выбрано".tr, - items: bloodPressureModelObj?.dropdownItemList ?? [], - onChanged: onChangeHyper(context),); - },),), - SizedBox(height: 22.v), - Text("do_you_have_hypertension_tendency".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 2.v), - Padding( - padding: EdgeInsets.symmetric(horizontal: 4.h), - child: BlocSelector( - selector: (state) => state.bloodPressureModelObj, - builder: (context, bloodPressureModelObj) { - return CustomDropDown( - icon: Container( - margin: EdgeInsets.fromLTRB(30.h, 11.v, 13.h, 11.v), - decoration: BoxDecoration(borderRadius: BorderRadius.circular(1.h)), - child: CustomImageView(imagePath: ImageConstant.imgFavorite, height: 12.adaptSize, width: 12.adaptSize),), - hintText: "Не выбрано".tr, - items: bloodPressureModelObj?.dropdownItemList ?? [], - onChanged: onChangeHypo(context),); - },),), - Spacer(), - BlocBuilder(builder: (context, state) { - return NextStepButton( - text: "continue".tr.toUpperCase(), - margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapContinue(state, context),); - },), - BlocBuilder(builder: (context, state) { - return GestureDetector( - onTap: onTapSkip(state, context), - child: Text("skip".tr, style: theme.textTheme.bodyLarge), - ); - },), - ],),),); - } - - onTapSkip(BloodPressureState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.bloodPressureModelObj!.userRegistrationSheet; - AppRouter.navigatorKey.currentContext?.goNamed('allergiesScreen', extra: sheet); - }; - } - - onTapContinue(BloodPressureState state, BuildContext context) { - return () { - List errors = validateFields(state.upPressureController!.text, state.downPressureController!.text); - if (errors.isEmpty) { - UserRegistrationSheet sheet = state.bloodPressureModelObj!.userRegistrationSheet; - sheet.bloodPressureUp = state.upPressureController!.text; - sheet.bloodPressureDown = state.downPressureController!.text; - AppRouter.navigatorKey.currentContext?.goNamed('favoriteSportsScreen', extra: sheet); - } else { - String errorMessage = ''; - - for (var error in errors) { - errorMessage += error + '\n\n'; - } - - 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); - }; - } - - onChangeHypo(BuildContext context) { - return (value) { - context.read().add(ChangeHyperDropDownEvent(value: value)); - }; - } - - onChangeHyper(BuildContext context) { - return (value) { - context.read().add(ChangeHypoDownEvent(value: value)); - }; - } - - /// Section Widget - _buildAppBar(BuildContext context) { - return CustomAppBar( - leadingWidth: 29.h, - leading: - AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), - centerTitle: true, - title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); - } - - Function onTapBack(BuildContext context) { - return () { - onTapArrowLeft(context); - }; - } - - /// Navigates to the previous screen. - onTapArrowLeft(BuildContext context) { - GoRouter.of(context).pop(); - } - - List validateFields( - String bloodPressureUp, - String bloodPressureDown, - ) { - List errors = []; - - if (bloodPressureUp.isEmpty | bloodPressureDown.isEmpty) { - errors.add('pressure_empty'.tr); - } - - if (![bloodPressureUp, bloodPressureDown].every((pressure) => int.tryParse(pressure) != null)) { - errors.add('pressure_is_not_a_number'.tr); - } - - return errors; - } -} diff --git a/lib/presentation/registration/blood_pressure_screen/models/blood_pressure_model.dart b/lib/presentation/registration/blood_pressure_screen/models/blood_pressure_model.dart deleted file mode 100644 index 2d8463ef..00000000 --- a/lib/presentation/registration/blood_pressure_screen/models/blood_pressure_model.dart +++ /dev/null @@ -1,25 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; -import 'package:eatvio_app/data/models/selectionPopupModel/selection_popup_model.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; - -/// This class defines the variables used in the [blood_pressure_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class BloodPressureModel extends Equatable { - UserRegistrationSheet userRegistrationSheet; - BloodPressureModel( - {required this.userRegistrationSheet, this.dropdownItemList = const [],}); - - List dropdownItemList; - - BloodPressureModel copyWith({List? dropdownItemList}) { - return BloodPressureModel( - userRegistrationSheet: userRegistrationSheet, - dropdownItemList: dropdownItemList ?? this.dropdownItemList, - ); - } - - @override - List get props => [dropdownItemList, userRegistrationSheet]; -} diff --git a/lib/presentation/registration/body_circumferences_screen/bloc/body_circumferences_bloc.dart b/lib/presentation/registration/body_circumferences_screen/bloc/body_circumferences_bloc.dart deleted file mode 100644 index 871ff8dc..00000000 --- a/lib/presentation/registration/body_circumferences_screen/bloc/body_circumferences_bloc.dart +++ /dev/null @@ -1,25 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/body_circumferences_screen/models/body_circumferences_model.dart'; -part 'body_circumferences_event.dart'; -part 'body_circumferences_state.dart'; - -/// A bloc that manages the state of a BodyCircumferences according to the event that is dispatched to it. -class BodyCircumferencesBloc - extends Bloc { - BodyCircumferencesBloc(BodyCircumferencesState initialState) - : super(initialState) { - on(_onInitialize); - } - - _onInitialize( - BodyCircumferencesInitialEvent event, - Emitter emit, - ) async { - emit(state.copyWith( - chestCircumferenceController: TextEditingController(), - waistCircumferenceController: TextEditingController(), - hipCircumferenceController: TextEditingController(),),); - } -} diff --git a/lib/presentation/registration/body_circumferences_screen/bloc/body_circumferences_event.dart b/lib/presentation/registration/body_circumferences_screen/bloc/body_circumferences_event.dart deleted file mode 100644 index d164270e..00000000 --- a/lib/presentation/registration/body_circumferences_screen/bloc/body_circumferences_event.dart +++ /dev/null @@ -1,16 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'body_circumferences_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///BodyCircumferences widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class BodyCircumferencesEvent extends Equatable {} - -/// Event that is dispatched when the BodyCircumferences widget is first created. -class BodyCircumferencesInitialEvent extends BodyCircumferencesEvent { - @override - List get props => []; -} diff --git a/lib/presentation/registration/body_circumferences_screen/bloc/body_circumferences_state.dart b/lib/presentation/registration/body_circumferences_screen/bloc/body_circumferences_state.dart deleted file mode 100644 index df28755c..00000000 --- a/lib/presentation/registration/body_circumferences_screen/bloc/body_circumferences_state.dart +++ /dev/null @@ -1,46 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'body_circumferences_bloc.dart'; - -/// Represents the state of BodyCircumferences in the application. -class BodyCircumferencesState extends Equatable { - BodyCircumferencesState({ - this.chestCircumferenceController, - this.waistCircumferenceController, - this.hipCircumferenceController, - this.bodyCircumferencesModelObj, - }); - - TextEditingController? chestCircumferenceController; - - TextEditingController? waistCircumferenceController; - - TextEditingController? hipCircumferenceController; - - BodyCircumferencesModel? bodyCircumferencesModelObj; - - @override - List get props => [ - chestCircumferenceController, - waistCircumferenceController, - hipCircumferenceController, - bodyCircumferencesModelObj, - ]; - BodyCircumferencesState copyWith({ - TextEditingController? chestCircumferenceController, - TextEditingController? waistCircumferenceController, - TextEditingController? hipCircumferenceController, - BodyCircumferencesModel? bodyCircumferencesModelObj, - }) { - return BodyCircumferencesState( - chestCircumferenceController: - chestCircumferenceController ?? this.chestCircumferenceController, - waistCircumferenceController: - waistCircumferenceController ?? this.waistCircumferenceController, - hipCircumferenceController: - hipCircumferenceController ?? this.hipCircumferenceController, - bodyCircumferencesModelObj: - bodyCircumferencesModelObj ?? this.bodyCircumferencesModelObj, - ); - } -} diff --git a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart b/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart deleted file mode 100644 index 3326d45a..00000000 --- a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart +++ /dev/null @@ -1,170 +0,0 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/body_circumferences_bloc.dart'; -import 'package:flutter/services.dart'; -import 'models/body_circumferences_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; - -class BodyCircumferencesScreen extends StatelessWidget { - const BodyCircumferencesScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => BodyCircumferencesBloc(BodyCircumferencesState(bodyCircumferencesModelObj: BodyCircumferencesModel(userRegistrationSheet: sheet))) - ..add(BodyCircumferencesInitialEvent()), - child: BodyCircumferencesScreen(), - ); - } - - @override - Widget build(BuildContext context) { - final digitsOnly = FilteringTextInputFormatter.digitsOnly; - mediaQueryData = MediaQuery.of(context); - return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), - child: Column(children: [ - SizedBox(height: 7.v), - Container( - height: 16.v, - width: 343.h, - decoration: BoxDecoration( - color: theme.colorScheme.onPrimary, - borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.h),), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: 0.40, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation(appTheme.blueA400),),),), - SizedBox(height: 39.v), - Text("initial_measurements".tr, style: theme.textTheme.headlineSmall), - SizedBox(height: 93.v), - Column(children: [ - Text("chest_circumference".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 3.v), - BlocSelector( - selector: (state) => state.chestCircumferenceController, - builder: (context, chestCircumferenceController) { - return CustomTextFormField(inputFormatters: [digitsOnly], controller: chestCircumferenceController, hintText: "90".tr); - },), - ],), - SizedBox(height: 19.v), - Text("waist_circumference".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 5.v), - BlocSelector( - selector: (state) => state.waistCircumferenceController, - builder: (context, waistCircumferenceController) { - return CustomTextFormField(inputFormatters: [digitsOnly], controller: waistCircumferenceController, hintText: "60".tr); - },), - SizedBox(height: 21.v), - Text("hip_circumference".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 3.v), - BlocSelector( - selector: (state) => state.hipCircumferenceController, - builder: (context, hipCircumferenceController) { - return CustomTextFormField( - inputFormatters: [digitsOnly], controller: hipCircumferenceController, hintText: "90".tr, textInputAction: TextInputAction.done,); - },), - Spacer(), - BlocBuilder(builder: (context, state) { - return NextStepButton( - text: "continue".tr.toUpperCase(), - margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapContinue(state, context),); - },), - ],),),); - } - - onTapContinue(BodyCircumferencesState state, BuildContext context) { - return () { - List errors = - validateFields(state.chestCircumferenceController!.text, state.waistCircumferenceController!.text, state.hipCircumferenceController!.text); - if (errors.isEmpty) { - UserRegistrationSheet sheet = state.bodyCircumferencesModelObj!.userRegistrationSheet; - sheet.chestCircumference = state.chestCircumferenceController!.text; - sheet.waistCircumference = state.waistCircumferenceController!.text; - sheet.hipCircumference = state.hipCircumferenceController!.text; - GoRouter.of(context).goNamed('weightScreen', extra: sheet); - } else { - String errorMessage = ''; - - for (var error in errors) { - errorMessage += error + '\n\n'; - } - - 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); - }; - } - - /// Section Widget - _buildAppBar(BuildContext context) { - return CustomAppBar( - leadingWidth: 29.h, - leading: - AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), - centerTitle: true, - title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); - } - - Function onTapBack(BuildContext context) { - return () { - onTapArrowLeft(context); - }; - } - - /// Navigates to the previous screen. - onTapArrowLeft(BuildContext context) { - GoRouter.of(context).pop(); - } - - /// Navigates to the weightScreen when the action is triggered. - navigateToWeight(BuildContext context) => GoRouter.of(context).goNamed('weightScreen'); - - List validateFields( - String chestCircumference, - String waistCircumference, - String hipCircumference, - ) { - List errors = []; - - if (chestCircumference.isEmpty | waistCircumference.isEmpty | hipCircumference.isEmpty) { - errors.add('circumference_empty'.tr); - } - - if (![chestCircumference, waistCircumference, hipCircumference].every((circumference) => int.tryParse(circumference) != null)) { - errors.add('circumference_is_not_a_number'.tr); - } - - return errors; - } -} diff --git a/lib/presentation/registration/body_circumferences_screen/models/body_circumferences_model.dart b/lib/presentation/registration/body_circumferences_screen/models/body_circumferences_model.dart deleted file mode 100644 index 2af76f9d..00000000 --- a/lib/presentation/registration/body_circumferences_screen/models/body_circumferences_model.dart +++ /dev/null @@ -1,20 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; - -/// This class defines the variables used in the [body_circumferences_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class BodyCircumferencesModel extends Equatable { - UserRegistrationSheet userRegistrationSheet; - BodyCircumferencesModel({required this.userRegistrationSheet}); - - BodyCircumferencesModel copyWith() { - return BodyCircumferencesModel( - userRegistrationSheet: userRegistrationSheet, - ); - } - - @override - List get props => [userRegistrationSheet]; -} diff --git a/lib/presentation/registration/city_of_living_screen/bloc/city_of_living_bloc.dart b/lib/presentation/registration/city_of_living_screen/bloc/city_of_living_bloc.dart deleted file mode 100644 index 71864dbf..00000000 --- a/lib/presentation/registration/city_of_living_screen/bloc/city_of_living_bloc.dart +++ /dev/null @@ -1,37 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/city_of_living_screen/models/city_of_living_model.dart'; -part 'city_of_living_event.dart'; -part 'city_of_living_state.dart'; - -/// A bloc that manages the state of a CityOfLiving according to the event that is dispatched to it. -class CityOfLivingBloc extends Bloc { - CityOfLivingBloc(CityOfLivingState initialState) : super(initialState) { - on(_onInitialize); - on(_changeDropDown); - } - - _onInitialize( - CityOfLivingInitialEvent event, - Emitter emit, - ) async { - emit(state.copyWith( - cityOfLivingModelObj: state.cityOfLivingModelObj?.copyWith( - dropdownItemList: fillDropdownItemList(), - ),),); - } - - _changeDropDown( - ChangeDropDownEvent event, - Emitter emit, - ) { - emit(state.copyWith(selectedDropDownValue: event.value)); - state.cityOfLivingModelObj?.userRegistrationSheet.country = - event.value.title; - } - - List fillDropdownItemList() { - return [SelectionPopupModel(id: 1, title: "Россия", isSelected: true)]; - } -} diff --git a/lib/presentation/registration/city_of_living_screen/bloc/city_of_living_event.dart b/lib/presentation/registration/city_of_living_screen/bloc/city_of_living_event.dart deleted file mode 100644 index d8418128..00000000 --- a/lib/presentation/registration/city_of_living_screen/bloc/city_of_living_event.dart +++ /dev/null @@ -1,28 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'city_of_living_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///CityOfLiving widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class CityOfLivingEvent extends Equatable {} - -/// Event that is dispatched when the CityOfLiving widget is first created. -class CityOfLivingInitialEvent extends CityOfLivingEvent { - @override - List get props => []; -} - -///event for dropdown selection -class ChangeDropDownEvent extends CityOfLivingEvent { - ChangeDropDownEvent({required this.value}); - - SelectionPopupModel value; - - @override - List get props => [ - value, - ]; -} diff --git a/lib/presentation/registration/city_of_living_screen/bloc/city_of_living_state.dart b/lib/presentation/registration/city_of_living_screen/bloc/city_of_living_state.dart deleted file mode 100644 index 5179b21e..00000000 --- a/lib/presentation/registration/city_of_living_screen/bloc/city_of_living_state.dart +++ /dev/null @@ -1,37 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'city_of_living_bloc.dart'; - -/// Represents the state of CityOfLiving in the application. -class CityOfLivingState extends Equatable { - CityOfLivingState({ - this.selectedDropDownValue, - this.cityController, - this.cityOfLivingModelObj, - }); - - SelectionPopupModel? selectedDropDownValue; - - TextEditingController? cityController; - - CityOfLivingModel? cityOfLivingModelObj; - - @override - List get props => [ - selectedDropDownValue, - cityController, - cityOfLivingModelObj, - ]; - CityOfLivingState copyWith({ - SelectionPopupModel? selectedDropDownValue, - SelectionPopupModel? selectedDropDownValue1, - CityOfLivingModel? cityOfLivingModelObj, - }) { - return CityOfLivingState( - selectedDropDownValue: - selectedDropDownValue ?? this.selectedDropDownValue, - cityController: cityController ?? this.cityController, - cityOfLivingModelObj: cityOfLivingModelObj ?? this.cityOfLivingModelObj, - ); - } -} diff --git a/lib/presentation/registration/city_of_living_screen/city_of_living_screen.dart b/lib/presentation/registration/city_of_living_screen/city_of_living_screen.dart deleted file mode 100644 index 82da493d..00000000 --- a/lib/presentation/registration/city_of_living_screen/city_of_living_screen.dart +++ /dev/null @@ -1,1291 +0,0 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/city_of_living_bloc.dart'; -import 'models/city_of_living_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/custom_drop_down.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; - -class CityOfLivingScreen extends StatelessWidget { - const CityOfLivingScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => - CityOfLivingBloc(CityOfLivingState(cityOfLivingModelObj: CityOfLivingModel(userRegistrationSheet: sheet)))..add(CityOfLivingInitialEvent()), - child: CityOfLivingScreen(), - ); - } - - @override - Widget build(BuildContext context) { - List _options = [ - "Абаза", - "Абакан", - "Абдулино", - "Абинск", - "Агидель", - "Агрыз", - "Адыгейск", - "Азнакаево", - "Азов", - "Ак-Довурак", - "Аксай", - "Алагир", - "Алапаевск", - "Алатырь", - "Алдан", - "Алейск", - "Александров", - "Александровск", - "Александровск-Сахалинский", - "Алексеевка", - "Алексин", - "Алзамай", - "АлупкаОспаривается", - "АлуштаОспаривается", - "Альметьевск", - "Амурск", - "Анадырь", - "Анапа", - "Ангарск", - "Андреаполь", - "Анжеро-Судженск", - "Анива", - "Апатиты", - "Апрелевка", - "Апшеронск", - "Арамиль", - "Аргун", - "Ардатов", - "Ардон", - "Арзамас", - "Аркадак", - "Армавир", - "АрмянскОспаривается", - "Арсеньев", - "Арск", - "Артём", - "Артёмовск", - "Артёмовский", - "Архангельск", - "Асбест", - "Асино", - "Астрахань", - "Аткарск", - "Ахтубинск", - "Ачинск", - "Аша", - "Бабаево", - "Бабушкин", - "Бавлы", - "Багратионовск", - "Байкальск", - "Баймак", - "Бакал", - "Баксан", - "Балабаново", - "Балаково", - "Балахна", - "Балашиха", - "Балашов", - "Балей", - "Балтийск", - "Барабинск", - "Барнаул", - "Барыш", - "Батайск", - "БахчисарайОспаривается", - "Бежецк", - "Белая Калитва", - "Белая Холуница", - "Белгород", - "Белебей", - "Белёв", - "Белинский", - "Белово", - "Белогорск", - "БелогорскОспаривается", - "Белозерск", - "Белокуриха", - "Беломорск", - "Белоозёрский", - "Белорецк", - "Белореченск", - "Белоусово", - "Белоярский", - "Белый", - "Бердск", - "Березники", - "Берёзовский", - "Берёзовский", - "Беслан", - "Бийск", - "Бикин", - "Билибино", - "Биробиджан", - "Бирск", - "Бирюсинск", - "Бирюч", - "Благовещенск", - "Благовещенск", - "Благодарный", - "Бобров", - "Богданович", - "Богородицк", - "Богородск", - "Боготол", - "Богучар", - "Бодайбо", - "Бокситогорск", - "Болгар", - "Бологое", - "Болотное", - "Болохово", - "Болхов", - "Большой Камень", - "Бор", - "Борзя", - "Борисоглебск", - "Боровичи", - "Боровск", - "Бородино", - "Братск", - "Бронницы", - "Брянск", - "Бугульма", - "Бугуруслан", - "Будённовск", - "Бузулук", - "Буинск", - "Буй", - "Буйнакск", - "Бутурлиновка", - "Валдай", - "Валуйки", - "Велиж", - "Великие Луки", - "Великий Новгород", - "Великий Устюг", - "Вельск", - "Венёв", - "Верещагино", - "Верея", - "Верхнеуральск", - "Верхний Тагил", - "Верхний Уфалей", - "Верхняя Пышма", - "Верхняя Салда", - "Верхняя Тура", - "Верхотурье", - "Верхоянск", - "Весьегонск", - "Ветлуга", - "Видное", - "Вилюйск", - "Вилючинск", - "Вихоревка", - "Вичуга", - "Владивосток", - "Владикавказ", - "Владимир", - "Волгоград", - "Волгодонск", - "Волгореченск", - "Волжск", - "Волжский", - "Вологда", - "Володарск", - "Волоколамск", - "Волосово", - "Волхов", - "Волчанск", - "Вольск", - "Воркута", - "Воронеж", - "Ворсма", - "Воскресенск", - "Воткинск", - "Всеволожск", - "Вуктыл", - "Выборг", - "Выкса", - "Высоковск", - "Высоцк", - "Вытегра", - "Вышний Волочёк", - "Вяземский", - "Вязники", - "Вязьма", - "Вятские Поляны", - "Гаврилов Посад", - "Гаврилов-Ям", - "Гагарин", - "Гаджиево", - "Гай", - "Галич", - "Гатчина", - "Гвардейск", - "Гдов", - "Геленджик", - "Георгиевск", - "Глазов", - "Голицыно", - "Горбатов", - "Горно-Алтайск", - "Горнозаводск", - "Горняк", - "Городец", - "Городище", - "Городовиковск", - "Гороховец", - "Горячий Ключ", - "Грайворон", - "Гремячинск", - "Грозный", - "Грязи", - "Грязовец", - "Губаха", - "Губкин", - "Губкинский", - "Гудермес", - "Гуково", - "Гулькевичи", - "Гурьевск", - "Гурьевск", - "Гусев", - "Гусиноозёрск", - "Гусь-Хрустальный", - "Давлеканово", - "Дагестанские Огни", - "Далматово", - "Дальнегорск", - "Дальнереченск", - "Данилов", - "Данков", - "Дегтярск", - "Дедовск", - "Демидов", - "Дербент", - "Десногорск", - "ДжанкойОспаривается", - "Дзержинск", - "Дзержинский", - "Дивногорск", - "Дигора", - "Димитровград", - "Дмитриев", - "Дмитров", - "Дмитровск", - "Дно", - "Добрянка", - "Долгопрудный", - "Долинск", - "Домодедово", - "Донецк", - "Донской", - "Дорогобуж", - "Дрезна", - "Дубна", - "Дубовка", - "Дудинка", - "Духовщина", - "Дюртюли", - "Дятьково", - "ЕвпаторияОспаривается", - "Егорьевск", - "Ейск", - "Екатеринбург", - "Елабуга", - "Елец", - "Елизово", - "Ельня", - "Еманжелинск", - "Емва", - "Енисейск", - "Ермолино", - "Ершов", - "Ессентуки", - "Ефремов", - "Железноводск", - "Железногорск", - "Железногорск", - "Железногорск-Илимский", - "Жердевка", - "Жигулёвск", - "Жиздра", - "Жирновск", - "Жуков", - "Жуковка", - "Жуковский", - "Завитинск", - "Заводоуковск", - "Заволжск", - "Заволжье", - "Задонск", - "Заинск", - "Закаменск", - "Заозёрный", - "Заозёрск", - "Западная Двина", - "Заполярный", - "Зарайск", - "Заречный", - "Заречный", - "Заринск", - "Звенигово", - "Звенигород", - "Зверево", - "Зеленогорск", - "Зеленоградск", - "Зеленодольск", - "Зеленокумск", - "Зерноград", - "Зея", - "Зима", - "Златоуст", - "Злынка", - "Змеиногорск", - "Знаменск", - "Зубцов", - "Зуевка", - "Ивангород", - "Иваново", - "Ивантеевка", - "Ивдель", - "Игарка", - "Ижевск", - "Избербаш", - "Изобильный", - "Иланский", - "Инза", - "Иннополис", - "Инсар", - "Инта", - "Ипатово", - "Ирбит", - "Иркутск", - "Исилькуль", - "Искитим", - "Истра", - "Ишим", - "Ишимбай", - "Йошкар-Ола", - "Кадников", - "Казань", - "Калач", - "Калач-на-Дону", - "Калачинск", - "Калининград", - "Калининск", - "Калтан", - "Калуга", - "Калязин", - "Камбарка", - "Каменка", - "Каменногорск", - "Каменск-Уральский", - "Каменск-Шахтинский", - "Камень-на-Оби", - "Камешково", - "Камызяк", - "Камышин", - "Камышлов", - "Канаш", - "Кандалакша", - "Канск", - "Карабаново", - "Карабаш", - "Карабулак", - "Карасук", - "Карачаевск", - "Карачев", - "Каргат", - "Каргополь", - "Карпинск", - "Карталы", - "Касимов", - "Касли", - "Каспийск", - "Катав-Ивановск", - "Катайск", - "Качканар", - "Кашин", - "Кашира", - "Кедровый", - "Кемерово", - "Кемь", - "КерчьОспаривается", - "Кизел", - "Кизилюрт", - "Кизляр", - "Кимовск", - "Кимры", - "Кингисепп", - "Кинель", - "Кинешма", - "Киреевск", - "Киренск", - "Киржач", - "Кириллов", - "Кириши", - "Киров", - "Киров", - "Кировград", - "Кирово-Чепецк", - "Кировск", - "Кировск", - "Кирс", - "Кирсанов", - "Киселёвск", - "Кисловодск", - "Клин", - "Клинцы", - "Княгинино", - "Ковдор", - "Ковров", - "Ковылкино", - "Когалым", - "Кодинск", - "Козельск", - "Козловка", - "Козьмодемьянск", - "Кола", - "Кологрив", - "Коломна", - "Колпашево", - "Кольчугино", - "Коммунар", - "Комсомольск", - "Комсомольск-на-Амуре", - "Конаково", - "Кондопога", - "Кондрово", - "Константиновск", - "Копейск", - "Кораблино", - "Кореновск", - "Коркино", - "Королёв", - "Короча", - "Корсаков", - "Коряжма", - "Костерёво", - "Костомукша", - "Кострома", - "Котельники", - "Котельниково", - "Котельнич", - "Котлас", - "Котово", - "Котовск", - "Кохма", - "Красавино", - "Красноармейск", - "Красноармейск", - "Красновишерск", - "Красногорск", - "Краснодар", - "Краснозаводск", - "Краснознаменск", - "Краснознаменск", - "Краснокаменск", - "Краснокамск", - "КрасноперекопскОспаривается", - "Краснослободск", - "Краснослободск", - "Краснотурьинск", - "Красноуральск", - "Красноуфимск", - "Красноярск", - "Красный Кут", - "Красный Сулин", - "Красный Холм", - "Кремёнки", - "Кропоткин", - "Крымск", - "Кстово", - "Кубинка", - "Кувандык", - "Кувшиново", - "Кудрово", - "Кудымкар", - "Кузнецк", - "Куйбышев", - "Кукмор", - "Кулебаки", - "Кумертау", - "Кунгур", - "Купино", - "Курган", - "Курганинск", - "Курильск", - "Курлово", - "Куровское", - "Курск", - "Куртамыш", - "Курчалой", - "Курчатов", - "Куса", - "Кушва", - "Кызыл", - "Кыштым", - "Кяхта", - "Лабинск", - "Лабытнанги", - "Лагань", - "Ладушкин", - "Лаишево", - "Лакинск", - "Лангепас", - "Лахденпохья", - "Лебедянь", - "Лениногорск", - "Ленинск", - "Ленинск-Кузнецкий", - "Ленск", - "Лермонтов", - "Лесной", - "Лесозаводск", - "Лесосибирск", - "Ливны", - "Ликино-Дулёво", - "Липецк", - "Липки", - "Лиски", - "Лихославль", - "Лобня", - "Лодейное Поле", - "Лосино-Петровский", - "Луга", - "Луза", - "Лукоянов", - "Луховицы", - "Лысково", - "Лысьва", - "Лыткарино", - "Льгов", - "Любань", - "Люберцы", - "Любим", - "Людиново", - "Лянтор", - "Магадан", - "Магас", - "Магнитогорск", - "Майкоп", - "Майский", - "Макаров", - "Макарьев", - "Макушино", - "Малая Вишера", - "Малгобек", - "Малмыж", - "Малоархангельск", - "Малоярославец", - "Мамадыш", - "Мамоново", - "Мантурово", - "Мариинск", - "Мариинский Посад", - "Маркс", - "Махачкала", - "Мглин", - "Мегион", - "Медвежьегорск", - "Медногорск", - "Медынь", - "Межгорье", - "Междуреченск", - "Мезень", - "Меленки", - "Мелеуз", - "Менделеевск", - "Мензелинск", - "Мещовск", - "Миасс", - "Микунь", - "Миллерово", - "Минеральные Воды", - "Минусинск", - "Миньяр", - "Мирный", - "Мирный", - "Михайлов", - "Михайловка", - "Михайловск", - "Михайловск", - "Мичуринск", - "Могоча", - "Можайск", - "Можга", - "Моздок", - "Мончегорск", - "Морозовск", - "Моршанск", - "Мосальск", - "Москва", - "Муравленко", - "Мураши", - "Мурино", - "Мурманск", - "Муром", - "Мценск", - "Мыски", - "Мытищи", - "Мышкин", - "Набережные Челны", - "Навашино", - "Наволоки", - "Надым", - "Назарово", - "Назрань", - "Называевск", - "Нальчик", - "Нариманов", - "Наро-Фоминск", - "Нарткала", - "Нарьян-Мар", - "Находка", - "Невель", - "Невельск", - "Невинномысск", - "Невьянск", - "Нелидово", - "Неман", - "Нерехта", - "Нерчинск", - "Нерюнгри", - "Нестеров", - "Нефтегорск", - "Нефтекамск", - "Нефтекумск", - "Нефтеюганск", - "Нея", - "Нижневартовск", - "Нижнекамск", - "Нижнеудинск", - "Нижние Серги", - "Нижний Ломов", - "Нижний Новгород", - "Нижний Тагил", - "Нижняя Салда", - "Нижняя Тура", - "Николаевск", - "Николаевск-на-Амуре", - "Никольск", - "Никольск", - "Никольское", - "Новая Ладога", - "Новая Ляля", - "Новоалександровск", - "Новоалтайск", - "Новоаннинский", - "Нововоронеж", - "Новодвинск", - "Новозыбков", - "Новокубанск", - "Новокузнецк", - "Новокуйбышевск", - "Новомичуринск", - "Новомосковск", - "Новопавловск", - "Новоржев", - "Новороссийск", - "Новосибирск", - "Новосиль", - "Новосокольники", - "Новотроицк", - "Новоузенск", - "Новоульяновск", - "Новоуральск", - "Новохопёрск", - "Новочебоксарск", - "Новочеркасск", - "Новошахтинск", - "Новый Оскол", - "Новый Уренгой", - "Ногинск", - "Нолинск", - "Норильск", - "Ноябрьск", - "Нурлат", - "Нытва", - "Нюрба", - "Нягань", - "Нязепетровск", - "Няндома", - "Облучье", - "Обнинск", - "Обоянь", - "Обь", - "Одинцово", - "Озёрск", - "Озёрск", - "Озёры", - "Октябрьск", - "Октябрьский", - "Окуловка", - "Олёкминск", - "Оленегорск", - "Олонец", - "Омск", - "Омутнинск", - "Онега", - "Опочка", - "Орёл", - "Оренбург", - "Орехово-Зуево", - "Орлов", - "Орск", - "Оса", - "Осинники", - "Осташков", - "Остров", - "Островной", - "Острогожск", - "Отрадное", - "Отрадный", - "Оха", - "Оханск", - "Очёр", - "Павлово", - "Павловск", - "Павловский Посад", - "Палласовка", - "Партизанск", - "Певек", - "Пенза", - "Первомайск", - "Первоуральск", - "Перевоз", - "Пересвет", - "Переславль-Залесский", - "Пермь", - "Пестово", - "Петров Вал", - "Петровск", - "Петровск-Забайкальский", - "Петрозаводск", - "Петропавловск-Камчатский", - "Петухово", - "Петушки", - "Печора", - "Печоры", - "Пикалёво", - "Пионерский", - "Питкяранта", - "Плавск", - "Пласт", - "Плёс", - "Поворино", - "Подольск", - "Подпорожье", - "Покачи", - "Покров", - "Покровск", - "Полевской", - "Полесск", - "Полысаево", - "Полярные Зори", - "Полярный", - "Поронайск", - "Порхов", - "Похвистнево", - "Почеп", - "Починок", - "Пошехонье", - "Правдинск", - "Приволжск", - "Приморск", - "Приморск", - "Приморско-Ахтарск", - "Приозерск", - "Прокопьевск", - "Пролетарск", - "Протвино", - "Прохладный", - "Псков", - "Пугачёв", - "Пудож", - "Пустошка", - "Пучеж", - "Пушкино", - "Пущино", - "Пыталово", - "Пыть-Ях", - "Пятигорск", - "Радужный", - "Радужный", - "Райчихинск", - "Раменское", - "Рассказово", - "Ревда", - "Реж", - "Реутов", - "Ржев", - "Родники", - "Рославль", - "Россошь", - "Ростов-на-Дону", - "Ростов", - "Рошаль", - "Ртищево", - "Рубцовск", - "Рудня", - "Руза", - "Рузаевка", - "Рыбинск", - "Рыбное", - "Рыльск", - "Ряжск", - "Рязань", - "СакиОспаривается", - "Салават", - "Салаир", - "Салехард", - "Сальск", - "Самара", - "Санкт-Петербург", - "Саранск", - "Сарапул", - "Саратов", - "Саров", - "Сасово", - "Сатка", - "Сафоново", - "Саяногорск", - "Саянск", - "Светлогорск", - "Светлоград", - "Светлый", - "Светогорск", - "Свирск", - "Свободный", - "Себеж", - "СевастопольОспаривается", - "Северо-Курильск", - "Северобайкальск", - "Северодвинск", - "Североморск", - "Североуральск", - "Северск", - "Севск", - "Сегежа", - "Сельцо", - "Семёнов", - "Семикаракорск", - "Семилуки", - "Сенгилей", - "Серафимович", - "Сергач", - "Сергиев Посад", - "Сердобск", - "Серов", - "Серпухов", - "Сертолово", - "Сибай", - "Сим", - "СимферопольОспаривается", - "Сковородино", - "Скопин", - "Славгород", - "Славск", - "Славянск-на-Кубани", - "Сланцы", - "Слободской", - "Слюдянка", - "Смоленск", - "Снежинск", - "Снежногорск", - "Собинка", - "Советск", - "Советск", - "Советск", - "Советская Гавань", - "Советский", - "Сокол", - "Солигалич", - "Соликамск", - "Солнечногорск", - "Соль-Илецк", - "Сольвычегодск", - "Сольцы", - "Сорочинск", - "Сорск", - "Сортавала", - "Сосенский", - "Сосновка", - "Сосновоборск", - "Сосновый Бор", - "Сосногорск", - "Сочи", - "Спас-Деменск", - "Спас-Клепики", - "Спасск", - "Спасск-Дальний", - "Спасск-Рязанский", - "Среднеколымск", - "Среднеуральск", - "Сретенск", - "Ставрополь", - "Старая Купавна", - "Старая Русса", - "Старица", - "Стародуб", - "Старый КрымОспаривается", - "Старый Оскол", - "Стерлитамак", - "Стрежевой", - "Строитель", - "Струнино", - "Ступино", - "Суворов", - "СудакОспаривается", - "Суджа", - "Судогда", - "Суздаль", - "Сунжа", - "Суоярви", - "Сураж", - "Сургут", - "Суровикино", - "Сурск", - "Сусуман", - "Сухиничи", - "Сухой Лог", - "Сызрань", - "Сыктывкар", - "Сысерть", - "Сычёвка", - "Сясьстрой", - "Тавда", - "Таганрог", - "Тайга", - "Тайшет", - "Талдом", - "Талица", - "Тамбов", - "Тара", - "Тарко-Сале", - "Таруса", - "Татарск", - "Таштагол", - "Тверь", - "Теберда", - "Тейково", - "Темников", - "Темрюк", - "Терек", - "Тетюши", - "Тимашёвск", - "Тихвин", - "Тихорецк", - "Тобольск", - "Тогучин", - "Тольятти", - "Томари", - "Томмот", - "Томск", - "Топки", - "Торжок", - "Торопец", - "Тосно", - "Тотьма", - "Трёхгорный", - "Троицк", - "Трубчевск", - "Туапсе", - "Туймазы", - "Тула", - "Тулун", - "Туран", - "Туринск", - "Тутаев", - "Тында", - "Тырныауз", - "Тюкалинск", - "Тюмень", - "Уварово", - "Углегорск", - "Углич", - "Удачный", - "Удомля", - "Ужур", - "Узловая", - "Улан-Удэ", - "Ульяновск", - "Унеча", - "Урай", - "Урень", - "Уржум", - "Урус-Мартан", - "Урюпинск", - "Усинск", - "Усмань", - "Усолье-Сибирское", - "Усолье", - "Уссурийск", - "Усть-Джегута", - "Усть-Илимск", - "Усть-Катав", - "Усть-Кут", - "Усть-Лабинск", - "Устюжна", - "Уфа", - "Ухта", - "Учалы", - "Уяр", - "Фатеж", - "ФеодосияОспаривается", - "Фокино", - "Фокино", - "Фролово", - "Фрязино", - "Фурманов", - "Хабаровск", - "Хадыженск", - "Ханты-Мансийск", - "Харабали", - "Харовск", - "Хасавюрт", - "Хвалынск", - "Хилок", - "Химки", - "Холм", - "Холмск", - "Хотьково", - "Цивильск", - "Цимлянск", - "Циолковский", - "Чадан", - "Чайковский", - "Чапаевск", - "Чаплыгин", - "Чебаркуль", - "Чебоксары", - "Чегем", - "Чекалин", - "Челябинск", - "Чердынь", - "Черемхово", - "Черепаново", - "Череповец", - "Черкесск", - "Чёрмоз", - "Черноголовка", - "Черногорск", - "Чернушка", - "Черняховск", - "Чехов", - "Чистополь", - "Чита", - "Чкаловск", - "Чудово", - "Чулым", - "Чусовой", - "Чухлома", - "Шагонар", - "Шадринск", - "Шали", - "Шарыпово", - "Шарья", - "Шатура", - "Шахты", - "Шахунья", - "Шацк", - "Шебекино", - "Шелехов", - "Шенкурск", - "Шилка", - "Шимановск", - "Шиханы", - "Шлиссельбург", - "Шумерля", - "Шумиха", - "Шуя", - "Щёкино", - "ЩёлкиноОспаривается", - "Щёлково", - "Щигры", - "Щучье", - "Электрогорск", - "Электросталь", - "Электроугли", - "Элиста", - "Энгельс", - "Эртиль", - "Югорск", - "Южа", - "Южно-Сахалинск", - "Южно-Сухокумск", - "Южноуральск", - "Юрга", - "Юрьев-Польский", - "Юрьевец", - "Юрюзань", - "Юхнов", - "Ядрин", - "Якутск", - "ЯлтаОспаривается", - "Ялуторовск", - "Янаул", - "Яранск", - "Яровое", - "Ярославль", - "Ярцево", - "Ясногорск", - "Ясный", - "Яхрома", - ]; - return Scaffold( - appBar: _buildAppBar(context), - body: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), - child: Column(children: [ - SizedBox(height: 7.v), - Container( - height: 16.v, - width: 343.h, - decoration: BoxDecoration( - color: theme.colorScheme.onPrimary, - borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.h),), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: 0.32, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation(appTheme.blueA400),),),), - SizedBox(height: 39.v), - Text("place_of_living".tr, style: theme.textTheme.headlineSmall), - Spacer(flex: 34), - Text("country".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 2.v), - BlocSelector( - selector: (state) => state.cityOfLivingModelObj, - builder: (context, cityOfLivingModelObj) { - return CustomDropDown( - icon: Container( - margin: EdgeInsets.fromLTRB(30.h, 11.v, 17.h, 11.v), - decoration: BoxDecoration(borderRadius: BorderRadius.circular(1.h)), - child: CustomImageView(imagePath: ImageConstant.imgFavorite, height: 12.adaptSize, width: 12.adaptSize),), - hintText: "Не выбрано".tr, - items: cityOfLivingModelObj?.dropdownItemList ?? [], - onChanged: onDropDownChange(context),); - },), - SizedBox(height: 22.v), - Text("Населенный пункт", style: theme.textTheme.bodyLarge), - SizedBox(height: 2.v), - BlocBuilder(builder: (context, state) { - return RawAutocomplete( - optionsBuilder: (TextEditingValue textEditingValue) => _options.where((String option) { - return option.toLowerCase().startsWith(textEditingValue.text.toLowerCase()); - }), - fieldViewBuilder: ( - BuildContext context, - TextEditingController textEditingController, - FocusNode focusNode, - VoidCallback onFieldSubmitted, - ) { - return CustomTextFormField( - controller: textEditingController, - focusNode: focusNode, - onFieldSubmitted: (String value) => onFieldSubmitted(), - ); - }, - optionsViewBuilder: ( - BuildContext context, - AutocompleteOnSelected onSelected, - Iterable options, - ) { - return Align( - alignment: Alignment.topLeft, - child: Material( - elevation: 4.0, - child: SizedBox( - height: 200.0, - child: ListView.builder( - padding: const EdgeInsets.all(8.0), - itemCount: options.length, - itemBuilder: (BuildContext context, int index) { - final String option = options.elementAt(index); - return GestureDetector( - onTap: () => onSelected(option), - child: ListTile( - title: Text(option), - ), - ); - }, - ), - ), - ), - ); - }, - ); - },), - Spacer(flex: 65), - BlocBuilder(builder: (context, state) { - return NextStepButton( - text: "continue".tr.toUpperCase(), - margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapContinue(state, context),); - },), - ],),),); - } - - onTapContinue(CityOfLivingState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.cityOfLivingModelObj!.userRegistrationSheet; - GoRouter.of(context).goNamed('bodyCircumferencesScreen', extra: sheet); - }; - } - - onDropDownChange(BuildContext context) { - return (value) { - context.read().add(ChangeDropDownEvent(value: value)); - }; - } - - /// Section Widget - _buildAppBar(BuildContext context) { - return CustomAppBar( - leadingWidth: 29.h, - leading: - AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), - centerTitle: true, - title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); - } - - Function onTapBack(BuildContext context) { - return () { - onTapArrowLeft(context); - }; - } - - /// Navigates to the previous screen. - onTapArrowLeft(BuildContext context) { - GoRouter.of(context).pop(); - } -} - -selectProduct(AutocompleteOnSelected onSelected, String option, CityOfLivingState state) { - state.cityController?.text = option; - return () { - onSelected(option); - }; -} - -buildOptions(List _options) { - return (TextEditingValue textEditingValue) { - return _options.where((String option) { - return true; - }); - }; -} diff --git a/lib/presentation/registration/city_of_living_screen/models/city_of_living_model.dart b/lib/presentation/registration/city_of_living_screen/models/city_of_living_model.dart deleted file mode 100644 index 24eb6d9c..00000000 --- a/lib/presentation/registration/city_of_living_screen/models/city_of_living_model.dart +++ /dev/null @@ -1,1153 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; -import 'package:eatvio_app/data/models/selectionPopupModel/selection_popup_model.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; - -/// This class defines the variables used in the [city_of_living_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class CityOfLivingModel extends Equatable { - UserRegistrationSheet userRegistrationSheet; - CityOfLivingModel({ - required this.userRegistrationSheet, - this.dropdownItemList = const [], - this.cityList = const [ - "Абаза", - "Абакан", - "Абдулино", - "Абинск", - "Агидель", - "Агрыз", - "Адыгейск", - "Азнакаево", - "Азов", - "Ак-Довурак", - "Аксай", - "Алагир", - "Алапаевск", - "Алатырь", - "Алдан", - "Алейск", - "Александров", - "Александровск", - "Александровск-Сахалинский", - "Алексеевка", - "Алексин", - "Алзамай", - "АлупкаОспаривается", - "АлуштаОспаривается", - "Альметьевск", - "Амурск", - "Анадырь", - "Анапа", - "Ангарск", - "Андреаполь", - "Анжеро-Судженск", - "Анива", - "Апатиты", - "Апрелевка", - "Апшеронск", - "Арамиль", - "Аргун", - "Ардатов", - "Ардон", - "Арзамас", - "Аркадак", - "Армавир", - "АрмянскОспаривается", - "Арсеньев", - "Арск", - "Артём", - "Артёмовск", - "Артёмовский", - "Архангельск", - "Асбест", - "Асино", - "Астрахань", - "Аткарск", - "Ахтубинск", - "Ачинск", - "Аша", - "Бабаево", - "Бабушкин", - "Бавлы", - "Багратионовск", - "Байкальск", - "Баймак", - "Бакал", - "Баксан", - "Балабаново", - "Балаково", - "Балахна", - "Балашиха", - "Балашов", - "Балей", - "Балтийск", - "Барабинск", - "Барнаул", - "Барыш", - "Батайск", - "БахчисарайОспаривается", - "Бежецк", - "Белая Калитва", - "Белая Холуница", - "Белгород", - "Белебей", - "Белёв", - "Белинский", - "Белово", - "Белогорск", - "БелогорскОспаривается", - "Белозерск", - "Белокуриха", - "Беломорск", - "Белоозёрский", - "Белорецк", - "Белореченск", - "Белоусово", - "Белоярский", - "Белый", - "Бердск", - "Березники", - "Берёзовский", - "Берёзовский", - "Беслан", - "Бийск", - "Бикин", - "Билибино", - "Биробиджан", - "Бирск", - "Бирюсинск", - "Бирюч", - "Благовещенск", - "Благовещенск", - "Благодарный", - "Бобров", - "Богданович", - "Богородицк", - "Богородск", - "Боготол", - "Богучар", - "Бодайбо", - "Бокситогорск", - "Болгар", - "Бологое", - "Болотное", - "Болохово", - "Болхов", - "Большой Камень", - "Бор", - "Борзя", - "Борисоглебск", - "Боровичи", - "Боровск", - "Бородино", - "Братск", - "Бронницы", - "Брянск", - "Бугульма", - "Бугуруслан", - "Будённовск", - "Бузулук", - "Буинск", - "Буй", - "Буйнакск", - "Бутурлиновка", - "Валдай", - "Валуйки", - "Велиж", - "Великие Луки", - "Великий Новгород", - "Великий Устюг", - "Вельск", - "Венёв", - "Верещагино", - "Верея", - "Верхнеуральск", - "Верхний Тагил", - "Верхний Уфалей", - "Верхняя Пышма", - "Верхняя Салда", - "Верхняя Тура", - "Верхотурье", - "Верхоянск", - "Весьегонск", - "Ветлуга", - "Видное", - "Вилюйск", - "Вилючинск", - "Вихоревка", - "Вичуга", - "Владивосток", - "Владикавказ", - "Владимир", - "Волгоград", - "Волгодонск", - "Волгореченск", - "Волжск", - "Волжский", - "Вологда", - "Володарск", - "Волоколамск", - "Волосово", - "Волхов", - "Волчанск", - "Вольск", - "Воркута", - "Воронеж", - "Ворсма", - "Воскресенск", - "Воткинск", - "Всеволожск", - "Вуктыл", - "Выборг", - "Выкса", - "Высоковск", - "Высоцк", - "Вытегра", - "Вышний Волочёк", - "Вяземский", - "Вязники", - "Вязьма", - "Вятские Поляны", - "Гаврилов Посад", - "Гаврилов-Ям", - "Гагарин", - "Гаджиево", - "Гай", - "Галич", - "Гатчина", - "Гвардейск", - "Гдов", - "Геленджик", - "Георгиевск", - "Глазов", - "Голицыно", - "Горбатов", - "Горно-Алтайск", - "Горнозаводск", - "Горняк", - "Городец", - "Городище", - "Городовиковск", - "Гороховец", - "Горячий Ключ", - "Грайворон", - "Гремячинск", - "Грозный", - "Грязи", - "Грязовец", - "Губаха", - "Губкин", - "Губкинский", - "Гудермес", - "Гуково", - "Гулькевичи", - "Гурьевск", - "Гурьевск", - "Гусев", - "Гусиноозёрск", - "Гусь-Хрустальный", - "Давлеканово", - "Дагестанские Огни", - "Далматово", - "Дальнегорск", - "Дальнереченск", - "Данилов", - "Данков", - "Дегтярск", - "Дедовск", - "Демидов", - "Дербент", - "Десногорск", - "ДжанкойОспаривается", - "Дзержинск", - "Дзержинский", - "Дивногорск", - "Дигора", - "Димитровград", - "Дмитриев", - "Дмитров", - "Дмитровск", - "Дно", - "Добрянка", - "Долгопрудный", - "Долинск", - "Домодедово", - "Донецк", - "Донской", - "Дорогобуж", - "Дрезна", - "Дубна", - "Дубовка", - "Дудинка", - "Духовщина", - "Дюртюли", - "Дятьково", - "ЕвпаторияОспаривается", - "Егорьевск", - "Ейск", - "Екатеринбург", - "Елабуга", - "Елец", - "Елизово", - "Ельня", - "Еманжелинск", - "Емва", - "Енисейск", - "Ермолино", - "Ершов", - "Ессентуки", - "Ефремов", - "Железноводск", - "Железногорск", - "Железногорск", - "Железногорск-Илимский", - "Жердевка", - "Жигулёвск", - "Жиздра", - "Жирновск", - "Жуков", - "Жуковка", - "Жуковский", - "Завитинск", - "Заводоуковск", - "Заволжск", - "Заволжье", - "Задонск", - "Заинск", - "Закаменск", - "Заозёрный", - "Заозёрск", - "Западная Двина", - "Заполярный", - "Зарайск", - "Заречный", - "Заречный", - "Заринск", - "Звенигово", - "Звенигород", - "Зверево", - "Зеленогорск", - "Зеленоградск", - "Зеленодольск", - "Зеленокумск", - "Зерноград", - "Зея", - "Зима", - "Златоуст", - "Злынка", - "Змеиногорск", - "Знаменск", - "Зубцов", - "Зуевка", - "Ивангород", - "Иваново", - "Ивантеевка", - "Ивдель", - "Игарка", - "Ижевск", - "Избербаш", - "Изобильный", - "Иланский", - "Инза", - "Иннополис", - "Инсар", - "Инта", - "Ипатово", - "Ирбит", - "Иркутск", - "Исилькуль", - "Искитим", - "Истра", - "Ишим", - "Ишимбай", - "Йошкар-Ола", - "Кадников", - "Казань", - "Калач", - "Калач-на-Дону", - "Калачинск", - "Калининград", - "Калининск", - "Калтан", - "Калуга", - "Калязин", - "Камбарка", - "Каменка", - "Каменногорск", - "Каменск-Уральский", - "Каменск-Шахтинский", - "Камень-на-Оби", - "Камешково", - "Камызяк", - "Камышин", - "Камышлов", - "Канаш", - "Кандалакша", - "Канск", - "Карабаново", - "Карабаш", - "Карабулак", - "Карасук", - "Карачаевск", - "Карачев", - "Каргат", - "Каргополь", - "Карпинск", - "Карталы", - "Касимов", - "Касли", - "Каспийск", - "Катав-Ивановск", - "Катайск", - "Качканар", - "Кашин", - "Кашира", - "Кедровый", - "Кемерово", - "Кемь", - "КерчьОспаривается", - "Кизел", - "Кизилюрт", - "Кизляр", - "Кимовск", - "Кимры", - "Кингисепп", - "Кинель", - "Кинешма", - "Киреевск", - "Киренск", - "Киржач", - "Кириллов", - "Кириши", - "Киров", - "Киров", - "Кировград", - "Кирово-Чепецк", - "Кировск", - "Кировск", - "Кирс", - "Кирсанов", - "Киселёвск", - "Кисловодск", - "Клин", - "Клинцы", - "Княгинино", - "Ковдор", - "Ковров", - "Ковылкино", - "Когалым", - "Кодинск", - "Козельск", - "Козловка", - "Козьмодемьянск", - "Кола", - "Кологрив", - "Коломна", - "Колпашево", - "Кольчугино", - "Коммунар", - "Комсомольск", - "Комсомольск-на-Амуре", - "Конаково", - "Кондопога", - "Кондрово", - "Константиновск", - "Копейск", - "Кораблино", - "Кореновск", - "Коркино", - "Королёв", - "Короча", - "Корсаков", - "Коряжма", - "Костерёво", - "Костомукша", - "Кострома", - "Котельники", - "Котельниково", - "Котельнич", - "Котлас", - "Котово", - "Котовск", - "Кохма", - "Красавино", - "Красноармейск", - "Красноармейск", - "Красновишерск", - "Красногорск", - "Краснодар", - "Краснозаводск", - "Краснознаменск", - "Краснознаменск", - "Краснокаменск", - "Краснокамск", - "КрасноперекопскОспаривается", - "Краснослободск", - "Краснослободск", - "Краснотурьинск", - "Красноуральск", - "Красноуфимск", - "Красноярск", - "Красный Кут", - "Красный Сулин", - "Красный Холм", - "Кремёнки", - "Кропоткин", - "Крымск", - "Кстово", - "Кубинка", - "Кувандык", - "Кувшиново", - "Кудрово", - "Кудымкар", - "Кузнецк", - "Куйбышев", - "Кукмор", - "Кулебаки", - "Кумертау", - "Кунгур", - "Купино", - "Курган", - "Курганинск", - "Курильск", - "Курлово", - "Куровское", - "Курск", - "Куртамыш", - "Курчалой", - "Курчатов", - "Куса", - "Кушва", - "Кызыл", - "Кыштым", - "Кяхта", - "Лабинск", - "Лабытнанги", - "Лагань", - "Ладушкин", - "Лаишево", - "Лакинск", - "Лангепас", - "Лахденпохья", - "Лебедянь", - "Лениногорск", - "Ленинск", - "Ленинск-Кузнецкий", - "Ленск", - "Лермонтов", - "Лесной", - "Лесозаводск", - "Лесосибирск", - "Ливны", - "Ликино-Дулёво", - "Липецк", - "Липки", - "Лиски", - "Лихославль", - "Лобня", - "Лодейное Поле", - "Лосино-Петровский", - "Луга", - "Луза", - "Лукоянов", - "Луховицы", - "Лысково", - "Лысьва", - "Лыткарино", - "Льгов", - "Любань", - "Люберцы", - "Любим", - "Людиново", - "Лянтор", - "Магадан", - "Магас", - "Магнитогорск", - "Майкоп", - "Майский", - "Макаров", - "Макарьев", - "Макушино", - "Малая Вишера", - "Малгобек", - "Малмыж", - "Малоархангельск", - "Малоярославец", - "Мамадыш", - "Мамоново", - "Мантурово", - "Мариинск", - "Мариинский Посад", - "Маркс", - "Махачкала", - "Мглин", - "Мегион", - "Медвежьегорск", - "Медногорск", - "Медынь", - "Межгорье", - "Междуреченск", - "Мезень", - "Меленки", - "Мелеуз", - "Менделеевск", - "Мензелинск", - "Мещовск", - "Миасс", - "Микунь", - "Миллерово", - "Минеральные Воды", - "Минусинск", - "Миньяр", - "Мирный", - "Мирный", - "Михайлов", - "Михайловка", - "Михайловск", - "Михайловск", - "Мичуринск", - "Могоча", - "Можайск", - "Можга", - "Моздок", - "Мончегорск", - "Морозовск", - "Моршанск", - "Мосальск", - "Москва", - "Муравленко", - "Мураши", - "Мурино", - "Мурманск", - "Муром", - "Мценск", - "Мыски", - "Мытищи", - "Мышкин", - "Набережные Челны", - "Навашино", - "Наволоки", - "Надым", - "Назарово", - "Назрань", - "Называевск", - "Нальчик", - "Нариманов", - "Наро-Фоминск", - "Нарткала", - "Нарьян-Мар", - "Находка", - "Невель", - "Невельск", - "Невинномысск", - "Невьянск", - "Нелидово", - "Неман", - "Нерехта", - "Нерчинск", - "Нерюнгри", - "Нестеров", - "Нефтегорск", - "Нефтекамск", - "Нефтекумск", - "Нефтеюганск", - "Нея", - "Нижневартовск", - "Нижнекамск", - "Нижнеудинск", - "Нижние Серги", - "Нижний Ломов", - "Нижний Новгород", - "Нижний Тагил", - "Нижняя Салда", - "Нижняя Тура", - "Николаевск", - "Николаевск-на-Амуре", - "Никольск", - "Никольск", - "Никольское", - "Новая Ладога", - "Новая Ляля", - "Новоалександровск", - "Новоалтайск", - "Новоаннинский", - "Нововоронеж", - "Новодвинск", - "Новозыбков", - "Новокубанск", - "Новокузнецк", - "Новокуйбышевск", - "Новомичуринск", - "Новомосковск", - "Новопавловск", - "Новоржев", - "Новороссийск", - "Новосибирск", - "Новосиль", - "Новосокольники", - "Новотроицк", - "Новоузенск", - "Новоульяновск", - "Новоуральск", - "Новохопёрск", - "Новочебоксарск", - "Новочеркасск", - "Новошахтинск", - "Новый Оскол", - "Новый Уренгой", - "Ногинск", - "Нолинск", - "Норильск", - "Ноябрьск", - "Нурлат", - "Нытва", - "Нюрба", - "Нягань", - "Нязепетровск", - "Няндома", - "Облучье", - "Обнинск", - "Обоянь", - "Обь", - "Одинцово", - "Озёрск", - "Озёрск", - "Озёры", - "Октябрьск", - "Октябрьский", - "Окуловка", - "Олёкминск", - "Оленегорск", - "Олонец", - "Омск", - "Омутнинск", - "Онега", - "Опочка", - "Орёл", - "Оренбург", - "Орехово-Зуево", - "Орлов", - "Орск", - "Оса", - "Осинники", - "Осташков", - "Остров", - "Островной", - "Острогожск", - "Отрадное", - "Отрадный", - "Оха", - "Оханск", - "Очёр", - "Павлово", - "Павловск", - "Павловский Посад", - "Палласовка", - "Партизанск", - "Певек", - "Пенза", - "Первомайск", - "Первоуральск", - "Перевоз", - "Пересвет", - "Переславль-Залесский", - "Пермь", - "Пестово", - "Петров Вал", - "Петровск", - "Петровск-Забайкальский", - "Петрозаводск", - "Петропавловск-Камчатский", - "Петухово", - "Петушки", - "Печора", - "Печоры", - "Пикалёво", - "Пионерский", - "Питкяранта", - "Плавск", - "Пласт", - "Плёс", - "Поворино", - "Подольск", - "Подпорожье", - "Покачи", - "Покров", - "Покровск", - "Полевской", - "Полесск", - "Полысаево", - "Полярные Зори", - "Полярный", - "Поронайск", - "Порхов", - "Похвистнево", - "Почеп", - "Починок", - "Пошехонье", - "Правдинск", - "Приволжск", - "Приморск", - "Приморск", - "Приморско-Ахтарск", - "Приозерск", - "Прокопьевск", - "Пролетарск", - "Протвино", - "Прохладный", - "Псков", - "Пугачёв", - "Пудож", - "Пустошка", - "Пучеж", - "Пушкино", - "Пущино", - "Пыталово", - "Пыть-Ях", - "Пятигорск", - "Радужный", - "Радужный", - "Райчихинск", - "Раменское", - "Рассказово", - "Ревда", - "Реж", - "Реутов", - "Ржев", - "Родники", - "Рославль", - "Россошь", - "Ростов-на-Дону", - "Ростов", - "Рошаль", - "Ртищево", - "Рубцовск", - "Рудня", - "Руза", - "Рузаевка", - "Рыбинск", - "Рыбное", - "Рыльск", - "Ряжск", - "Рязань", - "СакиОспаривается", - "Салават", - "Салаир", - "Салехард", - "Сальск", - "Самара", - "Санкт-Петербург", - "Саранск", - "Сарапул", - "Саратов", - "Саров", - "Сасово", - "Сатка", - "Сафоново", - "Саяногорск", - "Саянск", - "Светлогорск", - "Светлоград", - "Светлый", - "Светогорск", - "Свирск", - "Свободный", - "Себеж", - "СевастопольОспаривается", - "Северо-Курильск", - "Северобайкальск", - "Северодвинск", - "Североморск", - "Североуральск", - "Северск", - "Севск", - "Сегежа", - "Сельцо", - "Семёнов", - "Семикаракорск", - "Семилуки", - "Сенгилей", - "Серафимович", - "Сергач", - "Сергиев Посад", - "Сердобск", - "Серов", - "Серпухов", - "Сертолово", - "Сибай", - "Сим", - "СимферопольОспаривается", - "Сковородино", - "Скопин", - "Славгород", - "Славск", - "Славянск-на-Кубани", - "Сланцы", - "Слободской", - "Слюдянка", - "Смоленск", - "Снежинск", - "Снежногорск", - "Собинка", - "Советск", - "Советск", - "Советск", - "Советская Гавань", - "Советский", - "Сокол", - "Солигалич", - "Соликамск", - "Солнечногорск", - "Соль-Илецк", - "Сольвычегодск", - "Сольцы", - "Сорочинск", - "Сорск", - "Сортавала", - "Сосенский", - "Сосновка", - "Сосновоборск", - "Сосновый Бор", - "Сосногорск", - "Сочи", - "Спас-Деменск", - "Спас-Клепики", - "Спасск", - "Спасск-Дальний", - "Спасск-Рязанский", - "Среднеколымск", - "Среднеуральск", - "Сретенск", - "Ставрополь", - "Старая Купавна", - "Старая Русса", - "Старица", - "Стародуб", - "Старый КрымОспаривается", - "Старый Оскол", - "Стерлитамак", - "Стрежевой", - "Строитель", - "Струнино", - "Ступино", - "Суворов", - "СудакОспаривается", - "Суджа", - "Судогда", - "Суздаль", - "Сунжа", - "Суоярви", - "Сураж", - "Сургут", - "Суровикино", - "Сурск", - "Сусуман", - "Сухиничи", - "Сухой Лог", - "Сызрань", - "Сыктывкар", - "Сысерть", - "Сычёвка", - "Сясьстрой", - "Тавда", - "Таганрог", - "Тайга", - "Тайшет", - "Талдом", - "Талица", - "Тамбов", - "Тара", - "Тарко-Сале", - "Таруса", - "Татарск", - "Таштагол", - "Тверь", - "Теберда", - "Тейково", - "Темников", - "Темрюк", - "Терек", - "Тетюши", - "Тимашёвск", - "Тихвин", - "Тихорецк", - "Тобольск", - "Тогучин", - "Тольятти", - "Томари", - "Томмот", - "Томск", - "Топки", - "Торжок", - "Торопец", - "Тосно", - "Тотьма", - "Трёхгорный", - "Троицк", - "Трубчевск", - "Туапсе", - "Туймазы", - "Тула", - "Тулун", - "Туран", - "Туринск", - "Тутаев", - "Тында", - "Тырныауз", - "Тюкалинск", - "Тюмень", - "Уварово", - "Углегорск", - "Углич", - "Удачный", - "Удомля", - "Ужур", - "Узловая", - "Улан-Удэ", - "Ульяновск", - "Унеча", - "Урай", - "Урень", - "Уржум", - "Урус-Мартан", - "Урюпинск", - "Усинск", - "Усмань", - "Усолье-Сибирское", - "Усолье", - "Уссурийск", - "Усть-Джегута", - "Усть-Илимск", - "Усть-Катав", - "Усть-Кут", - "Усть-Лабинск", - "Устюжна", - "Уфа", - "Ухта", - "Учалы", - "Уяр", - "Фатеж", - "ФеодосияОспаривается", - "Фокино", - "Фокино", - "Фролово", - "Фрязино", - "Фурманов", - "Хабаровск", - "Хадыженск", - "Ханты-Мансийск", - "Харабали", - "Харовск", - "Хасавюрт", - "Хвалынск", - "Хилок", - "Химки", - "Холм", - "Холмск", - "Хотьково", - "Цивильск", - "Цимлянск", - "Циолковский", - "Чадан", - "Чайковский", - "Чапаевск", - "Чаплыгин", - "Чебаркуль", - "Чебоксары", - "Чегем", - "Чекалин", - "Челябинск", - "Чердынь", - "Черемхово", - "Черепаново", - "Череповец", - "Черкесск", - "Чёрмоз", - "Черноголовка", - "Черногорск", - "Чернушка", - "Черняховск", - "Чехов", - "Чистополь", - "Чита", - "Чкаловск", - "Чудово", - "Чулым", - "Чусовой", - "Чухлома", - "Шагонар", - "Шадринск", - "Шали", - "Шарыпово", - "Шарья", - "Шатура", - "Шахты", - "Шахунья", - "Шацк", - "Шебекино", - "Шелехов", - "Шенкурск", - "Шилка", - "Шимановск", - "Шиханы", - "Шлиссельбург", - "Шумерля", - "Шумиха", - "Шуя", - "Щёкино", - "ЩёлкиноОспаривается", - "Щёлково", - "Щигры", - "Щучье", - "Электрогорск", - "Электросталь", - "Электроугли", - "Элиста", - "Энгельс", - "Эртиль", - "Югорск", - "Южа", - "Южно-Сахалинск", - "Южно-Сухокумск", - "Южноуральск", - "Юрга", - "Юрьев-Польский", - "Юрьевец", - "Юрюзань", - "Юхнов", - "Ядрин", - "Якутск", - "ЯлтаОспаривается", - "Ялуторовск", - "Янаул", - "Яранск", - "Яровое", - "Ярославль", - "Ярцево", - "Ясногорск", - "Ясный", - "Яхрома", - ], - }); - - List dropdownItemList; - - List cityList; - - CityOfLivingModel copyWith({ - List? dropdownItemList, - List? dropdownItemList1, - }) { - return CityOfLivingModel( - userRegistrationSheet: userRegistrationSheet, - dropdownItemList: dropdownItemList ?? this.dropdownItemList, - cityList: cityList, - ); - } - - @override - List get props => - [dropdownItemList, cityList, userRegistrationSheet]; -} diff --git a/lib/presentation/registration/credentials_screen/bloc/credentials_bloc.dart b/lib/presentation/registration/credentials_screen/bloc/credentials_bloc.dart deleted file mode 100644 index f0d45cc0..00000000 --- a/lib/presentation/registration/credentials_screen/bloc/credentials_bloc.dart +++ /dev/null @@ -1,24 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/credentials_screen/models/credentials_model.dart'; -part 'credentials_event.dart'; -part 'credentials_state.dart'; - -/// A bloc that manages the state of a Credentials according to the event that is dispatched to it. -class CredentialsBloc extends Bloc { - CredentialsBloc(CredentialsState initialState) : super(initialState) { - on(_onInitialize); - } - - _onInitialize( - CredentialsInitialEvent event, - Emitter emit, - ) async { - emit(state.copyWith( - emailController: TextEditingController(), - nameController: TextEditingController(), - passwordController: TextEditingController(), - passwordConfirmationController: TextEditingController(),),); - } -} diff --git a/lib/presentation/registration/credentials_screen/bloc/credentials_event.dart b/lib/presentation/registration/credentials_screen/bloc/credentials_event.dart deleted file mode 100644 index 3001076a..00000000 --- a/lib/presentation/registration/credentials_screen/bloc/credentials_event.dart +++ /dev/null @@ -1,16 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'credentials_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///Credentials widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class CredentialsEvent extends Equatable {} - -/// Event that is dispatched when the Credentials widget is first created. -class CredentialsInitialEvent extends CredentialsEvent { - @override - List get props => []; -} diff --git a/lib/presentation/registration/credentials_screen/bloc/credentials_state.dart b/lib/presentation/registration/credentials_screen/bloc/credentials_state.dart deleted file mode 100644 index e127da6e..00000000 --- a/lib/presentation/registration/credentials_screen/bloc/credentials_state.dart +++ /dev/null @@ -1,49 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'credentials_bloc.dart'; - -/// Represents the state of Credentials in the application. -class CredentialsState extends Equatable { - CredentialsState({ - this.emailController, - this.nameController, - this.passwordController, - this.passwordConfirmationController, - this.credentialsModelObj, - }); - - TextEditingController? emailController; - - TextEditingController? nameController; - - TextEditingController? passwordController; - - TextEditingController? passwordConfirmationController; - - CredentialsModel? credentialsModelObj; - - @override - List get props => [ - emailController, - nameController, - passwordController, - passwordConfirmationController, - credentialsModelObj, - ]; - CredentialsState copyWith({ - TextEditingController? nameController, - TextEditingController? emailController, - TextEditingController? passwordController, - TextEditingController? passwordConfirmationController, - CredentialsModel? credentialsModelObj, - }) { - return CredentialsState( - emailController: emailController ?? this.emailController, - nameController: nameController ?? this.nameController, - passwordController: passwordController ?? this.passwordController, - passwordConfirmationController: - passwordConfirmationController ?? this.passwordConfirmationController, - credentialsModelObj: credentialsModelObj ?? this.credentialsModelObj, - ); - } -} diff --git a/lib/presentation/registration/credentials_screen/credentials_screen.dart b/lib/presentation/registration/credentials_screen/credentials_screen.dart deleted file mode 100644 index cbf31712..00000000 --- a/lib/presentation/registration/credentials_screen/credentials_screen.dart +++ /dev/null @@ -1,175 +0,0 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/credentials_bloc.dart'; -import 'models/credentials_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:validators/validators.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; - -class CredentialsScreen extends StatelessWidget { - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => CredentialsBloc( - CredentialsState( - credentialsModelObj: CredentialsModel(userRegistrationSheet: sheet), - ), - )..add(CredentialsInitialEvent()), - child: CredentialsScreen(), - ); - } - - @override - Widget build(BuildContext context) { - mediaQueryData = MediaQuery.of(context); - return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), - child: Column(children: [ - SizedBox(height: 7.v), - Container( - height: 16.v, - width: 343.h, - decoration: BoxDecoration( - color: theme.colorScheme.onPrimary, - borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.h),), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: 0.05, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation(appTheme.blueA400),),),), - SizedBox(height: 39.v), - Text("user_registration".tr, style: theme.textTheme.headlineSmall), - SizedBox(height: 16.v), - Text("email".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 3.v), - BlocSelector( - selector: (state) => state.emailController, - builder: (context, emailController) { - return CustomTextFormField(controller: emailController, textInputAction: TextInputAction.done); - },), - SizedBox(height: 22.v), - Text("username".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 3.v), - BlocSelector( - selector: (state) => state.nameController, - builder: (context, nameController) { - return CustomTextFormField(controller: nameController, textInputAction: TextInputAction.done); - },), - SizedBox(height: 19.v), - Text("password".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 5.v), - BlocSelector( - selector: (state) => state.passwordController, - builder: (context, passwordController) { - return CustomTextFormField( - obscureText: true, - controller: passwordController, - ); - },), - SizedBox(height: 21.v), - Text("password_confirmation".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 3.v), - BlocSelector( - selector: (state) => state.passwordConfirmationController, - builder: (context, passwordConfirmationController) { - return CustomTextFormField(obscureText: true, controller: passwordConfirmationController, textInputAction: TextInputAction.done); - },), - Spacer(), - BlocBuilder(builder: (context, state) { - return NextStepButton( - text: "continue".tr.toUpperCase(), - margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapContinue(state, context),); - },), - ],),),); - } - - onTapContinue(CredentialsState state, BuildContext context) { - return () { - List errors = - validateFields(state.emailController!.text, state.nameController!.text, state.passwordController!.text, state.passwordConfirmationController!.text); - if (errors.isEmpty) { - UserRegistrationSheet sheet = state.credentialsModelObj!.userRegistrationSheet; - sheet.email = state.emailController!.text; - sheet.name = state.nameController!.text; - sheet.password = state.passwordController!.text; - sheet.passwordConfirmation = state.passwordConfirmationController!.text; - GoRouter.of(context).goNamed('nameScreen', extra: sheet); - } else { - String errorMessage = ''; - - for (var error in errors) { - errorMessage += error + '\n\n'; - } - - 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); - }; - } - - /// Section Widget - _buildAppBar(BuildContext context) { - return CustomAppBar(leadingWidth: 29.h, centerTitle: true, title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio)); - } - - List validateFields(String email, String name, String password, String passwordConfirmation) { - List errors = []; - - if (!isEmail(email)) { - errors.add('email_invalid'.tr); - } - - if (email.isEmpty) { - errors.add('email_empty'.tr); - } - - if (name.length < 6) { - errors.add('name_short'.tr); - } - - if (name.isEmpty) { - errors.add('name_empty'.tr); - } - - if (password.isEmpty) { - errors.add('name_empty'.tr); - } - - if (password.length < 6) { - errors.add('password_short'.tr); - } - - if (password != passwordConfirmation) { - errors.add('password_confirmation_mismatch'.tr); - } - - return errors; - } -} diff --git a/lib/presentation/registration/credentials_screen/models/credentials_model.dart b/lib/presentation/registration/credentials_screen/models/credentials_model.dart deleted file mode 100644 index ae6c3201..00000000 --- a/lib/presentation/registration/credentials_screen/models/credentials_model.dart +++ /dev/null @@ -1,22 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; - -/// This class defines the variables used in the [credentials_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class CredentialsModel extends Equatable { - UserRegistrationSheet userRegistrationSheet; - - CredentialsModel({required this.userRegistrationSheet}); - - CredentialsModel copyWith({UserRegistrationSheet? userRegistrationSheet}) { - return CredentialsModel( - userRegistrationSheet: - userRegistrationSheet ?? this.userRegistrationSheet, - ); - } - - @override - List get props => [userRegistrationSheet]; -} diff --git a/lib/presentation/registration/date_of_birth_screen/bloc/date_of_birth_bloc.dart b/lib/presentation/registration/date_of_birth_screen/bloc/date_of_birth_bloc.dart deleted file mode 100644 index 78dec540..00000000 --- a/lib/presentation/registration/date_of_birth_screen/bloc/date_of_birth_bloc.dart +++ /dev/null @@ -1,18 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/date_of_birth_screen/models/date_of_birth_model.dart'; -part 'date_of_birth_event.dart'; -part 'date_of_birth_state.dart'; - -/// A bloc that manages the state of a DateOfBirth according to the event that is dispatched to it. -class DateOfBirthBloc extends Bloc { - DateOfBirthBloc(DateOfBirthState initialState) : super(initialState) { - on(_onInitialize); - } - - _onInitialize( - DateOfBirthInitialEvent event, - Emitter emit, - ) async {} -} diff --git a/lib/presentation/registration/date_of_birth_screen/bloc/date_of_birth_event.dart b/lib/presentation/registration/date_of_birth_screen/bloc/date_of_birth_event.dart deleted file mode 100644 index 0d6938b5..00000000 --- a/lib/presentation/registration/date_of_birth_screen/bloc/date_of_birth_event.dart +++ /dev/null @@ -1,16 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'date_of_birth_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///DateOfBirth widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class DateOfBirthEvent extends Equatable {} - -/// Event that is dispatched when the DateOfBirth widget is first created. -class DateOfBirthInitialEvent extends DateOfBirthEvent { - @override - List get props => []; -} diff --git a/lib/presentation/registration/date_of_birth_screen/bloc/date_of_birth_state.dart b/lib/presentation/registration/date_of_birth_screen/bloc/date_of_birth_state.dart deleted file mode 100644 index e54b82c6..00000000 --- a/lib/presentation/registration/date_of_birth_screen/bloc/date_of_birth_state.dart +++ /dev/null @@ -1,20 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'date_of_birth_bloc.dart'; - -/// Represents the state of DateOfBirth in the application. -class DateOfBirthState extends Equatable { - DateOfBirthState({this.dateOfBirthModelObj}); - - DateOfBirthModel? dateOfBirthModelObj; - - @override - List get props => [ - dateOfBirthModelObj, - ]; - DateOfBirthState copyWith({DateOfBirthModel? dateOfBirthModelObj}) { - return DateOfBirthState( - dateOfBirthModelObj: dateOfBirthModelObj ?? this.dateOfBirthModelObj, - ); - } -} diff --git a/lib/presentation/registration/date_of_birth_screen/date_of_birth_screen.dart b/lib/presentation/registration/date_of_birth_screen/date_of_birth_screen.dart deleted file mode 100644 index a6b2da07..00000000 --- a/lib/presentation/registration/date_of_birth_screen/date_of_birth_screen.dart +++ /dev/null @@ -1,148 +0,0 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/date_of_birth_bloc.dart'; -import 'models/date_of_birth_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; - -class DateOfBirthScreen extends StatefulWidget { - const DateOfBirthScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => DateOfBirthBloc( - DateOfBirthState( - dateOfBirthModelObj: DateOfBirthModel( - userRegistrationSheet: sheet, - ), - ), - )..add(DateOfBirthInitialEvent()), - child: DateOfBirthScreen(), - ); - } - - @override - State createState() => _DateOfBirthScreenState(); -} - -class _DateOfBirthScreenState extends State { - DateTime selectedDate = DateTime.now(); - - @override - Widget build(BuildContext context) { - mediaQueryData = MediaQuery.of(context); - return BlocBuilder(builder: (context, state) { - return Scaffold( - appBar: _buildAppBar(context), - body: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), - child: Column(children: [ - Container( - height: 16.v, - width: 343.h, - decoration: BoxDecoration( - color: theme.colorScheme.onPrimary, - borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.h),), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: 0.24, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation(appTheme.blueA400),),),), - SizedBox(height: 38.v), - Text("date_of_birth".tr, style: theme.textTheme.headlineSmall), - Spacer(flex: 39), - _buildDateInput(context), - Spacer(flex: 60), - BlocBuilder(builder: (context, state) { - return NextStepButton( - text: "continue".tr.toUpperCase(), - margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapContinue(state, context),); - },), - ],),),); - },); - } - - onTapContinue(DateOfBirthState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.dateOfBirthModelObj!.userRegistrationSheet; - sheet.birthdate = selectedDate.toString(); - GoRouter.of(context).goNamed('cityOfLivingScreen', extra: sheet); - }; - } - - /// Section Widget - _buildAppBar(BuildContext context) { - return CustomAppBar( - leadingWidth: 29.h, - leading: - AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), - centerTitle: true, - title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); - } - - Function onTapBack(BuildContext context) { - return () { - onTapArrowLeft(context); - }; - } - - /// Section Widget - _buildDateInput(BuildContext context) { - return Container( - width: 343.h, - padding: EdgeInsets.symmetric(horizontal: 4.h, vertical: 1.v), - decoration: AppDecoration.outlineBlueA.copyWith(borderRadius: BorderRadiusStyle.circleBorder8), - child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ - CustomImageView(imagePath: ImageConstant.imgFavorite, height: 12.adaptSize, width: 12.adaptSize, radius: BorderRadius.circular(1.h)), - SizedBox(height: 6.v), - Align( - alignment: Alignment.center, - child: GestureDetector( - onTap: onTapCalendar(context), - child: Text('${selectedDate.day}.${selectedDate.month}.${selectedDate.year}', style: theme.textTheme.titleMedium),),), - SizedBox(height: 6.v), - ],),); - } - - onTapCalendar(BuildContext context) { - return () { - openDatePickerDialog(context); - }; - } - - /// Navigates to the previous screen. - onTapArrowLeft(BuildContext context) { - GoRouter.of(context).pop(); - } - - /// Displays a date picker dialog to update the selected date - /// - /// This function returns a `Future` that completes with `void`. - Future openDatePickerDialog(BuildContext context) async { - DateTime? dateTime = await showDatePicker( - context: context, - initialDate: DateTime.now(), - firstDate: DateTime(1924), - lastDate: DateTime( - DateTime.now().year, - DateTime.now().month, - DateTime.now().day, - ), - ); - if (dateTime != null) { - if (mounted) { - setState(() { - selectedDate = dateTime; - }); - } - } - } -} diff --git a/lib/presentation/registration/date_of_birth_screen/models/date_of_birth_model.dart b/lib/presentation/registration/date_of_birth_screen/models/date_of_birth_model.dart deleted file mode 100644 index 121b10d6..00000000 --- a/lib/presentation/registration/date_of_birth_screen/models/date_of_birth_model.dart +++ /dev/null @@ -1,21 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; - -/// This class defines the variables used in the [date_of_birth_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class DateOfBirthModel extends Equatable { - UserRegistrationSheet userRegistrationSheet; - - DateOfBirthModel({required this.userRegistrationSheet}); - - DateOfBirthModel copyWith() { - return DateOfBirthModel( - userRegistrationSheet: userRegistrationSheet, - ); - } - - @override - List get props => [userRegistrationSheet]; -} diff --git a/lib/presentation/registration/favorite_foods_screen/bloc/favorite_foods_bloc.dart b/lib/presentation/registration/favorite_foods_screen/bloc/favorite_foods_bloc.dart deleted file mode 100644 index b9494911..00000000 --- a/lib/presentation/registration/favorite_foods_screen/bloc/favorite_foods_bloc.dart +++ /dev/null @@ -1,22 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/favorite_foods_screen/models/favorite_foods_model.dart'; -part 'favorite_foods_event.dart'; -part 'favorite_foods_state.dart'; - -/// A bloc that manages the state of a FavoriteFoods according to the event that is dispatched to it. -class FavoriteFoodsBloc extends Bloc { - FavoriteFoodsBloc(FavoriteFoodsState initialState) : super(initialState) { - on(_onInitialize); - } - - _onInitialize( - FavoriteFoodsInitialEvent event, - Emitter emit, - ) async { - emit(state.copyWith( - favoriteFoodsController: TextEditingController(), - unfavoriteFoodsController: TextEditingController(),),); - } -} diff --git a/lib/presentation/registration/favorite_foods_screen/bloc/favorite_foods_event.dart b/lib/presentation/registration/favorite_foods_screen/bloc/favorite_foods_event.dart deleted file mode 100644 index f930b8e0..00000000 --- a/lib/presentation/registration/favorite_foods_screen/bloc/favorite_foods_event.dart +++ /dev/null @@ -1,16 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'favorite_foods_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///FavoriteFoods widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class FavoriteFoodsEvent extends Equatable {} - -/// Event that is dispatched when the FavoriteFoods widget is first created. -class FavoriteFoodsInitialEvent extends FavoriteFoodsEvent { - @override - List get props => []; -} diff --git a/lib/presentation/registration/favorite_foods_screen/bloc/favorite_foods_state.dart b/lib/presentation/registration/favorite_foods_screen/bloc/favorite_foods_state.dart deleted file mode 100644 index aa4fc3b8..00000000 --- a/lib/presentation/registration/favorite_foods_screen/bloc/favorite_foods_state.dart +++ /dev/null @@ -1,39 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'favorite_foods_bloc.dart'; - -/// Represents the state of FavoriteFoods in the application. -class FavoriteFoodsState extends Equatable { - FavoriteFoodsState({ - this.favoriteFoodsController, - this.unfavoriteFoodsController, - this.favoriteFoodsModelObj, - }); - - TextEditingController? favoriteFoodsController; - - TextEditingController? unfavoriteFoodsController; - - FavoriteFoodsModel? favoriteFoodsModelObj; - - @override - List get props => [ - favoriteFoodsController, - unfavoriteFoodsController, - favoriteFoodsModelObj, - ]; - FavoriteFoodsState copyWith({ - TextEditingController? favoriteFoodsController, - TextEditingController? unfavoriteFoodsController, - FavoriteFoodsModel? favoriteFoodsModelObj, - }) { - return FavoriteFoodsState( - favoriteFoodsController: - favoriteFoodsController ?? this.favoriteFoodsController, - unfavoriteFoodsController: - unfavoriteFoodsController ?? this.unfavoriteFoodsController, - favoriteFoodsModelObj: - favoriteFoodsModelObj ?? this.favoriteFoodsModelObj, - ); - } -} diff --git a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart b/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart deleted file mode 100644 index ea90d988..00000000 --- a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart +++ /dev/null @@ -1,145 +0,0 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/favorite_foods_bloc.dart'; -import 'models/favorite_foods_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; - -class FavoriteFoodsScreen extends StatefulWidget { - const FavoriteFoodsScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => - FavoriteFoodsBloc(FavoriteFoodsState(favoriteFoodsModelObj: FavoriteFoodsModel(userRegistrationSheet: sheet)))..add(FavoriteFoodsInitialEvent()), - child: FavoriteFoodsScreen(),); - } - - @override - State createState() => _FavoriteFoodsScreenState(); -} - -class _FavoriteFoodsScreenState extends State { - @override - Widget build(BuildContext context) { - return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), - child: Column(children: [ - SizedBox(height: 7.v), - Container( - height: 16.v, - width: 343.h, - decoration: BoxDecoration( - color: theme.colorScheme.onPrimary, - borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.h),), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: 0.90, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation(appTheme.blueA400),),),), - SizedBox(height: 19.v), - Container( - width: 327.h, - margin: EdgeInsets.only(left: 8.h, right: 7.h), - child: Text("favorite_unfavorite_foods".tr, - maxLines: 2, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: theme.textTheme.headlineSmall,),), - SizedBox(height: 13.v), - _buildTextFormFieldFav(context), - SizedBox(height: 12.v), - _buildTextFormFieldUnfav(context), - Spacer(), - BlocBuilder(builder: (context, state) { - return NextStepButton( - text: "continue".tr.toUpperCase(), - margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 40.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapContinue(state, context),); - },), - BlocBuilder(builder: (context, state) { - return GestureDetector( - onTap: onTapSkip(state, context), - child: Text("skip".tr, style: theme.textTheme.bodyLarge), - ); - },), - ],),),); - } - - onTapSkip(FavoriteFoodsState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.favoriteFoodsModelObj!.userRegistrationSheet; - GoRouter.of(context).goNamed('additionalInformationScreen', extra: sheet); - }; - } - - onTapContinue(FavoriteFoodsState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.favoriteFoodsModelObj!.userRegistrationSheet; - sheet.favoriteFoods = state.favoriteFoodsController!.text; - sheet.unfavoriteFoods = state.unfavoriteFoodsController!.text; - GoRouter.of(context).goNamed('additionalInformationScreen', extra: sheet); - }; - } - - /// Section Widget - _buildAppBar(BuildContext context) { - return CustomAppBar( - leadingWidth: 31.h, - leading: - AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 18.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), - centerTitle: true, - title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); - } - - Function onTapBack(BuildContext context) { - return () { - onTapArrowLeft(context); - }; - } - - /// Section Widget - _buildTextFormFieldFav(BuildContext context) { - return Column(children: [ - Text("favorite_foods".tr, style: CustomTextStyles.titleMediumSegoeUI), - SizedBox(height: 2.v), - BlocSelector( - selector: (state) => state.favoriteFoodsController, - builder: (context, favoriteFoodsController) { - return CustomTextFormField(controller: favoriteFoodsController, hintText: "enter_information".tr, maxLines: 7); - },), - ],); - } - - /// Section Widget - _buildTextFormFieldUnfav(BuildContext context) { - return Column(children: [ - Text("unfavorite_foods".tr, style: CustomTextStyles.titleMediumSegoeUI), - SizedBox(height: 2.v), - BlocSelector( - selector: (state) => state.unfavoriteFoodsController, - builder: (context, unfavoriteFoodsController) { - return CustomTextFormField( - controller: unfavoriteFoodsController, hintText: "enter_information".tr, textInputAction: TextInputAction.done, maxLines: 7,); - },), - ],); - } - - /// Navigates to the previous screen. - onTapArrowLeft(BuildContext context) { - GoRouter.of(context).pop(); - } - - /// Navigates to the scheduleScreen when the action is triggered. - navigateToAdditionalInformationScreen(BuildContext context) { - GoRouter.of(context).goNamed('additionalInformationScreen'); - } -} diff --git a/lib/presentation/registration/favorite_foods_screen/models/favorite_foods_model.dart b/lib/presentation/registration/favorite_foods_screen/models/favorite_foods_model.dart deleted file mode 100644 index 3aeeee20..00000000 --- a/lib/presentation/registration/favorite_foods_screen/models/favorite_foods_model.dart +++ /dev/null @@ -1,20 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; - -/// This class defines the variables used in the [favorite_foods_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class FavoriteFoodsModel extends Equatable { - UserRegistrationSheet userRegistrationSheet; - FavoriteFoodsModel({required this.userRegistrationSheet}); - - FavoriteFoodsModel copyWith() { - return FavoriteFoodsModel( - userRegistrationSheet: userRegistrationSheet, - ); - } - - @override - List get props => [userRegistrationSheet]; -} diff --git a/lib/presentation/registration/favorite_sports_screen/bloc/favorite_sports_bloc.dart b/lib/presentation/registration/favorite_sports_screen/bloc/favorite_sports_bloc.dart deleted file mode 100644 index 7857f8b4..00000000 --- a/lib/presentation/registration/favorite_sports_screen/bloc/favorite_sports_bloc.dart +++ /dev/null @@ -1,21 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/favorite_sports_screen/models/favorite_sports_model.dart'; -part 'favorite_sports_event.dart'; -part 'favorite_sports_state.dart'; - -/// A bloc that manages the state of a FavoriteSports according to the event that is dispatched to it. -class FavoriteSportsBloc - extends Bloc { - FavoriteSportsBloc(FavoriteSportsState initialState) : super(initialState) { - on(_onInitialize); - } - - _onInitialize( - FavoriteSportsInitialEvent event, - Emitter emit, - ) async { - emit(state.copyWith(enterinformationController: TextEditingController())); - } -} diff --git a/lib/presentation/registration/favorite_sports_screen/bloc/favorite_sports_event.dart b/lib/presentation/registration/favorite_sports_screen/bloc/favorite_sports_event.dart deleted file mode 100644 index ae9a018f..00000000 --- a/lib/presentation/registration/favorite_sports_screen/bloc/favorite_sports_event.dart +++ /dev/null @@ -1,16 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'favorite_sports_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///FavoriteSports widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class FavoriteSportsEvent extends Equatable {} - -/// Event that is dispatched when the FavoriteSports widget is first created. -class FavoriteSportsInitialEvent extends FavoriteSportsEvent { - @override - List get props => []; -} diff --git a/lib/presentation/registration/favorite_sports_screen/bloc/favorite_sports_state.dart b/lib/presentation/registration/favorite_sports_screen/bloc/favorite_sports_state.dart deleted file mode 100644 index c44cb2ad..00000000 --- a/lib/presentation/registration/favorite_sports_screen/bloc/favorite_sports_state.dart +++ /dev/null @@ -1,32 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'favorite_sports_bloc.dart'; - -/// Represents the state of FavoriteSports in the application. -class FavoriteSportsState extends Equatable { - FavoriteSportsState({ - this.enterinformationController, - this.favoriteSportsModelObj, - }); - - TextEditingController? enterinformationController; - - FavoriteSportsModel? favoriteSportsModelObj; - - @override - List get props => [ - enterinformationController, - favoriteSportsModelObj, - ]; - FavoriteSportsState copyWith({ - TextEditingController? enterinformationController, - FavoriteSportsModel? favoriteSportsModelObj, - }) { - return FavoriteSportsState( - enterinformationController: - enterinformationController ?? this.enterinformationController, - favoriteSportsModelObj: - favoriteSportsModelObj ?? this.favoriteSportsModelObj, - ); - } -} diff --git a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart b/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart deleted file mode 100644 index 498b24c4..00000000 --- a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart +++ /dev/null @@ -1,122 +0,0 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/favorite_sports_bloc.dart'; -import 'models/favorite_sports_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; - -class FavoriteSportsScreen extends StatefulWidget { - const FavoriteSportsScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => FavoriteSportsBloc(FavoriteSportsState(favoriteSportsModelObj: FavoriteSportsModel(userRegistrationSheet: sheet))) - ..add(FavoriteSportsInitialEvent()), - child: FavoriteSportsScreen(),); - } - - @override - State createState() => _FavoriteSportsScreenState(); -} - -class _FavoriteSportsScreenState extends State { - @override - Widget build(BuildContext context) { - return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 5.v), - child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [ - SizedBox(height: 20.v), - Container( - height: 16.v, - width: 343.h, - decoration: BoxDecoration( - color: theme.colorScheme.onPrimary, - borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.h),), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: 0.83, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation(appTheme.blueA400),),),), - SizedBox(height: 38.v), - Text("your_favorite_sports".tr, style: theme.textTheme.headlineSmall), - Spacer(flex: 32), - _buildTextFormFieldSection(context), - Spacer(flex: 67), - BlocBuilder(builder: (context, state) { - return NextStepButton( - text: "continue".tr.toUpperCase(), - margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapContinue(state, context),); - },), - BlocBuilder(builder: (context, state) { - return GestureDetector( - onTap: onTapSkip(state, context), - child: Text("skip".tr, style: theme.textTheme.bodyLarge), - ); - },), - ],),),); - } - - onTapSkip(FavoriteSportsState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.favoriteSportsModelObj!.userRegistrationSheet; - GoRouter.of(context).goNamed('favoriteFoodsScreen', extra: sheet); - }; - } - - onTapContinue(FavoriteSportsState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.favoriteSportsModelObj!.userRegistrationSheet; - sheet.aboutSportHobbies = state.enterinformationController!.text; - GoRouter.of(context).goNamed('favoriteFoodsScreen', extra: sheet); - }; - } - - _buildAppBar(BuildContext context) { - return CustomAppBar( - leadingWidth: 29.h, - leading: - AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), - centerTitle: true, - title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); - } - - Function onTapBack(BuildContext context) { - return () { - onTapArrowLeft(context); - }; - } - - /// Section Widget - _buildTextFormFieldSection(BuildContext context) { - return Column(children: [ - Text("fill_in_information".tr, style: CustomTextStyles.titleMediumSegoeUI), - SizedBox(height: 2.v), - BlocSelector( - selector: (state) => state.enterinformationController, - builder: (context, enterinformationController) { - return CustomTextFormField( - controller: enterinformationController, - hintText: - "Я занимаюсь плаванием , почти каждый вечер прогулки на свежем воздухе, пару раз в месяц играю в волейбол. Стараюсь не сидеть на месте!", - textInputAction: TextInputAction.done, - maxLines: 8,); - },), - ],); - } - - onTapArrowLeft(BuildContext context) { - GoRouter.of(context).pop(); - } -} diff --git a/lib/presentation/registration/favorite_sports_screen/models/favorite_sports_model.dart b/lib/presentation/registration/favorite_sports_screen/models/favorite_sports_model.dart deleted file mode 100644 index 25481701..00000000 --- a/lib/presentation/registration/favorite_sports_screen/models/favorite_sports_model.dart +++ /dev/null @@ -1,20 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; - -/// This class defines the variables used in the [favorite_sports_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class FavoriteSportsModel extends Equatable { - UserRegistrationSheet userRegistrationSheet; - FavoriteSportsModel({required this.userRegistrationSheet}); - - FavoriteSportsModel copyWith() { - return FavoriteSportsModel( - userRegistrationSheet: userRegistrationSheet, - ); - } - - @override - List get props => [userRegistrationSheet]; -} diff --git a/lib/presentation/registration/gender_screen/bloc/gender_bloc.dart b/lib/presentation/registration/gender_screen/bloc/gender_bloc.dart deleted file mode 100644 index 5f614c27..00000000 --- a/lib/presentation/registration/gender_screen/bloc/gender_bloc.dart +++ /dev/null @@ -1,29 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/gender_screen/models/gender_model.dart'; -part 'gender_event.dart'; -part 'gender_state.dart'; - -/// A bloc that manages the state of a Gender according to the event that is dispatched to it. -class GenderBloc extends Bloc { - GenderBloc(GenderState initialState) : super(initialState) { - on(_onInitialize); - on(_genderSelect); - } - - _onInitialize( - GenderInitialEvent event, - Emitter emit, - ) async { - emit(state.copyWith(genderModelObj: state.genderModelObj)); - } - - _genderSelect( - GenderSelectEvent event, - Emitter emit, - ) { - emit(state.copyWith(selectedRadioValue: event.value)); - state.genderModelObj?.userRegistrationSheet.gender = event.value; - } -} diff --git a/lib/presentation/registration/gender_screen/bloc/gender_event.dart b/lib/presentation/registration/gender_screen/bloc/gender_event.dart deleted file mode 100644 index f6b9f69c..00000000 --- a/lib/presentation/registration/gender_screen/bloc/gender_event.dart +++ /dev/null @@ -1,26 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'gender_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///Gender widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class GenderEvent extends Equatable {} - -class GenderInitialEvent extends GenderEvent { - @override - List get props => []; -} - -class GenderSelectEvent extends GenderEvent { - GenderSelectEvent({required this.value}); - - String value; - - @override - List get props => [ - value, - ]; -} diff --git a/lib/presentation/registration/gender_screen/bloc/gender_state.dart b/lib/presentation/registration/gender_screen/bloc/gender_state.dart deleted file mode 100644 index 996082e8..00000000 --- a/lib/presentation/registration/gender_screen/bloc/gender_state.dart +++ /dev/null @@ -1,30 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'gender_bloc.dart'; - -/// Represents the state of Gender in the application. -class GenderState extends Equatable { - GenderState({ - this.selectedRadioValue, - this.genderModelObj, - }); - - String? selectedRadioValue; - - GenderModel? genderModelObj; - - @override - List get props => [ - selectedRadioValue, - genderModelObj, - ]; - GenderState copyWith({ - String? selectedRadioValue, - GenderModel? genderModelObj, - }) { - return GenderState( - selectedRadioValue: selectedRadioValue ?? this.selectedRadioValue, - genderModelObj: genderModelObj ?? this.genderModelObj, - ); - } -} diff --git a/lib/presentation/registration/gender_screen/gender_screen.dart b/lib/presentation/registration/gender_screen/gender_screen.dart deleted file mode 100644 index d6a9b63d..00000000 --- a/lib/presentation/registration/gender_screen/gender_screen.dart +++ /dev/null @@ -1,131 +0,0 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/gender_bloc.dart'; -import 'models/gender_model.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:flutter/material.dart'; - -class GenderScreen extends StatefulWidget { - const GenderScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => GenderBloc( - GenderState( - genderModelObj: GenderModel(userRegistrationSheet: sheet), - ), - )..add(GenderInitialEvent()), - child: GenderScreen(),); - } - - @override - State createState() => _GenderScreenState(); -} - -class _GenderScreenState extends State { - @override - Widget build(BuildContext context) { - mediaQueryData = MediaQuery.of(context); - return BlocBuilder(builder: (context, state) { - return Scaffold( - appBar: _buildAppBar(context), - body: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), - child: Column(children: [ - SizedBox(height: 7.v), - Container( - height: 16.v, - width: 343.h, - decoration: BoxDecoration( - color: theme.colorScheme.onPrimary, - borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.h),), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: 0.16, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation(appTheme.blueA400),),),), - SizedBox(height: 36.v), - Text("your_gender".tr, style: theme.textTheme.headlineSmall), - RadioListTile( - title: Text('Мужской'), - value: 'male', - groupValue: state.selectedRadioValue, - onChanged: onMale(context), - secondary: Image.asset( - 'assets/images/img_male.png', - width: 40, - height: 40, - ), - ), - RadioListTile( - title: Text('Женский'), - value: 'female', - groupValue: state.selectedRadioValue, - onChanged: onFemale(context), - secondary: Image.asset( - 'assets/images/img_female.png', - width: 40, - height: 40, - ), - ), - Spacer(flex: 66), - BlocBuilder(builder: (context, state) { - return NextStepButton( - text: "continue".tr.toUpperCase(), - margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapNext(state, context),); - },), - ],),),); - },); - } - - onTapNext(GenderState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.genderModelObj!.userRegistrationSheet; - sheet.gender = state.selectedRadioValue!; - GoRouter.of(context).goNamed('dateOfBirthScreen', extra: sheet); - }; - } - - onMale(BuildContext context) { - return (value) { - BlocProvider.of(context).add(GenderSelectEvent(value: 'male')); - }; - } - - onFemale(BuildContext context) { - return (value) { - BlocProvider.of(context).add(GenderSelectEvent(value: 'female')); - }; - } - - /// Section Widget - _buildAppBar(BuildContext context) { - return CustomAppBar( - leadingWidth: 29.h, - leading: AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack()), - centerTitle: true, - title: AppbarTitleImage( - imagePath: ImageConstant.imgLogoEatvio, - ), - ); - } - - Function onTapBack() { - return () { - GoRouter.of(context).pop(); - }; - } - - /// Navigates to the previous screen. - onTapArrowLeft(BuildContext context) { - GoRouter.of(context).pop(); - } -} diff --git a/lib/presentation/registration/gender_screen/models/gender_model.dart b/lib/presentation/registration/gender_screen/models/gender_model.dart deleted file mode 100644 index 69779b41..00000000 --- a/lib/presentation/registration/gender_screen/models/gender_model.dart +++ /dev/null @@ -1,20 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; - -/// This class defines the variables used in the [gender_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class GenderModel extends Equatable { - UserRegistrationSheet userRegistrationSheet; - GenderModel({required this.userRegistrationSheet}); - - GenderModel copyWith({UserRegistrationSheet? userRegistrationSheet, gender}) { - return GenderModel( - userRegistrationSheet: - userRegistrationSheet ?? this.userRegistrationSheet,); - } - - @override - List get props => [userRegistrationSheet]; -} diff --git a/lib/presentation/registration/height_screen/bloc/height_bloc.dart b/lib/presentation/registration/height_screen/bloc/height_bloc.dart deleted file mode 100644 index 223f7194..00000000 --- a/lib/presentation/registration/height_screen/bloc/height_bloc.dart +++ /dev/null @@ -1,22 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/height_screen/models/height_model.dart'; -part 'height_event.dart'; -part 'height_state.dart'; - -/// A bloc that manages the state of a Height according to the event that is dispatched to it. -class HeightBloc extends Bloc { - HeightBloc(HeightState initialState) : super(initialState) { - on(_onInitialize); - } - - _onInitialize( - HeightInitialEvent event, - Emitter emit, - ) async { - emit(state.copyWith( - heightModelObj: state.heightModelObj?.copyWith(), - heightController: state.heightController,),); - } -} diff --git a/lib/presentation/registration/height_screen/bloc/height_event.dart b/lib/presentation/registration/height_screen/bloc/height_event.dart deleted file mode 100644 index 1d65dd82..00000000 --- a/lib/presentation/registration/height_screen/bloc/height_event.dart +++ /dev/null @@ -1,16 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'height_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///Height widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class HeightEvent extends Equatable {} - -/// Event that is dispatched when the Height widget is first created. -class HeightInitialEvent extends HeightEvent { - @override - List get props => []; -} diff --git a/lib/presentation/registration/height_screen/bloc/height_state.dart b/lib/presentation/registration/height_screen/bloc/height_state.dart deleted file mode 100644 index aa10592f..00000000 --- a/lib/presentation/registration/height_screen/bloc/height_state.dart +++ /dev/null @@ -1,30 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'height_bloc.dart'; - -/// Represents the state of Height in the application. -class HeightState extends Equatable { - HeightState({ - this.heightController, - this.heightModelObj, - }); - - TextEditingController? heightController; - - HeightModel? heightModelObj; - - @override - List get props => [ - heightController, - heightModelObj, - ]; - HeightState copyWith({ - TextEditingController? heightController, - HeightModel? heightModelObj, - }) { - return HeightState( - heightController: heightController ?? this.heightController, - heightModelObj: heightModelObj ?? this.heightModelObj, - ); - } -} diff --git a/lib/presentation/registration/height_screen/height_screen.dart b/lib/presentation/registration/height_screen/height_screen.dart deleted file mode 100644 index 22ada6c4..00000000 --- a/lib/presentation/registration/height_screen/height_screen.dart +++ /dev/null @@ -1,135 +0,0 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/height_bloc.dart'; -import 'models/height_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:flutter/services.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; - -class HeightScreen extends StatelessWidget { - const HeightScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => HeightBloc(HeightState(heightModelObj: HeightModel(userRegistrationSheet: sheet)))..add(HeightInitialEvent()), - child: HeightScreen(),); - } - - @override - Widget build(BuildContext context) { - mediaQueryData = MediaQuery.of(context); - return Scaffold( - appBar: _buildAppBar(context), - body: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), - child: Column( - children: [ - SizedBox(height: 7.v), - Container( - height: 16.v, - width: 343.h, - decoration: BoxDecoration( - color: theme.colorScheme.onPrimary, - borderRadius: BorderRadius.circular(8.h), - border: Border.all( - color: theme.colorScheme.primary, - width: 1.h, - ), - ), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: 0.55, - backgroundColor: theme.colorScheme.onPrimary, - valueColor: AlwaysStoppedAnimation( - appTheme.blueA400, - ), - ), - ), - ), - SizedBox(height: 39.v), - Column( - children: [ - Text( - "height_measurements".tr, - style: theme.textTheme.headlineSmall, - ), - SizedBox(height: 174.v), - Column( - children: [ - Text( - "your_height".tr, - style: theme.textTheme.bodyLarge, - ), - SizedBox(height: 4.v), - BlocBuilder(builder: (context, state) { - return CustomTextFormField( - width: 150.h, - textInputAction: TextInputAction.done, - controller: state.heightController, - keyboardType: TextInputType.number, - inputFormatters: [ - FilteringTextInputFormatter.digitsOnly, - ], - ); - },), - ], - ), - ], - ), - Spacer(), - BlocBuilder( - builder: (context, state) { - return NextStepButton( - text: "continue".tr.toUpperCase(), - margin: EdgeInsets.only( - left: 16.h, - right: 16.h, - bottom: 50.v, - ), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapNext(state, context), - ); - }, - ), - ], - ), - ), - ); - } - - onTapNext(HeightState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.heightModelObj!.userRegistrationSheet; - GoRouter.of(context).goNamed('bloodPressureScreen', extra: sheet); - }; - } - - /// Section Widget - _buildAppBar(BuildContext context) { - return CustomAppBar( - leadingWidth: 29.h, - leading: - AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), - centerTitle: true, - title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); - } - - Function onTapBack(BuildContext context) { - return () { - onTapArrowLeft(context); - }; - } - - /// Navigates to the previous screen. - onTapArrowLeft(BuildContext context) { - GoRouter.of(context).pop(); - } -} diff --git a/lib/presentation/registration/height_screen/models/height_model.dart b/lib/presentation/registration/height_screen/models/height_model.dart deleted file mode 100644 index 3a56580a..00000000 --- a/lib/presentation/registration/height_screen/models/height_model.dart +++ /dev/null @@ -1,25 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; -import 'package:eatvio_app/data/models/selectionPopupModel/selection_popup_model.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; - -/// This class defines the variables used in the [height_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class HeightModel extends Equatable { - UserRegistrationSheet userRegistrationSheet; - HeightModel( - {this.dropdownItemList = const [], required this.userRegistrationSheet,}); - - List dropdownItemList; - - HeightModel copyWith({List? dropdownItemList}) { - return HeightModel( - userRegistrationSheet: userRegistrationSheet, - dropdownItemList: dropdownItemList ?? this.dropdownItemList, - ); - } - - @override - List get props => [dropdownItemList, userRegistrationSheet]; -} diff --git a/lib/presentation/registration/language_select_screen/bloc/language_select_bloc.dart b/lib/presentation/registration/language_select_screen/bloc/language_select_bloc.dart deleted file mode 100644 index b0592bb0..00000000 --- a/lib/presentation/registration/language_select_screen/bloc/language_select_bloc.dart +++ /dev/null @@ -1,39 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/language_select_screen/models/language_select_model.dart'; -part 'language_select_event.dart'; -part 'language_select_state.dart'; - -/// A bloc that manages the state of a LanguageSelect according to the event that is dispatched to it. -class LanguageSelectBloc - extends Bloc { - LanguageSelectBloc(LanguageSelectState initialState) : super(initialState) { - on(_onInitialize); - on(_changeDropDown); - } - - _onInitialize( - LanguageSelectInitialEvent event, - Emitter emit, - ) async { - emit(state.copyWith( - languageSelectModelObj: state.languageSelectModelObj - ?.copyWith(dropdownItemList: fillDropdownItemList()),),); - } - - _changeDropDown( - ChangeDropDownEvent event, - Emitter emit, - ) { - emit(state.copyWith(selectedDropDownValue: event.value)); - state.languageSelectModelObj?.userRegistrationSheet.lang = - event.value.title; - } - - List fillDropdownItemList() { - return [ - SelectionPopupModel(id: 1, title: "Русский", isSelected: true), - ]; - } -} diff --git a/lib/presentation/registration/language_select_screen/bloc/language_select_event.dart b/lib/presentation/registration/language_select_screen/bloc/language_select_event.dart deleted file mode 100644 index 5c39a950..00000000 --- a/lib/presentation/registration/language_select_screen/bloc/language_select_event.dart +++ /dev/null @@ -1,28 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'language_select_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///LanguageSelect widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class LanguageSelectEvent extends Equatable {} - -/// Event that is dispatched when the LanguageSelect widget is first created. -class LanguageSelectInitialEvent extends LanguageSelectEvent { - @override - List get props => []; -} - -///event for dropdown selection -class ChangeDropDownEvent extends LanguageSelectEvent { - ChangeDropDownEvent({required this.value}); - - SelectionPopupModel value; - - @override - List get props => [ - value, - ]; -} diff --git a/lib/presentation/registration/language_select_screen/bloc/language_select_state.dart b/lib/presentation/registration/language_select_screen/bloc/language_select_state.dart deleted file mode 100644 index 602a4adc..00000000 --- a/lib/presentation/registration/language_select_screen/bloc/language_select_state.dart +++ /dev/null @@ -1,32 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'language_select_bloc.dart'; - -/// Represents the state of LanguageSelect in the application. -class LanguageSelectState extends Equatable { - LanguageSelectState({ - this.selectedDropDownValue, - this.languageSelectModelObj, - }); - - SelectionPopupModel? selectedDropDownValue; - - LanguageSelectModel? languageSelectModelObj; - - @override - List get props => [ - selectedDropDownValue, - languageSelectModelObj, - ]; - LanguageSelectState copyWith({ - SelectionPopupModel? selectedDropDownValue, - LanguageSelectModel? languageSelectModelObj, - }) { - return LanguageSelectState( - selectedDropDownValue: - selectedDropDownValue ?? this.selectedDropDownValue, - languageSelectModelObj: - languageSelectModelObj ?? this.languageSelectModelObj, - ); - } -} diff --git a/lib/presentation/registration/language_select_screen/language_select_screen.dart b/lib/presentation/registration/language_select_screen/language_select_screen.dart deleted file mode 100644 index a682d9db..00000000 --- a/lib/presentation/registration/language_select_screen/language_select_screen.dart +++ /dev/null @@ -1,121 +0,0 @@ -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:go_router/go_router.dart'; - -import 'bloc/language_select_bloc.dart'; -import 'models/language_select_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/custom_drop_down.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:flutter/material.dart'; - -class LanguageSelectScreen extends StatelessWidget { - const LanguageSelectScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context) { - return BlocProvider( - create: (context) => LanguageSelectBloc( - LanguageSelectState( - languageSelectModelObj: LanguageSelectModel(), - ), - )..add(LanguageSelectInitialEvent()), - child: LanguageSelectScreen(), - ); - } - - @override - Widget build(BuildContext context) { - return Scaffold( - body: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 5.v), - child: Column( - children: [ - CustomImageView(imagePath: ImageConstant.imgLogoEatvio, height: 50.adaptSize, width: 50.adaptSize), - SizedBox(height: 20.v), - Container( - height: 16.v, - width: 343.h, - decoration: BoxDecoration( - color: theme.colorScheme.onPrimary, - borderRadius: BorderRadius.circular(8.h), - border: Border.all( - color: theme.colorScheme.primary, - width: 1.h, - ), - ), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: 0, - backgroundColor: theme.colorScheme.onPrimary, - valueColor: AlwaysStoppedAnimation(appTheme.blueA400), - ), - ), - ), - SizedBox(height: 20.v), - Container( - width: 262.h, - margin: EdgeInsets.only(left: 41.h, right: 39.h), - child: Text( - "preferred_language".tr, - maxLines: 2, - overflow: TextOverflow.ellipsis, - textAlign: TextAlign.center, - style: theme.textTheme.headlineSmall, - ), - ), - Spacer(flex: 36), - BlocSelector( - selector: (state) => state.languageSelectModelObj, - builder: ( - context, - languageSelectModelObj, - ) { - return CustomDropDown( - icon: Container( - margin: EdgeInsets.fromLTRB(30.h, 11.v, 17.h, 11.v), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(1.h), - ), - child: CustomImageView( - imagePath: ImageConstant.imgFavorite, - height: 12.adaptSize, - width: 12.adaptSize, - ), - ), - hintText: "Не выбрано".tr, - items: languageSelectModelObj?.dropdownItemList ?? [], - onChanged: (value) => _onDropDownChanged(context, value), - ); - },), - Spacer(flex: 63), - ], - ), - ), - bottomNavigationBar: BlocBuilder( - builder: (context, state) { - return NextStepButton( - text: "continue".tr.toUpperCase(), - margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: _saveAndPush(state, context), - ); - }, - ), - ); - } - - void Function()? _saveAndPush(LanguageSelectState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.languageSelectModelObj!.userRegistrationSheet; - GoRouter.of(context).goNamed( - 'credentialsScreen', - extra: sheet, - ); - }; - } - - void _onDropDownChanged(BuildContext context, value) { - context.read().add(ChangeDropDownEvent(value: value)); - } -} diff --git a/lib/presentation/registration/language_select_screen/models/language_select_model.dart b/lib/presentation/registration/language_select_screen/models/language_select_model.dart deleted file mode 100644 index 465a8ac8..00000000 --- a/lib/presentation/registration/language_select_screen/models/language_select_model.dart +++ /dev/null @@ -1,50 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:eatvio_app/data/models/selectionPopupModel/selection_popup_model.dart'; - -/// This class defines the variables used in the [language_select_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class LanguageSelectModel extends Equatable { - LanguageSelectModel({this.dropdownItemList = const []}); - UserRegistrationSheet userRegistrationSheet = UserRegistrationSheet( - name: '', - firstName: '', - lastName: '', - email: '', - password: '', - passwordConfirmation: '', - termsAccepted: 'accepted', - birthdate: DateTime.now().toString(), - gender: '', - country: '', - city: '', - lang: '', - weight: '', - height: '', - chestCircumference: '', - waistCircumference: '', - hipCircumference: '', - bloodPressureUp: '', - bloodPressureDown: '', - hasHypo: '', - hasHyper: '', - aboutAllergy: '', - aboutTakingPils: '', - aboutSportHobbies: '', - favoriteFoods: '', - unfavoriteFoods: '', - additionalInfo: '', - ); - List dropdownItemList; - - LanguageSelectModel copyWith({List? dropdownItemList}) { - return LanguageSelectModel( - dropdownItemList: dropdownItemList ?? this.dropdownItemList, - ); - } - - @override - List get props => [dropdownItemList]; -} diff --git a/lib/presentation/registration/medicine_intake_screen/bloc/medicine_intake_bloc.dart b/lib/presentation/registration/medicine_intake_screen/bloc/medicine_intake_bloc.dart deleted file mode 100644 index bd878765..00000000 --- a/lib/presentation/registration/medicine_intake_screen/bloc/medicine_intake_bloc.dart +++ /dev/null @@ -1,21 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/medicine_intake_screen/models/medicine_intake_model.dart'; -part 'medicine_intake_event.dart'; -part 'medicine_intake_state.dart'; - -/// A bloc that manages the state of a MedicineIntake according to the event that is dispatched to it. -class MedicineIntakeBloc - extends Bloc { - MedicineIntakeBloc(MedicineIntakeState initialState) : super(initialState) { - on(_onInitialize); - } - - _onInitialize( - MedicineIntakeInitialEvent event, - Emitter emit, - ) async { - emit(state.copyWith(enterInformationController: TextEditingController())); - } -} diff --git a/lib/presentation/registration/medicine_intake_screen/bloc/medicine_intake_event.dart b/lib/presentation/registration/medicine_intake_screen/bloc/medicine_intake_event.dart deleted file mode 100644 index 0300b286..00000000 --- a/lib/presentation/registration/medicine_intake_screen/bloc/medicine_intake_event.dart +++ /dev/null @@ -1,16 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'medicine_intake_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///MedicineIntake widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class MedicineIntakeEvent extends Equatable {} - -/// Event that is dispatched when the MedicineIntake widget is first created. -class MedicineIntakeInitialEvent extends MedicineIntakeEvent { - @override - List get props => []; -} diff --git a/lib/presentation/registration/medicine_intake_screen/bloc/medicine_intake_state.dart b/lib/presentation/registration/medicine_intake_screen/bloc/medicine_intake_state.dart deleted file mode 100644 index 8d7958f6..00000000 --- a/lib/presentation/registration/medicine_intake_screen/bloc/medicine_intake_state.dart +++ /dev/null @@ -1,32 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'medicine_intake_bloc.dart'; - -/// Represents the state of MedicineIntake in the application. -class MedicineIntakeState extends Equatable { - MedicineIntakeState({ - this.enterInformationController, - this.medicineIntakeModelObj, - }); - - TextEditingController? enterInformationController; - - MedicineIntakeModel? medicineIntakeModelObj; - - @override - List get props => [ - enterInformationController, - medicineIntakeModelObj, - ]; - MedicineIntakeState copyWith({ - TextEditingController? enterInformationController, - MedicineIntakeModel? medicineIntakeModelObj, - }) { - return MedicineIntakeState( - enterInformationController: - enterInformationController ?? this.enterInformationController, - medicineIntakeModelObj: - medicineIntakeModelObj ?? this.medicineIntakeModelObj, - ); - } -} diff --git a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart b/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart deleted file mode 100644 index bce90496..00000000 --- a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart +++ /dev/null @@ -1,131 +0,0 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/medicine_intake_bloc.dart'; -import 'models/medicine_intake_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; - -class MedicineIntakeScreen extends StatefulWidget { - const MedicineIntakeScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => MedicineIntakeBloc(MedicineIntakeState(medicineIntakeModelObj: MedicineIntakeModel(userRegistrationSheet: sheet))) - ..add(MedicineIntakeInitialEvent()), - child: MedicineIntakeScreen(),); - } - - @override - State createState() => _MedicineIntakeScreenState(); -} - -class _MedicineIntakeScreenState extends State { - @override - Widget build(BuildContext context) { - mediaQueryData = MediaQuery.of(context); - return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), - child: Column(children: [ - SizedBox(height: 7.v), - Container( - height: 16.v, - width: 343.h, - decoration: BoxDecoration( - color: theme.colorScheme.onPrimary, - borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.h),), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: 0.69, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation(appTheme.blueA400),),),), - SizedBox(height: 20.v), - Container( - width: 271.h, - margin: EdgeInsets.only(left: 35.h, right: 36.h), - child: Text("do_you_take_pills".tr, - maxLines: 2, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: theme.textTheme.headlineSmall,),), - SizedBox(height: 86.v), - _buildTextFormField(context), - Spacer(), - BlocBuilder(builder: (context, state) { - return NextStepButton( - text: "continue".tr.toUpperCase(), - margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapNext(state, context),); - },), - BlocBuilder(builder: (context, state) { - return GestureDetector( - onTap: onTapSkip(state, context), - child: Text("skip".tr, style: theme.textTheme.bodyLarge), - ); - },), - ],),),); - } - - onTapSkip(MedicineIntakeState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.medicineIntakeModelObj!.userRegistrationSheet; - GoRouter.of(context).goNamed( - 'bloodPressureScreen', - extra: sheet, - ); - }; - } - - onTapNext(MedicineIntakeState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.medicineIntakeModelObj!.userRegistrationSheet; - sheet.aboutTakingPils = state.enterInformationController!.text; - GoRouter.of(context).goNamed( - 'bloodPressureScreen', - extra: sheet, - ); - }; - } - - /// Section Widget - _buildAppBar(BuildContext context) { - return CustomAppBar( - leadingWidth: 31.h, - leading: - AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 18.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), - centerTitle: true, - title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); - } - - Function onTapBack(BuildContext context) { - return () { - onTapArrowLeft(context); - }; - } - - /// Section Widget - _buildTextFormField(BuildContext context) { - return Column(children: [ - Text("fill_in_information".tr, style: CustomTextStyles.titleMediumSegoeUI), - SizedBox(height: 2.v), - BlocSelector( - selector: (state) => state.enterInformationController, - builder: (context, enterInformationController) { - return CustomTextFormField( - controller: enterInformationController, hintText: "enter_information".tr, textInputAction: TextInputAction.done, maxLines: 8,); - },), - ],); - } - - /// Navigates to the previous screen. - onTapArrowLeft(BuildContext context) { - GoRouter.of(context).pop(); - } -} diff --git a/lib/presentation/registration/medicine_intake_screen/models/medicine_intake_model.dart b/lib/presentation/registration/medicine_intake_screen/models/medicine_intake_model.dart deleted file mode 100644 index f6634de4..00000000 --- a/lib/presentation/registration/medicine_intake_screen/models/medicine_intake_model.dart +++ /dev/null @@ -1,20 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; - -/// This class defines the variables used in the [medicine_intake_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class MedicineIntakeModel extends Equatable { - UserRegistrationSheet userRegistrationSheet; - MedicineIntakeModel({required this.userRegistrationSheet}); - - MedicineIntakeModel copyWith() { - return MedicineIntakeModel( - userRegistrationSheet: userRegistrationSheet, - ); - } - - @override - List get props => [userRegistrationSheet]; -} diff --git a/lib/presentation/registration/name_screen/bloc/name_bloc.dart b/lib/presentation/registration/name_screen/bloc/name_bloc.dart deleted file mode 100644 index e4a51431..00000000 --- a/lib/presentation/registration/name_screen/bloc/name_bloc.dart +++ /dev/null @@ -1,22 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/name_screen/models/name_model.dart'; -part 'name_event.dart'; -part 'name_state.dart'; - -/// A bloc that manages the state of a Name according to the event that is dispatched to it. -class NameBloc extends Bloc { - NameBloc(NameState initialState) : super(initialState) { - on(_onInitialize); - } - - _onInitialize( - NameInitialEvent event, - Emitter emit, - ) async { - emit(state.copyWith( - firstNameController: TextEditingController(), - lastNameController: TextEditingController(),),); - } -} diff --git a/lib/presentation/registration/name_screen/bloc/name_event.dart b/lib/presentation/registration/name_screen/bloc/name_event.dart deleted file mode 100644 index 7e102994..00000000 --- a/lib/presentation/registration/name_screen/bloc/name_event.dart +++ /dev/null @@ -1,16 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'name_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///Name widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class NameEvent extends Equatable {} - -/// Event that is dispatched when the Name widget is first created. -class NameInitialEvent extends NameEvent { - @override - List get props => []; -} diff --git a/lib/presentation/registration/name_screen/bloc/name_state.dart b/lib/presentation/registration/name_screen/bloc/name_state.dart deleted file mode 100644 index b3e0980b..00000000 --- a/lib/presentation/registration/name_screen/bloc/name_state.dart +++ /dev/null @@ -1,36 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'name_bloc.dart'; - -/// Represents the state of Name in the application. -class NameState extends Equatable { - NameState({ - this.firstNameController, - this.lastNameController, - this.nameModelObj, - }); - - TextEditingController? firstNameController; - - TextEditingController? lastNameController; - - NameModel? nameModelObj; - - @override - List get props => [ - firstNameController, - lastNameController, - nameModelObj, - ]; - NameState copyWith({ - TextEditingController? firstNameController, - TextEditingController? lastNameController, - NameModel? nameModelObj, - }) { - return NameState( - firstNameController: firstNameController ?? this.firstNameController, - lastNameController: lastNameController ?? this.lastNameController, - nameModelObj: nameModelObj ?? this.nameModelObj, - ); - } -} diff --git a/lib/presentation/registration/name_screen/models/name_model.dart b/lib/presentation/registration/name_screen/models/name_model.dart deleted file mode 100644 index 6fa44b07..00000000 --- a/lib/presentation/registration/name_screen/models/name_model.dart +++ /dev/null @@ -1,21 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; - -/// This class defines the variables used in the [name_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class NameModel extends Equatable { - UserRegistrationSheet userRegistrationSheet; - NameModel({required this.userRegistrationSheet}); - - NameModel copyWith({UserRegistrationSheet? userRegistrationSheet}) { - return NameModel( - userRegistrationSheet: - userRegistrationSheet ?? this.userRegistrationSheet, - ); - } - - @override - List get props => []; -} diff --git a/lib/presentation/registration/name_screen/name_screen.dart b/lib/presentation/registration/name_screen/name_screen.dart deleted file mode 100644 index 880c3ae2..00000000 --- a/lib/presentation/registration/name_screen/name_screen.dart +++ /dev/null @@ -1,155 +0,0 @@ -import 'package:eatvio_app/app_router.dart'; -import 'package:go_router/go_router.dart'; - -import 'bloc/name_bloc.dart'; -import 'models/name_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:flutter/material.dart'; - -class NameScreen extends StatelessWidget { - const NameScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => NameBloc( - NameState( - nameModelObj: NameModel(userRegistrationSheet: sheet), - ), - )..add(NameInitialEvent()), - child: NameScreen(),); - } - - @override - Widget build(BuildContext context) { - mediaQueryData = MediaQuery.of(context); - return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), - child: Column(children: [ - SizedBox(height: 7.v), - Container( - height: 16.v, - width: 343.h, - decoration: BoxDecoration( - color: theme.colorScheme.onPrimary, - borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.h),), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: 0.1, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation(appTheme.blueA400),),),), - SizedBox(height: 39.v), - Text("what_is_your_name".tr, style: theme.textTheme.headlineSmall), - SizedBox(height: 93.v), - Text("first_name".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 3.v), - BlocSelector( - selector: (state) => state.firstNameController, - builder: (context, firstNameController) { - return CustomTextFormField(controller: firstNameController, textInputAction: TextInputAction.done); - },), - SizedBox(height: 19.v), - Text("last_name".tr, style: theme.textTheme.bodyLarge), - SizedBox(height: 5.v), - BlocSelector( - selector: (state) => state.lastNameController, - builder: (context, lastNameController) { - return CustomTextFormField( - controller: lastNameController, - ); - },), - Spacer(), - BlocBuilder(builder: (context, state) { - return NextStepButton( - text: "continue".tr.toUpperCase(), - margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: () => _onTapNext(context, state), // Assign callback function here - ); - },), - ],),),); - } - - /// Section Widget - _buildAppBar(BuildContext context) { - return CustomAppBar( - leadingWidth: 29.h, - leading: AppbarLeadingImage( - imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: () => onTapArrowLeft(context),), - centerTitle: true, - title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); - } - - /// Navigates to the previous screen. - onTapArrowLeft(BuildContext context) { - GoRouter.of(context).pop(); - } - - _onTapNext(BuildContext context, NameState state) { - if (state.firstNameController != null && state.lastNameController != null) { - List errors = validateFields(state.firstNameController!.text, state.lastNameController!.text); - - if (errors.isEmpty) { - UserRegistrationSheet sheet = state.nameModelObj!.userRegistrationSheet; - sheet.firstName = state.firstNameController!.text; - sheet.lastName = state.lastNameController!.text; - AppRouter.navigatorKey.currentContext?.goNamed('genderScreen', extra: sheet); - } else { - String errorMessage = ''; - - for (var error in errors) { - errorMessage += error + '\n\n'; - } - - showDialog( - context: context, - builder: (context) => AlertDialog( - title: Text('Error'), - content: Text(errorMessage), - actions: [ - TextButton( - onPressed: () => onTapOk(context), - child: Text('OK'), - ), - ], - ), - ); - } - } - } - - void onTapOk(BuildContext context) { - Navigator.pop(context); - } - - List validateFields(String firstName, String lastName) { - List errors = []; - - if (firstName.isEmpty) { - errors.add('First name cannot be empty'); - } - - if (firstName.length < 1) { - errors.add('First name is too short'); - } - - if (lastName.isEmpty) { - errors.add('Last name cannot be empty'); - } - - if (lastName.length < 1) { - errors.add('Last name is too short'); - } - - return errors; - } -} diff --git a/lib/presentation/registration/splash_screen/bloc/splash_bloc.dart b/lib/presentation/registration/splash_screen/bloc/splash_bloc.dart deleted file mode 100644 index bdd396f0..00000000 --- a/lib/presentation/registration/splash_screen/bloc/splash_bloc.dart +++ /dev/null @@ -1,26 +0,0 @@ -import 'package:eatvio_app/app_router.dart'; -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import 'package:go_router/go_router.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/splash_screen/models/splash_model.dart'; - -part 'splash_event.dart'; - -part 'splash_state.dart'; - -/// A bloc that manages the state of a Splash according to the event that is dispatched to it. -class SplashBloc extends Bloc { - SplashBloc(SplashState initialState) : super(initialState) { - on(_onInitialize); - } - - _onInitialize( - SplashInitialEvent event, - Emitter emit, - ) async { - Future.delayed(const Duration(milliseconds: 3000), () { - AppRouter.navigatorKey.currentContext?.goNamed('myProfileScreen'); - }); - } -} diff --git a/lib/presentation/registration/splash_screen/bloc/splash_event.dart b/lib/presentation/registration/splash_screen/bloc/splash_event.dart deleted file mode 100644 index a78a25bb..00000000 --- a/lib/presentation/registration/splash_screen/bloc/splash_event.dart +++ /dev/null @@ -1,16 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'splash_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///Splash widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class SplashEvent extends Equatable {} - -/// Event that is dispatched when the Splash widget is first created. -class SplashInitialEvent extends SplashEvent { - @override - List get props => []; -} diff --git a/lib/presentation/registration/splash_screen/bloc/splash_state.dart b/lib/presentation/registration/splash_screen/bloc/splash_state.dart deleted file mode 100644 index e47ce03e..00000000 --- a/lib/presentation/registration/splash_screen/bloc/splash_state.dart +++ /dev/null @@ -1,20 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'splash_bloc.dart'; - -/// Represents the state of Splash in the application. -class SplashState extends Equatable { - SplashState({this.splashModelObj}); - - SplashModel? splashModelObj; - - @override - List get props => [ - splashModelObj, - ]; - SplashState copyWith({SplashModel? splashModelObj}) { - return SplashState( - splashModelObj: splashModelObj ?? this.splashModelObj, - ); - } -} diff --git a/lib/presentation/registration/splash_screen/models/splash_model.dart b/lib/presentation/registration/splash_screen/models/splash_model.dart deleted file mode 100644 index 6ad8f8f1..00000000 --- a/lib/presentation/registration/splash_screen/models/splash_model.dart +++ /dev/null @@ -1,16 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; - -/// This class defines the variables used in the [splash_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class SplashModel extends Equatable { - SplashModel(); - - SplashModel copyWith() { - return SplashModel(); - } - - @override - List get props => []; -} diff --git a/lib/presentation/registration/splash_screen/splash_screen.dart b/lib/presentation/registration/splash_screen/splash_screen.dart deleted file mode 100644 index f8355f03..00000000 --- a/lib/presentation/registration/splash_screen/splash_screen.dart +++ /dev/null @@ -1,36 +0,0 @@ -import 'bloc/splash_bloc.dart'; -import 'models/splash_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:flutter/material.dart'; - -class SplashScreen extends StatelessWidget { - const SplashScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context) { - return BlocProvider( - create: (context) => - SplashBloc(SplashState(splashModelObj: SplashModel())) - ..add(SplashInitialEvent()), - child: SplashScreen(),); - } - - @override - Widget build(BuildContext context) { - mediaQueryData = MediaQuery.of(context); - return BlocBuilder(builder: (context, state) { - return SafeArea( - child: Scaffold( - body: SizedBox( - width: double.maxFinite, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - SizedBox(height: 16.v), - CustomImageView( - imagePath: ImageConstant.img2456927096976, - height: 137.adaptSize, - width: 137.adaptSize,), - ],),),),); - },); - } -} diff --git a/lib/presentation/registration/weight_screen/bloc/weight_bloc.dart b/lib/presentation/registration/weight_screen/bloc/weight_bloc.dart deleted file mode 100644 index f03c8c3b..00000000 --- a/lib/presentation/registration/weight_screen/bloc/weight_bloc.dart +++ /dev/null @@ -1,22 +0,0 @@ -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/registration/weight_screen/models/weight_model.dart'; -part 'weight_event.dart'; -part 'weight_state.dart'; - -/// A bloc that manages the state of a Weight according to the event that is dispatched to it. -class WeightBloc extends Bloc { - WeightBloc(WeightState initialState) : super(initialState) { - on(_onInitialize); - } - - _onInitialize( - WeightInitialEvent event, - Emitter emit, - ) async { - emit(state.copyWith( - weightModelObj: state.weightModelObj?.copyWith(), - weightController: state.weightController,),); - } -} diff --git a/lib/presentation/registration/weight_screen/bloc/weight_event.dart b/lib/presentation/registration/weight_screen/bloc/weight_event.dart deleted file mode 100644 index 1b554c5e..00000000 --- a/lib/presentation/registration/weight_screen/bloc/weight_event.dart +++ /dev/null @@ -1,16 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'weight_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///Weight widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class WeightEvent extends Equatable {} - -/// Event that is dispatched when the Weight widget is first created. -class WeightInitialEvent extends WeightEvent { - @override - List get props => []; -} diff --git a/lib/presentation/registration/weight_screen/bloc/weight_state.dart b/lib/presentation/registration/weight_screen/bloc/weight_state.dart deleted file mode 100644 index 5d782dfd..00000000 --- a/lib/presentation/registration/weight_screen/bloc/weight_state.dart +++ /dev/null @@ -1,30 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'weight_bloc.dart'; - -/// Represents the state of Weight in the application. -class WeightState extends Equatable { - WeightState({ - this.weightController, - this.weightModelObj, - }); - - TextEditingController? weightController; - - WeightModel? weightModelObj; - - @override - List get props => [ - weightController, - weightModelObj, - ]; - WeightState copyWith({ - TextEditingController? weightController, - WeightModel? weightModelObj, - }) { - return WeightState( - weightController: weightController ?? this.weightController, - weightModelObj: weightModelObj ?? this.weightModelObj, - ); - } -} diff --git a/lib/presentation/registration/weight_screen/models/weight_model.dart b/lib/presentation/registration/weight_screen/models/weight_model.dart deleted file mode 100644 index d5edd078..00000000 --- a/lib/presentation/registration/weight_screen/models/weight_model.dart +++ /dev/null @@ -1,25 +0,0 @@ -// ignore_for_file: must_be_immutable - -import 'package:equatable/equatable.dart'; -import 'package:eatvio_app/data/models/selectionPopupModel/selection_popup_model.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; - -/// This class defines the variables used in the [weight_screen], -/// and is typically used to hold data that is passed between different parts of the application. -class WeightModel extends Equatable { - UserRegistrationSheet userRegistrationSheet; - WeightModel( - {this.dropdownItemList = const [], required this.userRegistrationSheet,}); - - List dropdownItemList; - - WeightModel copyWith({List? dropdownItemList}) { - return WeightModel( - userRegistrationSheet: userRegistrationSheet, - dropdownItemList: dropdownItemList ?? this.dropdownItemList, - ); - } - - @override - List get props => [dropdownItemList, userRegistrationSheet]; -} diff --git a/lib/presentation/registration/weight_screen/weight_screen.dart b/lib/presentation/registration/weight_screen/weight_screen.dart deleted file mode 100644 index 5d47e8d1..00000000 --- a/lib/presentation/registration/weight_screen/weight_screen.dart +++ /dev/null @@ -1,134 +0,0 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/weight_bloc.dart'; -import 'models/weight_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:flutter/services.dart'; -import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; - -class WeightScreen extends StatelessWidget { - const WeightScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => WeightBloc(WeightState(weightModelObj: WeightModel(userRegistrationSheet: sheet)))..add(WeightInitialEvent()), - child: WeightScreen(),); - } - - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: _buildAppBar(context), - body: Container( - width: double.maxFinite, - padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), - child: Column( - children: [ - SizedBox(height: 7.v), - Container( - height: 16.v, - width: 343.h, - decoration: BoxDecoration( - color: theme.colorScheme.onPrimary, - borderRadius: BorderRadius.circular(8.h), - border: Border.all( - color: theme.colorScheme.primary, - width: 1.h, - ), - ), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: 0.55, - backgroundColor: theme.colorScheme.onPrimary, - valueColor: AlwaysStoppedAnimation( - appTheme.blueA400, - ), - ), - ), - ), - SizedBox(height: 39.v), - Column( - children: [ - Text( - "weight_measurements".tr, - style: theme.textTheme.headlineSmall, - ), - SizedBox(height: 174.v), - Column( - children: [ - Text( - "your_weight".tr, - style: theme.textTheme.bodyLarge, - ), - SizedBox(height: 4.v), - BlocBuilder(builder: (context, state) { - return CustomTextFormField( - width: 150.h, - textInputAction: TextInputAction.done, - controller: state.weightController, - keyboardType: TextInputType.number, - inputFormatters: [ - FilteringTextInputFormatter.digitsOnly, - ], - ); - },), - ], - ), - ], - ), - Spacer(), - BlocBuilder( - builder: (context, state) { - return NextStepButton( - text: "continue".tr.toUpperCase(), - margin: EdgeInsets.only( - left: 16.h, - right: 16.h, - bottom: 50.v, - ), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapNext(state, context), - ); - }, - ), - ], - ), - ), - ); - } - - onTapNext(WeightState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.weightModelObj!.userRegistrationSheet; - GoRouter.of(context).goNamed('heightScreen', extra: sheet); - }; - } - - /// Section Widget - _buildAppBar(BuildContext context) { - return CustomAppBar( - leadingWidth: 29.h, - leading: - AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), - centerTitle: true, - title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); - } - - Function onTapBack(BuildContext context) { - return () { - onTapArrowLeft(context); - }; - } - - /// Navigates to the previous screen. - onTapArrowLeft(BuildContext context) { - GoRouter.of(context).pop(); - } -} diff --git a/lib/presentation/users/subscribers_screen/bloc/subscribers_bloc.dart b/lib/presentation/users/subscribers_screen/bloc/subscribers_bloc.dart index 1bb1bcf6..a48d6198 100644 --- a/lib/presentation/users/subscribers_screen/bloc/subscribers_bloc.dart +++ b/lib/presentation/users/subscribers_screen/bloc/subscribers_bloc.dart @@ -1,16 +1,16 @@ //import 'package:eatvio_app/presentation/auth/auth_screen/auth_screen.dart'; import 'dart:async'; +import 'dart:convert'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/presentation/users/subscribers_screen/models/subscribers_model.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/users/subscribers_screen/models/subscribers_model.dart'; -import 'package:http/http.dart' as http; -import 'dart:convert'; -import 'package:hive/hive.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:go_router/go_router.dart'; +import 'package:hive/hive.dart'; +import 'package:http/http.dart' as http; + +import '/core/app_export.dart'; part 'subscribers_event.dart'; part 'subscribers_state.dart'; @@ -32,7 +32,7 @@ class SubscribersBloc extends Bloc { AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); } final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/profile/subscribers'), + Uri.parse(baseUrl + '/api/profile/subscribers'), headers: { 'Authorization': 'Bearer $token', }, diff --git a/lib/presentation/users/subscribers_screen/bloc/subscribers_state.dart b/lib/presentation/users/subscribers_screen/bloc/subscribers_state.dart index 151e0625..f934270d 100644 --- a/lib/presentation/users/subscribers_screen/bloc/subscribers_state.dart +++ b/lib/presentation/users/subscribers_screen/bloc/subscribers_state.dart @@ -12,14 +12,12 @@ class SubscribersState extends Equatable { } class SubscribersInitialState extends SubscribersState { - SubscribersInitialState({required SubscribersModel myProfileModelObj}) - : super(myProfileModelObj: myProfileModelObj); + SubscribersInitialState({required SubscribersModel myProfileModelObj}) : super(myProfileModelObj: myProfileModelObj); } /// Represents the state of Subscribers in the application. class SubscribersLoadedState extends SubscribersState { - SubscribersLoadedState({this.myProfileModelObj, this.subscribers}) - : super(myProfileModelObj: null); + SubscribersLoadedState({this.myProfileModelObj, this.subscribers}) : super(myProfileModelObj: null); SubscribersModel? myProfileModelObj; dynamic subscribers; diff --git a/lib/presentation/users/subscribers_screen/subscribers_screen.dart b/lib/presentation/users/subscribers_screen/subscribers_screen.dart index f2ac7e15..01fb9a7f 100644 --- a/lib/presentation/users/subscribers_screen/subscribers_screen.dart +++ b/lib/presentation/users/subscribers_screen/subscribers_screen.dart @@ -1,23 +1,20 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/presentation/feed/feed_screen/widgets/feed_search_view.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; +import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart'; +import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; +import 'package:eatvio_app/widgets/custom_outlined_button.dart'; +import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'bloc/subscribers_bloc.dart'; import 'models/subscribers_model.dart'; -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/presentation/feed/feed_screen/widgets/feed_search_view.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart'; -import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart'; -import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart'; -import 'package:eatvio_app/widgets/custom_outlined_button.dart'; -import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:flutter/material.dart'; class SubscribersScreen extends StatelessWidget { static Widget builder(BuildContext context) { return BlocProvider( - create: (context) => SubscribersBloc( - SubscribersState(myProfileModelObj: SubscribersModel())) - ..add(SubscribersInitialEvent()), + create: (context) => SubscribersBloc(SubscribersState(myProfileModelObj: SubscribersModel()))..add(SubscribersInitialEvent()), child: SubscribersScreen()); } @@ -73,8 +70,7 @@ class SubscribersScreen extends StatelessWidget { leadingWidth: 28.h, leading: AppbarLeadingImage( imagePath: ImageConstant.imgArrowLeft, - margin: - EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), + margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: () => GoRouter.of(context).pop(), ), title: Padding( @@ -83,14 +79,12 @@ class SubscribersScreen extends StatelessWidget { children: [ AppbarSubtitle( text: "Мои подписчики", - margin: EdgeInsets.only( - left: 80.h, top: 12.v, bottom: 9.v), + margin: EdgeInsets.only(left: 80.h, top: 12.v, bottom: 9.v), ), Spacer(), Padding( padding: const EdgeInsets.only(right: 20.0), - child: GestureDetector( - child: Icon(Icons.create_outlined)), + child: GestureDetector(child: Icon(Icons.create_outlined)), ) ], ), @@ -145,8 +139,7 @@ class SubscribersScreen extends StatelessWidget { flex: 1, child: CustomOutlinedButton( text: "+", - onPressed: () => - GoRouter.of(context).goNamed('blogPostCreateScreen'), + onPressed: () => GoRouter.of(context).goNamed('blogPostCreateScreen'), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, ), ), @@ -190,7 +183,7 @@ class SubscribersScreen extends StatelessWidget { ), child: ListTile( leading: CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + subscriber['image'], + imageUrl: baseUrl + '/storage/' + subscriber['image'], imageBuilder: (context, imageProvider) => CircleAvatar( backgroundImage: imageProvider, radius: 25, diff --git a/lib/theme/app_decoration.dart b/lib/theme/app_decoration.dart index f304e54d..9ba1b22f 100644 --- a/lib/theme/app_decoration.dart +++ b/lib/theme/app_decoration.dart @@ -1,5 +1,5 @@ -import 'package:flutter/material.dart'; import 'package:eatvio_app/core/app_export.dart'; +import 'package:flutter/material.dart'; class AppDecoration { // Fill decorations diff --git a/lib/theme/bloc/theme_bloc.dart b/lib/theme/bloc/theme_bloc.dart index 60f947d2..ae2863bd 100644 --- a/lib/theme/bloc/theme_bloc.dart +++ b/lib/theme/bloc/theme_bloc.dart @@ -1,6 +1,8 @@ import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; + import '../../core/app_export.dart'; + part 'theme_event.dart'; part 'theme_state.dart'; diff --git a/lib/theme/custom_text_style.dart b/lib/theme/custom_text_style.dart index de3bee78..1ed606cd 100644 --- a/lib/theme/custom_text_style.dart +++ b/lib/theme/custom_text_style.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; + import '../core/app_export.dart'; /// A collection of pre-defined text styles for customizing text appearance, diff --git a/lib/theme/theme_helper.dart b/lib/theme/theme_helper.dart index c912cb29..e202a868 100644 --- a/lib/theme/theme_helper.dart +++ b/lib/theme/theme_helper.dart @@ -1,5 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:google_fonts/google_fonts.dart'; + import '../../core/app_export.dart'; /// Helper class for managing themes and colors. @@ -22,7 +24,8 @@ class ThemeHelper { //throw exception to notify given theme is not found or not generated by the generator if (!_supportedCustomColor.containsKey(_appTheme)) { throw Exception( - "$_appTheme is not found.Make sure you have added this theme class in JSON Try running flutter pub run build_runner",); + "$_appTheme is not found.Make sure you have added this theme class in JSON Try running flutter pub run build_runner", + ); } //return theme from map @@ -34,13 +37,50 @@ class ThemeHelper { //throw exception to notify given theme is not found or not generated by the generator if (!_supportedColorScheme.containsKey(_appTheme)) { throw Exception( - "$_appTheme is not found.Make sure you have added this theme class in JSON Try running flutter pub run build_runner",); + "$_appTheme is not found.Make sure you have added this theme class in JSON Try running flutter pub run build_runner", + ); } //return theme from map - var colorScheme = - _supportedColorScheme[_appTheme] ?? ColorSchemes.primaryColorScheme; + var colorScheme = _supportedColorScheme[_appTheme] ?? ColorSchemes.primaryColorScheme; return ThemeData( + textTheme: GoogleFonts.mulishTextTheme().copyWith( + bodyLarge: TextStyle( + color: appTheme.blueGray400, + fontSize: 18, + fontWeight: FontWeight.w400, + ), + headlineSmall: TextStyle( + color: colorScheme.primary, + fontWeight: FontWeight.w600, + fontSize: 24, + ), + titleMedium: TextStyle( + color: colorScheme.primary, + fontWeight: FontWeight.w700, + fontSize: 18, + ), + titleSmall: TextStyle( + color: colorScheme.onPrimary, + fontWeight: FontWeight.w700, + fontSize: 15, + ), + bodyMedium: TextStyle( + color: appTheme.blueGray400, + fontWeight: FontWeight.w400, + fontSize: 14, + ), + bodySmall: TextStyle( + color: appTheme.gray500, + fontWeight: FontWeight.w400, + fontSize: 10, + ), + labelLarge: TextStyle( + color: appTheme.blueGray800, + fontWeight: FontWeight.w600, + fontSize: 12, + ), + ), pageTransitionsTheme: PageTransitionsTheme( builders: { TargetPlatform.android: CupertinoPageTransitionsBuilder(), @@ -49,7 +89,6 @@ class ThemeHelper { ), visualDensity: VisualDensity.standard, colorScheme: colorScheme, - textTheme: TextThemes.textTheme(colorScheme), scaffoldBackgroundColor: colorScheme.onPrimary, appBarTheme: AppBarTheme( systemOverlayStyle: SystemUiOverlayStyle( @@ -85,54 +124,6 @@ class ThemeHelper { ThemeData themeData() => _getThemeData(); } -/// Class containing the supported text theme styles. -class TextThemes { - static TextTheme textTheme(ColorScheme colorScheme) => TextTheme( - bodyLarge: TextStyle( - color: appTheme.blueGray400, - fontSize: 18.fSize, - fontFamily: 'Mulish', - fontWeight: FontWeight.w400, - ), - headlineSmall: TextStyle( - color: colorScheme.primary, - fontSize: 24.fSize, - fontFamily: 'Segoe UI', - fontWeight: FontWeight.w600, - ), - titleMedium: TextStyle( - color: colorScheme.primary, - fontSize: 18.fSize, - fontFamily: 'Mulish', - fontWeight: FontWeight.w700, - ), - titleSmall: TextStyle( - color: colorScheme.onPrimary, - fontSize: 15.fSize, - fontFamily: 'Mulish', - fontWeight: FontWeight.w700, - ), - bodyMedium: TextStyle( - color: appTheme.blueGray400, - fontSize: 14.fSize, - fontFamily: 'Mulish', - fontWeight: FontWeight.w400, - ), - bodySmall: TextStyle( - color: appTheme.gray500, - fontSize: 10.fSize, - fontFamily: 'Mulish', - fontWeight: FontWeight.w400, - ), - labelLarge: TextStyle( - color: appTheme.blueGray800, - fontSize: 12.fSize, - fontFamily: 'Mulish', - fontWeight: FontWeight.w600, - ), - ); -} - /// Class containing the supported color schemes. class ColorSchemes { static final primaryColorScheme = ColorScheme.light( @@ -149,10 +140,12 @@ class ColorSchemes { class PrimaryColors { // Blue Color get blue400 => Color(0XFF43A6F2); + Color get blueA400 => Color(0XFF2F80ED); // BlueGray Color get blueGray400 => Color(0XFF7B8794); + Color get black900 => Color(0XFF000000); // Blue @@ -160,7 +153,9 @@ class PrimaryColors { // BlueGray Color get blueGray300 => Color(0XFF9AA5B1); + Color get blueGray800 => Color(0XFF323F4B); + Color get blueGray900 => Color(0XFF2A2F4C); // DeepOrange @@ -168,22 +163,33 @@ class PrimaryColors { // Gray Color get gray100 => Color(0XFFF0F2F5); + Color get gray200 => Color(0XFFF0F0F0); + Color get gray400 => Color(0XFFC1C1C1); + Color get gray40001 => Color(0XFFC8C8C8); + Color get gray50 => Color(0XFFF6FAFF); + Color get gray500 => Color(0XFFA3A3A3); + Color get gray600 => Color(0XFF6D6D6D); + Color get gray60001 => Color(0XFF848484); + Color get gray60002 => Color(0XFF757575); + Color get gray60003 => Color(0XFF707070); // Green Color get greenA700 => Color(0XFF019A3E); + Color get greenA70001 => Color(0XFF00BE13); // LightGreen Color get lightGreen300 => Color(0XFFB2DF8A); + Color get lightGreenA700 => Color(0XFF18FF14); // Red @@ -191,6 +197,7 @@ class PrimaryColors { // Teal Color get teal100 => Color(0XFFA6CEE3); + Color get teal900 => Color(0XFF0B3F56); // White @@ -200,4 +207,5 @@ class PrimaryColors { } PrimaryColors get appTheme => ThemeHelper().themeColor(); + ThemeData get theme => ThemeHelper().themeData(); diff --git a/lib/widgets/app_bar/appbar_title_image.dart b/lib/widgets/app_bar/appbar_title_image.dart index 4ef20de2..429ab4d8 100644 --- a/lib/widgets/app_bar/appbar_title_image.dart +++ b/lib/widgets/app_bar/appbar_title_image.dart @@ -3,37 +3,16 @@ import 'package:flutter/material.dart'; // ignore: must_be_immutable class AppbarTitleImage extends StatelessWidget { - AppbarTitleImage({ - Key? key, - this.imagePath, - this.margin, - this.onTap, - }) : super( - key: key, - ); + const AppbarTitleImage({required this.imagePath, super.key}); - String? imagePath; - - EdgeInsetsGeometry? margin; - - Function? onTap; + final String? imagePath; @override Widget build(BuildContext context) { - return InkWell( - onTap: onTapCall, - child: Padding( - padding: margin ?? EdgeInsets.zero, - child: CustomImageView( - imagePath: imagePath, - height: 50.adaptSize, - width: 50.adaptSize, - fit: BoxFit.contain, - ), - ), + return CustomImageView( + imagePath: imagePath, + height: 48, + fit: BoxFit.contain, ); } - - void onTapCall() { - } } diff --git a/lib/widgets/chart_axis.dart b/lib/widgets/chart_axis.dart index 5cc64480..f137c6d3 100644 --- a/lib/widgets/chart_axis.dart +++ b/lib/widgets/chart_axis.dart @@ -142,4 +142,4 @@ buildChart( ), ); } -*/ \ No newline at end of file +*/ diff --git a/lib/widgets/chart_bars.dart b/lib/widgets/chart_bars.dart index 7f4fc342..eac9e99c 100644 --- a/lib/widgets/chart_bars.dart +++ b/lib/widgets/chart_bars.dart @@ -76,4 +76,4 @@ class MyApp extends StatelessWidget { ); } } -*/ \ No newline at end of file +*/ diff --git a/lib/widgets/custom_about_list.dart b/lib/widgets/custom_about_list.dart index 4b4e709f..90b1d3d0 100644 --- a/lib/widgets/custom_about_list.dart +++ b/lib/widgets/custom_about_list.dart @@ -26,9 +26,10 @@ class _AboutListState extends State { Text( widget.title, style: TextStyle( - color: Colors.black, - fontSize: 14, - fontWeight: FontWeight.bold,), + color: Colors.black, + fontSize: 14, + fontWeight: FontWeight.bold, + ), ), Icon(isExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), ], @@ -38,8 +39,9 @@ class _AboutListState extends State { Padding( padding: const EdgeInsets.only(left: 16.0), child: Column( - //children: widget.items.map((item) => Text(item)).toList(), - children: [Text(widget.items.join('\n'))],), + //children: widget.items.map((item) => Text(item)).toList(), + children: [Text(widget.items.join('\n'))], + ), ), Divider(), ], diff --git a/lib/widgets/custom_drop_down.dart b/lib/widgets/custom_drop_down.dart index 759efc1a..ff80bac9 100644 --- a/lib/widgets/custom_drop_down.dart +++ b/lib/widgets/custom_drop_down.dart @@ -23,7 +23,7 @@ class CustomDropDown extends StatelessWidget { this.filled = true, this.validator, this.onChanged, - this.defaultValue, + this.value, }) : super( key: key, ); @@ -62,7 +62,7 @@ class CustomDropDown extends StatelessWidget { final bool? filled; - final SelectionPopupModel? defaultValue; + final SelectionPopupModel? value; final FormFieldValidator? validator; @@ -85,6 +85,7 @@ class CustomDropDown extends StatelessWidget { focusNode: focusNode ?? FocusNode(), icon: icon, autofocus: autofocus!, + value: value, isExpanded: true, style: textStyle ?? Theme.of(context).textTheme.titleMedium, items: items?.map((SelectionPopupModel item) { @@ -92,7 +93,6 @@ class CustomDropDown extends StatelessWidget { value: item, child: Text( item.title, - overflow: TextOverflow.fade, style: hintStyle ?? Theme.of(context).textTheme.titleMedium, ), ); diff --git a/lib/widgets/custom_expandable_list.dart b/lib/widgets/custom_expandable_list.dart index 79d62d1b..a98dd33d 100644 --- a/lib/widgets/custom_expandable_list.dart +++ b/lib/widgets/custom_expandable_list.dart @@ -1,16 +1,16 @@ -import 'package:flutter/material.dart'; +import 'dart:convert'; + import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart'; import 'package:eatvio_app/widgets/custom_hyper_switch.dart'; import 'package:eatvio_app/widgets/custom_hypo_switch.dart'; -import 'package:go_router/go_router.dart'; -import 'package:intl/intl.dart'; import 'package:eatvio_app/widgets/next_step_button.dart'; -import 'dart:convert'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:hive/hive.dart'; +import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:go_router/go_router.dart'; +import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; +import 'package:intl/intl.dart'; class ExpandableList extends StatefulWidget { final String title; @@ -37,9 +37,10 @@ class _ExpandableListState extends State { Text( widget.title, style: TextStyle( - color: Colors.black, - fontSize: 14, - fontWeight: FontWeight.bold,), + color: Colors.black, + fontSize: 14, + fontWeight: FontWeight.bold, + ), ), Icon(isExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), ], @@ -49,24 +50,25 @@ class _ExpandableListState extends State { Padding( padding: const EdgeInsets.only(left: 16.0), child: BlocBuilder( - builder: (context, state) { - if (state is MyProfileInitialState) { - // Это начальное состояние, данные ещё не загружены. - return CircularProgressIndicator( - color: Colors.white, - backgroundColor: Colors.white, - ); - } else if (state is MyProfileLoadedState) { - // Данные загружены, можно строить форму. - return _buildForm(context, state); - } else if (state is MyProfileErrorState) { - // Произошла ошибка при загрузке данных. - return Center(child: Text(state.errorMessage)); - } else { - // Другие состояния, если они есть. - return Container(); // Пустой контейнер для необработанных состояний. - } - },), + builder: (context, state) { + if (state is MyProfileInitialState) { + // Это начальное состояние, данные ещё не загружены. + return CircularProgressIndicator( + color: Colors.white, + backgroundColor: Colors.white, + ); + } else if (state is MyProfileLoadedState) { + // Данные загружены, можно строить форму. + return _buildForm(context, state); + } else if (state is MyProfileErrorState) { + // Произошла ошибка при загрузке данных. + return Center(child: Text(state.errorMessage)); + } else { + // Другие состояния, если они есть. + return Container(); // Пустой контейнер для необработанных состояний. + } + }, + ), ), Divider(), ], @@ -125,142 +127,152 @@ class _ExpandableListState extends State { 'экстремальный (несколько интенсивных тренировок в день)', ]; final digitsOnly = FilteringTextInputFormatter.digitsOnly; - return Column(children: [ - TextField( - controller: state.firstNameFormController, - decoration: InputDecoration(labelText: 'first_name'.tr), - ), - TextField( - controller: state.lastNameFormController, - decoration: InputDecoration(labelText: 'last_name'.tr), - ), - TextField( + return Column( + children: [ + TextField( + controller: state.firstNameFormController, + decoration: InputDecoration(labelText: 'first_name'.tr), + ), + TextField( + controller: state.lastNameFormController, + decoration: InputDecoration(labelText: 'last_name'.tr), + ), + TextField( decoration: InputDecoration(labelText: 'date_of_birth'.tr), controller: state.dateFormController, - onTap: inputTime(context, state),), - DropdownButtonFormField( - value: state.selectedCountry, - hint: Text(state.selectedCountry ?? "Не выбрано"), - onChanged: setCountry(state), - items: countries.map>((String value) { - return DropdownMenuItem( - value: value, - child: Text(value), - ); - }).toList(), - decoration: InputDecoration(labelText: 'country'.tr), - ), - DropdownButtonFormField( - hint: Text(state.selectedCity ?? "Не выбрано"), - value: state.selectedCity, - onChanged: setCity(state), - items: cities.map>((String value) { - return DropdownMenuItem( - value: value, - child: Text(value), - ); - }).toList(), - decoration: InputDecoration(labelText: 'city_of_living'.tr), - ), - TextField( + onTap: inputTime(context, state), + ), + DropdownButtonFormField( + value: state.selectedCountry, + hint: Text(state.selectedCountry ?? "Не выбрано"), + onChanged: setCountry(state), + items: countries.map>((String value) { + return DropdownMenuItem( + value: value, + child: Text(value), + ); + }).toList(), + decoration: InputDecoration(labelText: 'country'.tr), + ), + DropdownButtonFormField( + hint: Text(state.selectedCity ?? "Не выбрано"), + value: state.selectedCity, + onChanged: setCity(state), + items: cities.map>((String value) { + return DropdownMenuItem( + value: value, + child: Text(value), + ); + }).toList(), + decoration: InputDecoration(labelText: 'city_of_living'.tr), + ), + TextField( controller: state.weightFormController, decoration: InputDecoration(labelText: 'weight_measurements'.tr), keyboardType: TextInputType.number, - inputFormatters: [digitsOnly],), - TextField( + inputFormatters: [digitsOnly], + ), + TextField( controller: state.heightFormController, decoration: InputDecoration(labelText: 'height_measurements'.tr), keyboardType: TextInputType.number, - inputFormatters: [digitsOnly],), - TextField( + inputFormatters: [digitsOnly], + ), + TextField( controller: state.chestCircumferenceFormController, decoration: InputDecoration(labelText: 'chest_circumference'.tr), keyboardType: TextInputType.number, - inputFormatters: [digitsOnly],), - TextField( + inputFormatters: [digitsOnly], + ), + TextField( controller: state.waistCircumferenceFormController, decoration: InputDecoration(labelText: 'waist_circumference'.tr), keyboardType: TextInputType.number, - inputFormatters: [digitsOnly],), - TextField( + inputFormatters: [digitsOnly], + ), + TextField( controller: state.hipCircumferenceFormController, decoration: InputDecoration(labelText: 'hip_circumference'.tr), keyboardType: TextInputType.number, - inputFormatters: [digitsOnly],), - TextField( + inputFormatters: [digitsOnly], + ), + TextField( controller: state.upPressureFormController, decoration: InputDecoration(labelText: 'up_pressure'.tr), keyboardType: TextInputType.number, - inputFormatters: [digitsOnly],), - TextField( + inputFormatters: [digitsOnly], + ), + TextField( controller: state.downPressureFormController, decoration: InputDecoration(labelText: 'down_pressure'.tr), keyboardType: TextInputType.number, - inputFormatters: [digitsOnly],), - TextField( - controller: state.allergiesFormController, - decoration: InputDecoration(labelText: 'allergies_presence'.tr), - maxLines: null, - ), - TextField( - controller: state.pillsFormController, - decoration: InputDecoration(labelText: 'do_you_take_pills'.tr), - maxLines: null, - ), - TextField( - controller: state.sportsFormController, - decoration: InputDecoration(labelText: 'your_favorite_sports'.tr), - maxLines: null, - ), - TextField( - controller: state.favoriteFormController, - decoration: InputDecoration(labelText: 'favorite_foods'.tr), - maxLines: null, - ), - TextField( - controller: state.unfavoriteFormController, - decoration: InputDecoration(labelText: 'unfavorite_foods'.tr), - maxLines: null, - ), - TextField( - controller: state.additionalFormController, - decoration: InputDecoration(labelText: 'additional_information'.tr), - maxLines: null, - ), - DropdownButtonFormField( - hint: Text(state.selectedActivity ?? "Не выбрано"), - value: state.selectedActivity, - onChanged: setActivity(state), - items: activities.map>((String value) { - return DropdownMenuItem( - value: value, - child: SizedBox( - // Используем SizedBox для ограничения ширины элемента списка - width: MediaQuery.of(context).size.width * - 0.8, // Устанавливаем желаемую ширину элемента списка - child: Text(value), - ), - ); - }).toList(), - isExpanded: true, // Расширяем список на всю доступную ширину - decoration: InputDecoration(labelText: 'Активность'), - ), - Row( - children: [ - HypoSwitch('do_you_have_hypotension_tendency'.tr, state), - ], - ), - Row( - children: [ - HyperSwitch('do_you_have_hypertension_tendency'.tr, state), - ], - ), - NextStepButton( + inputFormatters: [digitsOnly], + ), + TextField( + controller: state.allergiesFormController, + decoration: InputDecoration(labelText: 'allergies_presence'.tr), + maxLines: null, + ), + TextField( + controller: state.pillsFormController, + decoration: InputDecoration(labelText: 'do_you_take_pills'.tr), + maxLines: null, + ), + TextField( + controller: state.sportsFormController, + decoration: InputDecoration(labelText: 'your_favorite_sports'.tr), + maxLines: null, + ), + TextField( + controller: state.favoriteFormController, + decoration: InputDecoration(labelText: 'favorite_foods'.tr), + maxLines: null, + ), + TextField( + controller: state.unfavoriteFormController, + decoration: InputDecoration(labelText: 'unfavorite_foods'.tr), + maxLines: null, + ), + TextField( + controller: state.additionalFormController, + decoration: InputDecoration(labelText: 'additional_information'.tr), + maxLines: null, + ), + DropdownButtonFormField( + hint: Text(state.selectedActivity ?? "Не выбрано"), + value: state.selectedActivity, + onChanged: setActivity(state), + items: activities.map>((String value) { + return DropdownMenuItem( + value: value, + child: SizedBox( + // Используем SizedBox для ограничения ширины элемента списка + width: MediaQuery.of(context).size.width * 0.8, // Устанавливаем желаемую ширину элемента списка + child: Text(value), + ), + ); + }).toList(), + isExpanded: true, // Расширяем список на всю доступную ширину + decoration: InputDecoration(labelText: 'Активность'), + ), + Row( + children: [ + HypoSwitch('do_you_have_hypotension_tendency'.tr, state), + ], + ), + Row( + children: [ + HyperSwitch('do_you_have_hypertension_tendency'.tr, state), + ], + ), + NextStepButton( onPressed: () => sendProfileData(state), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, text: "save".tr.toUpperCase(), - margin: EdgeInsets.only(top: 20.h, bottom: 20.h),), - ],); + margin: EdgeInsets.only(top: 20.h, bottom: 20.h), + ), + ], + ); } sendData(MyProfileLoadedState state) { @@ -300,8 +312,7 @@ class _ExpandableListState extends State { ).then((selectedDate) { if (selectedDate != null) { setState(() { - state.dateFormController!.text = - DateFormat('dd-MM-yyyy').format(selectedDate); + state.dateFormController!.text = DateFormat('dd-MM-yyyy').format(selectedDate); }); } }); @@ -367,8 +378,7 @@ class _ExpandableListState extends State { 'city': state?.selectedCity ?? 'Москва', 'has_hypo': state?.hypoFormController, 'has_hyper': state?.hyperFormController, - 'activity_coefficient': - determineActivityFactor(state?.selectedActivity ?? 'сидячий'), + 'activity_coefficient': determineActivityFactor(state?.selectedActivity ?? 'сидячий'), }; } @@ -378,11 +388,14 @@ class _ExpandableListState extends State { } String _buildApiUrl() { - return dotenv.env['SERVER_ROOT']! + '/profile/update'; + return baseUrl + '/api/profile/update'; } Future _sendHttpRequest( - Map profileData, String apiUrl, String? token,) { + Map profileData, + String apiUrl, + String? token, + ) { return http.post( Uri.parse(apiUrl), body: json.encode(profileData), diff --git a/lib/widgets/custom_hyper_switch.dart b/lib/widgets/custom_hyper_switch.dart index e25c462b..edad8ec6 100644 --- a/lib/widgets/custom_hyper_switch.dart +++ b/lib/widgets/custom_hyper_switch.dart @@ -1,6 +1,6 @@ -import 'package:flutter/material.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart'; +import 'package:flutter/material.dart'; class HyperSwitch extends StatefulWidget { final String title; @@ -30,7 +30,10 @@ class _HyperState extends State { Text( widget.title, style: TextStyle( - color: Colors.black, fontSize: 14, fontWeight: FontWeight.bold,), + color: Colors.black, + fontSize: 14, + fontWeight: FontWeight.bold, + ), ), Switch( value: switchValue, diff --git a/lib/widgets/custom_hypo_switch.dart b/lib/widgets/custom_hypo_switch.dart index 173de64a..2e0c511b 100644 --- a/lib/widgets/custom_hypo_switch.dart +++ b/lib/widgets/custom_hypo_switch.dart @@ -1,6 +1,6 @@ -import 'package:flutter/material.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart'; +import 'package:flutter/material.dart'; class HypoSwitch extends StatefulWidget { final String title; @@ -30,7 +30,10 @@ class _HypoState extends State { Text( widget.title, style: TextStyle( - color: Colors.black, fontSize: 14, fontWeight: FontWeight.bold,), + color: Colors.black, + fontSize: 14, + fontWeight: FontWeight.bold, + ), ), Switch( value: switchValue, diff --git a/lib/widgets/custom_icon_button.dart b/lib/widgets/custom_icon_button.dart index 2937b5a1..d029004a 100644 --- a/lib/widgets/custom_icon_button.dart +++ b/lib/widgets/custom_icon_button.dart @@ -45,7 +45,8 @@ class CustomIconButton extends StatelessWidget { color: Colors.black, borderRadius: const BorderRadius.all(Radius.circular(9)), border: const Border.fromBorderSide( - BorderSide(color: Colors.blueGrey, width: 1),), + BorderSide(color: Colors.blueGrey, width: 1), + ), ), child: child, ), diff --git a/lib/widgets/custom_navigation_menu.dart b/lib/widgets/custom_navigation_menu.dart index 03d11a98..5868bf01 100644 --- a/lib/widgets/custom_navigation_menu.dart +++ b/lib/widgets/custom_navigation_menu.dart @@ -1,9 +1,8 @@ import 'package:eatvio_app/core/app_export.dart'; -import 'package:flutter/material.dart'; import 'package:eatvio_app/widgets/custom_navigation_menu_item.dart'; +import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:hive/hive.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:http/http.dart' as http; class CustomNavigationMenu extends StatelessWidget { @@ -66,7 +65,7 @@ _onTapLogout(BuildContext context) { final box = await Hive.openBox('token'); final token = box.get('token'); final response = await http.post( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/profile/logout'), + Uri.parse(baseUrl + '/api/profile/logout'), headers: { 'Authorization': 'Bearer $token', }, diff --git a/lib/widgets/custom_navigation_menu_item.dart b/lib/widgets/custom_navigation_menu_item.dart index 2ee47a8c..44850fa3 100644 --- a/lib/widgets/custom_navigation_menu_item.dart +++ b/lib/widgets/custom_navigation_menu_item.dart @@ -1,5 +1,6 @@ -import 'package:flutter/material.dart'; +import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/widgets/custom_image_view.dart'; +import 'package:flutter/material.dart'; class MenuItem extends StatelessWidget { final String icon; @@ -20,13 +21,12 @@ class MenuItem extends StatelessWidget { padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: - CrossAxisAlignment.center, // Выравнивание по центру вертикально + crossAxisAlignment: CrossAxisAlignment.center, // Выравнивание по центру вертикально children: [ CustomImageView(imagePath: icon), SizedBox( - width: - 8.0,), // Добавляем небольшой отступ между иконкой и текстом + width: 8.0, + ), // Добавляем небольшой отступ между иконкой и текстом Text(text), ], ), diff --git a/lib/widgets/custom_notification_screen.dart b/lib/widgets/custom_notification_screen.dart index 960293c3..72fd860b 100644 --- a/lib/widgets/custom_notification_screen.dart +++ b/lib/widgets/custom_notification_screen.dart @@ -1,5 +1,5 @@ -import 'package:flutter/material.dart'; import 'package:eatvio_app/core/app_export.dart'; +import 'package:flutter/material.dart'; class NotificationSwitch extends StatefulWidget { final String title; @@ -21,7 +21,10 @@ class _NotificationSwitchState extends State { Text( widget.title, style: TextStyle( - color: Colors.black, fontSize: 14, fontWeight: FontWeight.bold,), + color: Colors.black, + fontSize: 14, + fontWeight: FontWeight.bold, + ), ), Switch( value: switchValue, diff --git a/lib/widgets/custom_text_form_field.dart b/lib/widgets/custom_text_form_field.dart index e70b2b53..862cc104 100644 --- a/lib/widgets/custom_text_form_field.dart +++ b/lib/widgets/custom_text_form_field.dart @@ -62,7 +62,7 @@ class CustomTextFormField extends StatelessWidget { final String? initialValue; final Function(String)? onFieldSubmitted; final void Function(String?)? onSaved; - final void Function(String?)? onChanged; + final void Function(String)? onChanged; @override Widget build(BuildContext context) { @@ -128,6 +128,7 @@ class CustomTextFormField extends StatelessWidget { : SizedBox( width: width ?? double.maxFinite, child: TextFormField( + onChanged: onChanged, controller: controller, focusNode: focusNode ?? null, autofocus: autofocus!, @@ -180,7 +181,7 @@ class CustomTextFormField extends StatelessWidget { ); } } - /* InputDecoration _buildInputDecoration() { +/* InputDecoration _buildInputDecoration() { return InputDecoration( hintText: hintText ?? "", hintStyle: hintStyle ?? theme.textTheme.bodyLarge, diff --git a/pubspec.yaml b/pubspec.yaml index 87ed29e8..2cdbe598 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -27,7 +27,6 @@ dependencies: path_provider: ^2.1.3 fl_chart: ^0.68.0 flutter_spinkit: ^5.2.1 - flutter_dotenv: ^5.1.0 carousel_slider: ^4.2.1 flutter_form_builder: ^9.3.0 image_picker: ^1.1.2 @@ -44,6 +43,7 @@ dependencies: easy_debounce: ^2.0.3 lazy_load_scrollview: ^1.3.0 badges: ^3.1.2 + google_fonts: ^6.2.1 dev_dependencies: build_runner: ^2.4.11 @@ -58,18 +58,4 @@ flutter: uses-material-design: true assets: - assets/ - - assets/images/ - - .env - fonts: - - family: Segoe UI - fonts: - - asset: assets/fonts/SegoeUISemibold.ttf - weight: 600 - - family: Mulish - fonts: - - asset: assets/fonts/MulishBold.ttf - weight: 700 - - asset: assets/fonts/MulishRegular.ttf - weight: 400 - - asset: assets/fonts/MulishSemiBold.ttf - weight: 600 + - assets/images/ \ No newline at end of file diff --git a/test/add_info_test.dart b/test/add_info_test.dart deleted file mode 100644 index 86379dda..00000000 --- a/test/add_info_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/registration/additional_information_screen/additional_information_screen.dart'; -import 'package:eatvio_app/presentation/registration/additional_information_screen/bloc/additional_information_bloc.dart'; -import 'package:eatvio_app/presentation/registration/additional_information_screen/models/additional_information_model.dart'; - -void main() { - group('AdditionalInfoScreen', () { - testWidgets('renders screen in initial state', (WidgetTester tester) async { - final myProfileBloc = AdditionalInformationBloc(AdditionalInformationState( - additionalInformationModelObj: AdditionalInformationModel( - userRegistrationSheet: UserRegistrationSheet( - name: "name", - firstName: "firstName", - lastName: "lastName", - email: "email", - password: "password", - passwordConfirmation: "passwordConfirmation", - termsAccepted: "termsAccepted", - birthdate: "birthdate", - gender: "gender", - country: "country", - city: "city", - lang: "lang", - weight: "weight", - height: "height", - chestCircumference: 'asdasd', - waistCircumference: "waistCircumference", - hipCircumference: "hipCircumference", - bloodPressureUp: "bloodPressureUp", - bloodPressureDown: "bloodPressureDown", - hasHypo: "hasHypo", - hasHyper: "hasHyper", - aboutAllergy: "aboutAllergy", - aboutTakingPils: "aboutTakingPils", - aboutSportHobbies: "aboutSportHobbies", - favoriteFoods: "favoriteFoods", - unfavoriteFoods: "unfavoriteFoods", - additionalInfo: - "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: AdditionalInformationScreen(), - ), - ), - ); - }); - }); -} diff --git a/test/allergies_test.dart b/test/allergies_test.dart deleted file mode 100644 index d0a78328..00000000 --- a/test/allergies_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/registration/allergies_screen/allergies_screen.dart'; -import 'package:eatvio_app/presentation/registration/allergies_screen/bloc/allergies_bloc.dart'; -import 'package:eatvio_app/presentation/registration/allergies_screen/models/allergies_model.dart'; - -void main() { - group('AdditionalInfoScreen', () { - testWidgets('renders screen in initial state', (WidgetTester tester) async { - final myProfileBloc = AllergiesBloc(AllergiesState( - allergiesModelObj: AllergiesModel( - userRegistrationSheet: UserRegistrationSheet( - name: "name", - firstName: "firstName", - lastName: "lastName", - email: "email", - password: "password", - passwordConfirmation: "passwordConfirmation", - termsAccepted: "termsAccepted", - birthdate: "birthdate", - gender: "gender", - country: "country", - city: "city", - lang: "lang", - weight: "weight", - height: "height", - chestCircumference: 'asdasd', - waistCircumference: "waistCircumference", - hipCircumference: "hipCircumference", - bloodPressureUp: "bloodPressureUp", - bloodPressureDown: "bloodPressureDown", - hasHypo: "hasHypo", - hasHyper: "hasHyper", - aboutAllergy: "aboutAllergy", - aboutTakingPils: "aboutTakingPils", - aboutSportHobbies: "aboutSportHobbies", - favoriteFoods: "favoriteFoods", - unfavoriteFoods: "unfavoriteFoods", - additionalInfo: - "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: AllergiesScreen(), - ), - ), - ); - }); - }); -} diff --git a/test/blood_pressure_test.dart b/test/blood_pressure_test.dart deleted file mode 100644 index a8c70dbe..00000000 --- a/test/blood_pressure_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart'; -import 'package:eatvio_app/presentation/registration/blood_pressure_screen/bloc/blood_pressure_bloc.dart'; -import 'package:eatvio_app/presentation/registration/blood_pressure_screen/models/blood_pressure_model.dart'; - -void main() { - group('AdditionalInfoScreen', () { - testWidgets('renders screen in initial state', (WidgetTester tester) async { - final myProfileBloc = BloodPressureBloc(BloodPressureState( - bloodPressureModelObj: BloodPressureModel( - userRegistrationSheet: UserRegistrationSheet( - name: "name", - firstName: "firstName", - lastName: "lastName", - email: "email", - password: "password", - passwordConfirmation: "passwordConfirmation", - termsAccepted: "termsAccepted", - birthdate: "birthdate", - gender: "gender", - country: "country", - city: "city", - lang: "lang", - weight: "weight", - height: "height", - chestCircumference: 'asdasd', - waistCircumference: "waistCircumference", - hipCircumference: "hipCircumference", - bloodPressureUp: "bloodPressureUp", - bloodPressureDown: "bloodPressureDown", - hasHypo: "hasHypo", - hasHyper: "hasHyper", - aboutAllergy: "aboutAllergy", - aboutTakingPils: "aboutTakingPils", - aboutSportHobbies: "aboutSportHobbies", - favoriteFoods: "favoriteFoods", - unfavoriteFoods: "unfavoriteFoods", - additionalInfo: - "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: BloodPressureScreen(), - ), - ), - ); - }); - }); -} diff --git a/test/body_circumferences_test.dart b/test/body_circumferences_test.dart deleted file mode 100644 index 339c3b8b..00000000 --- a/test/body_circumferences_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart'; -import 'package:eatvio_app/presentation/registration/body_circumferences_screen/bloc/body_circumferences_bloc.dart'; -import 'package:eatvio_app/presentation/registration/body_circumferences_screen/models/body_circumferences_model.dart'; - -void main() { - group('AdditionalInfoScreen', () { - testWidgets('renders screen in initial state', (WidgetTester tester) async { - final myProfileBloc = BodyCircumferencesBloc(BodyCircumferencesState( - bodyCircumferencesModelObj: BodyCircumferencesModel( - userRegistrationSheet: UserRegistrationSheet( - name: "name", - firstName: "firstName", - lastName: "lastName", - email: "email", - password: "password", - passwordConfirmation: "passwordConfirmation", - termsAccepted: "termsAccepted", - birthdate: "birthdate", - gender: "gender", - country: "country", - city: "city", - lang: "lang", - weight: "weight", - height: "height", - chestCircumference: 'asdasd', - waistCircumference: "waistCircumference", - hipCircumference: "hipCircumference", - bloodPressureUp: "bloodPressureUp", - bloodPressureDown: "bloodPressureDown", - hasHypo: "hasHypo", - hasHyper: "hasHyper", - aboutAllergy: "aboutAllergy", - aboutTakingPils: "aboutTakingPils", - aboutSportHobbies: "aboutSportHobbies", - favoriteFoods: "favoriteFoods", - unfavoriteFoods: "unfavoriteFoods", - additionalInfo: - "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: BodyCircumferencesScreen(), - ), - ), - ); - }); - }); -} diff --git a/test/city_of_living_test.dart b/test/city_of_living_test.dart deleted file mode 100644 index 1a6c18ba..00000000 --- a/test/city_of_living_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/registration/city_of_living_screen/city_of_living_screen.dart'; -import 'package:eatvio_app/presentation/registration/city_of_living_screen/bloc/city_of_living_bloc.dart'; -import 'package:eatvio_app/presentation/registration/city_of_living_screen/models/city_of_living_model.dart'; - -void main() { - group('AdditionalInfoScreen', () { - testWidgets('renders screen in initial state', (WidgetTester tester) async { - final myProfileBloc = CityOfLivingBloc(CityOfLivingState( - cityOfLivingModelObj: CityOfLivingModel( - userRegistrationSheet: UserRegistrationSheet( - name: "name", - firstName: "firstName", - lastName: "lastName", - email: "email", - password: "password", - passwordConfirmation: "passwordConfirmation", - termsAccepted: "termsAccepted", - birthdate: "birthdate", - gender: "gender", - country: "country", - city: "city", - lang: "lang", - weight: "weight", - height: "height", - chestCircumference: 'asdasd', - waistCircumference: "waistCircumference", - hipCircumference: "hipCircumference", - bloodPressureUp: "bloodPressureUp", - bloodPressureDown: "bloodPressureDown", - hasHypo: "hasHypo", - hasHyper: "hasHyper", - aboutAllergy: "aboutAllergy", - aboutTakingPils: "aboutTakingPils", - aboutSportHobbies: "aboutSportHobbies", - favoriteFoods: "favoriteFoods", - unfavoriteFoods: "unfavoriteFoods", - additionalInfo: - "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: CityOfLivingScreen(), - ), - ), - ); - }); - }); -} diff --git a/test/credentials_test.dart b/test/credentials_test.dart deleted file mode 100644 index a82cd418..00000000 --- a/test/credentials_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/registration/credentials_screen/credentials_screen.dart'; -import 'package:eatvio_app/presentation/registration/credentials_screen/bloc/credentials_bloc.dart'; -import 'package:eatvio_app/presentation/registration/credentials_screen/models/credentials_model.dart'; - -void main() { - group('AdditionalInfoScreen', () { - testWidgets('renders screen in initial state', (WidgetTester tester) async { - final myProfileBloc = CredentialsBloc(CredentialsState( - credentialsModelObj: CredentialsModel( - userRegistrationSheet: UserRegistrationSheet( - name: "name", - firstName: "firstName", - lastName: "lastName", - email: "email", - password: "password", - passwordConfirmation: "passwordConfirmation", - termsAccepted: "termsAccepted", - birthdate: "birthdate", - gender: "gender", - country: "country", - city: "city", - lang: "lang", - weight: "weight", - height: "height", - chestCircumference: 'asdasd', - waistCircumference: "waistCircumference", - hipCircumference: "hipCircumference", - bloodPressureUp: "bloodPressureUp", - bloodPressureDown: "bloodPressureDown", - hasHypo: "hasHypo", - hasHyper: "hasHyper", - aboutAllergy: "aboutAllergy", - aboutTakingPils: "aboutTakingPils", - aboutSportHobbies: "aboutSportHobbies", - favoriteFoods: "favoriteFoods", - unfavoriteFoods: "unfavoriteFoods", - additionalInfo: - "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: CredentialsScreen(), - ), - ), - ); - }); - }); -} diff --git a/test/date_of_birth_test.dart b/test/date_of_birth_test.dart deleted file mode 100644 index 8ce0a1f7..00000000 --- a/test/date_of_birth_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/registration/date_of_birth_screen/date_of_birth_screen.dart'; -import 'package:eatvio_app/presentation/registration/date_of_birth_screen/bloc/date_of_birth_bloc.dart'; -import 'package:eatvio_app/presentation/registration/date_of_birth_screen/models/date_of_birth_model.dart'; - -void main() { - group('AdditionalInfoScreen', () { - testWidgets('renders screen in initial state', (WidgetTester tester) async { - final myProfileBloc = DateOfBirthBloc(DateOfBirthState( - dateOfBirthModelObj: DateOfBirthModel( - userRegistrationSheet: UserRegistrationSheet( - name: "name", - firstName: "firstName", - lastName: "lastName", - email: "email", - password: "password", - passwordConfirmation: "passwordConfirmation", - termsAccepted: "termsAccepted", - birthdate: "birthdate", - gender: "gender", - country: "country", - city: "city", - lang: "lang", - weight: "weight", - height: "height", - chestCircumference: 'asdasd', - waistCircumference: "waistCircumference", - hipCircumference: "hipCircumference", - bloodPressureUp: "bloodPressureUp", - bloodPressureDown: "bloodPressureDown", - hasHypo: "hasHypo", - hasHyper: "hasHyper", - aboutAllergy: "aboutAllergy", - aboutTakingPils: "aboutTakingPils", - aboutSportHobbies: "aboutSportHobbies", - favoriteFoods: "favoriteFoods", - unfavoriteFoods: "unfavoriteFoods", - additionalInfo: - "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: DateOfBirthScreen(), - ), - ), - ); - }); - }); -} diff --git a/test/diary_test.dart b/test/diary_test.dart deleted file mode 100644 index 56d1c582..00000000 --- a/test/diary_test.dart +++ /dev/null @@ -1,71 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/diary/diary_edit_screen/diary_edit_screen.dart'; -import 'package:eatvio_app/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart'; -import 'package:eatvio_app/presentation/diary/diary_edit_screen/models/diary_edit_model.dart'; - -void main() { - group('DiaryEditScreen', () { - /*testWidgets('renders CircularProgressIndicator when in initial state', - (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: DiaryEditScreen(), - ), - ); - });*/ - - testWidgets('renders _buildDiaryEditScreen when in loaded state', (WidgetTester tester) async { - final diaryEditBloc = DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel())); - final loadedState = DiaryEditLoadedState( - diaryId: 1, - selectedSatiety: 4, - autocompleteList: [], - photos: [], - portions: [], - wakeupExpanded: false, - moderationExpanded: false, - recommendedChartValues: [10, 10, 10, 10], - consumedChartValues: [1, 2, 3, 4], - moodExpanded: false,); - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: diaryEditBloc, - child: DiaryEditScreen(), - ), - ), - ); - - diaryEditBloc.emit(loadedState); - await tester.pump(); - - //expect(find.byType(_buildDiaryEditScreen), findsOneWidget); - }); - - /*testWidgets('renders error message when in error state', - (WidgetTester tester) async { - final diaryEditBloc = - DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel())); - final errorState = DiaryEditErrorState("error"); - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: diaryEditBloc, - child: DiaryEditScreen(), - ), - ), - ); - - diaryEditBloc.emit(errorState); - await tester.pump(); - - expect(find.text('Ошибка'), findsOneWidget); - });*/ - - // Add more tests for other scenarios if needed - }); -} diff --git a/test/favorite_foods_test.dart b/test/favorite_foods_test.dart deleted file mode 100644 index 6364726f..00000000 --- a/test/favorite_foods_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart'; -import 'package:eatvio_app/presentation/registration/favorite_foods_screen/bloc/favorite_foods_bloc.dart'; -import 'package:eatvio_app/presentation/registration/favorite_foods_screen/models/favorite_foods_model.dart'; - -void main() { - group('AdditionalInfoScreen', () { - testWidgets('renders screen in initial state', (WidgetTester tester) async { - final myProfileBloc = FavoriteFoodsBloc(FavoriteFoodsState( - favoriteFoodsModelObj: FavoriteFoodsModel( - userRegistrationSheet: UserRegistrationSheet( - name: "name", - firstName: "firstName", - lastName: "lastName", - email: "email", - password: "password", - passwordConfirmation: "passwordConfirmation", - termsAccepted: "termsAccepted", - birthdate: "birthdate", - gender: "gender", - country: "country", - city: "city", - lang: "lang", - weight: "weight", - height: "height", - chestCircumference: 'asdasd', - waistCircumference: "waistCircumference", - hipCircumference: "hipCircumference", - bloodPressureUp: "bloodPressureUp", - bloodPressureDown: "bloodPressureDown", - hasHypo: "hasHypo", - hasHyper: "hasHyper", - aboutAllergy: "aboutAllergy", - aboutTakingPils: "aboutTakingPils", - aboutSportHobbies: "aboutSportHobbies", - favoriteFoods: "favoriteFoods", - unfavoriteFoods: "unfavoriteFoods", - additionalInfo: - "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: FavoriteFoodsScreen(), - ), - ), - ); - }); - }); -} diff --git a/test/favorite_sports_test.dart b/test/favorite_sports_test.dart deleted file mode 100644 index 1c7311e6..00000000 --- a/test/favorite_sports_test.dart +++ /dev/null @@ -1,55 +0,0 @@ -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart'; -import 'package:eatvio_app/presentation/registration/favorite_sports_screen/bloc/favorite_sports_bloc.dart'; -import 'package:eatvio_app/presentation/registration/favorite_sports_screen/models/favorite_sports_model.dart'; - -void main() { - group('AdditionalInfoScreen', () { - testWidgets('renders screen in initial state', (WidgetTester tester) async { - final myProfileBloc = FavoriteSportsBloc(FavoriteSportsState( - favoriteSportsModelObj: FavoriteSportsModel( - userRegistrationSheet: UserRegistrationSheet( - name: "name", - firstName: "firstName", - lastName: "lastName", - email: "email", - password: "password", - passwordConfirmation: "passwordConfirmation", - termsAccepted: "termsAccepted", - birthdate: "birthdate", - gender: "gender", - country: "country", - city: "city", - lang: "lang", - weight: "weight", - height: "height", - chestCircumference: 'asdasd', - waistCircumference: "waistCircumference", - hipCircumference: "hipCircumference", - bloodPressureUp: "bloodPressureUp", - bloodPressureDown: "bloodPressureDown", - hasHypo: "hasHypo", - hasHyper: "hasHyper", - aboutAllergy: "aboutAllergy", - aboutTakingPils: "aboutTakingPils", - aboutSportHobbies: "aboutSportHobbies", - favoriteFoods: "favoriteSports", - unfavoriteFoods: "unfavoriteSports", - additionalInfo: - "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: FavoriteSportsScreen(), - ), - ), - ); - }); - }); -} -//sports \ No newline at end of file diff --git a/test/gender_test.dart b/test/gender_test.dart deleted file mode 100644 index 94ab621c..00000000 --- a/test/gender_test.dart +++ /dev/null @@ -1,55 +0,0 @@ -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/registration/gender_screen/gender_screen.dart'; -import 'package:eatvio_app/presentation/registration/gender_screen/bloc/gender_bloc.dart'; -import 'package:eatvio_app/presentation/registration/gender_screen/models/gender_model.dart'; - -void main() { - group('AdditionalInfoScreen', () { - testWidgets('renders screen in initial state', (WidgetTester tester) async { - final myProfileBloc = GenderBloc(GenderState( - genderModelObj: GenderModel( - userRegistrationSheet: UserRegistrationSheet( - name: "name", - firstName: "firstName", - lastName: "lastName", - email: "email", - password: "password", - passwordConfirmation: "passwordConfirmation", - termsAccepted: "termsAccepted", - birthdate: "birthdate", - gender: "gender", - country: "country", - city: "city", - lang: "lang", - weight: "weight", - height: "height", - chestCircumference: 'asdasd', - waistCircumference: "waistCircumference", - hipCircumference: "hipCircumference", - bloodPressureUp: "bloodPressureUp", - bloodPressureDown: "bloodPressureDown", - hasHypo: "hasHypo", - hasHyper: "hasHyper", - aboutAllergy: "aboutAllergy", - aboutTakingPils: "aboutTakingPils", - aboutSportHobbies: "aboutSportHobbies", - favoriteFoods: "favoriteSports", - unfavoriteFoods: "unfavoriteSports", - additionalInfo: - "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: GenderScreen(), - ), - ), - ); - }); - }); -} -//sports \ No newline at end of file diff --git a/test/height_test.dart b/test/height_test.dart deleted file mode 100644 index cd512ed4..00000000 --- a/test/height_test.dart +++ /dev/null @@ -1,55 +0,0 @@ -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/registration/height_screen/height_screen.dart'; -import 'package:eatvio_app/presentation/registration/height_screen/bloc/height_bloc.dart'; -import 'package:eatvio_app/presentation/registration/height_screen/models/height_model.dart'; - -void main() { - group('AdditionalInfoScreen', () { - testWidgets('renders screen in initial state', (WidgetTester tester) async { - final myProfileBloc = HeightBloc(HeightState( - heightModelObj: HeightModel( - userRegistrationSheet: UserRegistrationSheet( - name: "name", - firstName: "firstName", - lastName: "lastName", - email: "email", - password: "password", - passwordConfirmation: "passwordConfirmation", - termsAccepted: "termsAccepted", - birthdate: "birthdate", - height: "height", - country: "country", - city: "city", - lang: "lang", - weight: "weight", - gender: "height", - chestCircumference: 'asdasd', - waistCircumference: "waistCircumference", - hipCircumference: "hipCircumference", - bloodPressureUp: "bloodPressureUp", - bloodPressureDown: "bloodPressureDown", - hasHypo: "hasHypo", - hasHyper: "hasHyper", - aboutAllergy: "aboutAllergy", - aboutTakingPils: "aboutTakingPils", - aboutSportHobbies: "aboutSportHobbies", - favoriteFoods: "favoriteSports", - unfavoriteFoods: "unfavoriteSports", - additionalInfo: - "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: HeightScreen(), - ), - ), - ); - }); - }); -} -//sports \ No newline at end of file diff --git a/test/language_select_test.dart b/test/language_select_test.dart deleted file mode 100644 index 15582cf6..00000000 --- a/test/language_select_test.dart +++ /dev/null @@ -1,26 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/registration/language_select_screen/language_select_screen.dart'; -import 'package:eatvio_app/presentation/registration/language_select_screen/bloc/language_select_bloc.dart'; -import 'package:eatvio_app/presentation/registration/language_select_screen/models/language_select_model.dart'; - -void main() { - group('AdditionalInfoScreen', () { - testWidgets('renders screen in initial state', (WidgetTester tester) async { - final myProfileBloc = LanguageSelectBloc(LanguageSelectState( - languageSelectModelObj: - LanguageSelectModel(),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: LanguageSelectScreen(), - ), - ), - ); - }); - }); -} -//sports \ No newline at end of file diff --git a/test/launch_test.dart b/test/launch_test.dart deleted file mode 100644 index 4f1eafee..00000000 --- a/test/launch_test.dart +++ /dev/null @@ -1,15 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/main.dart' as app; - -void main() { - testWidgets('Smoke test', (WidgetTester tester) async { - // Запустить приложение - app.main(); - - // Подождать, пока приложение загрузится - await tester.pumpAndSettle(); - - // Проверить, что нет ошибок - expect(tester.takeException(), isNull); - }); -} diff --git a/test/medicine_intake_test.dart b/test/medicine_intake_test.dart deleted file mode 100644 index eae83c13..00000000 --- a/test/medicine_intake_test.dart +++ /dev/null @@ -1,55 +0,0 @@ -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart'; -import 'package:eatvio_app/presentation/registration/medicine_intake_screen/bloc/medicine_intake_bloc.dart'; -import 'package:eatvio_app/presentation/registration/medicine_intake_screen/models/medicine_intake_model.dart'; - -void main() { - group('AdditionalInfoScreen', () { - testWidgets('renders screen in initial state', (WidgetTester tester) async { - final myProfileBloc = MedicineIntakeBloc(MedicineIntakeState( - medicineIntakeModelObj: MedicineIntakeModel( - userRegistrationSheet: UserRegistrationSheet( - name: "name", - firstName: "firstName", - lastName: "lastName", - email: "email", - password: "password", - passwordConfirmation: "passwordConfirmation", - termsAccepted: "termsAccepted", - birthdate: "birthdate", - gender: "gender", - country: "country", - city: "city", - lang: "lang", - weight: "weight", - height: "height", - chestCircumference: 'asdasd', - waistCircumference: "waistCircumference", - hipCircumference: "hipCircumference", - bloodPressureUp: "bloodPressureUp", - bloodPressureDown: "bloodPressureDown", - hasHypo: "hasHypo", - hasHyper: "hasHyper", - aboutAllergy: "aboutAllergy", - aboutTakingPils: "aboutTakingPils", - aboutSportHobbies: "aboutSportHobbies", - favoriteFoods: "favoriteFoods", - unfavoriteFoods: "unfavoriteFoods", - additionalInfo: - "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: MedicineIntakeScreen(), - ), - ), - ); - }); - }); -} -//sports \ No newline at end of file diff --git a/test/name_test.dart b/test/name_test.dart deleted file mode 100644 index 1e271cb2..00000000 --- a/test/name_test.dart +++ /dev/null @@ -1,55 +0,0 @@ -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/registration/name_screen/name_screen.dart'; -import 'package:eatvio_app/presentation/registration/name_screen/bloc/name_bloc.dart'; -import 'package:eatvio_app/presentation/registration/name_screen/models/name_model.dart'; - -void main() { - group('AdditionalInfoScreen', () { - testWidgets('renders screen in initial state', (WidgetTester tester) async { - final myProfileBloc = NameBloc(NameState( - nameModelObj: NameModel( - userRegistrationSheet: UserRegistrationSheet( - name: "name", - firstName: "firstName", - lastName: "lastName", - email: "email", - password: "password", - passwordConfirmation: "passwordConfirmation", - termsAccepted: "termsAccepted", - birthdate: "birthdate", - gender: "gender", - country: "country", - city: "city", - lang: "lang", - weight: "weight", - height: "height", - chestCircumference: 'asdasd', - waistCircumference: "waistCircumference", - hipCircumference: "hipCircumference", - bloodPressureUp: "bloodPressureUp", - bloodPressureDown: "bloodPressureDown", - hasHypo: "hasHypo", - hasHyper: "hasHyper", - aboutAllergy: "aboutAllergy", - aboutTakingPils: "aboutTakingPils", - aboutSportHobbies: "aboutSportHobbies", - favoriteFoods: "favoriteFoods", - unfavoriteFoods: "unfavoriteFoods", - additionalInfo: - "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: NameScreen(), - ), - ), - ); - }); - }); -} -//sports \ No newline at end of file diff --git a/test/profile_test.dart b/test/profile_test.dart deleted file mode 100644 index cf0ebc41..00000000 --- a/test/profile_test.dart +++ /dev/null @@ -1,26 +0,0 @@ -import 'package:eatvio_app/core/app_export.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/profile/my_profile_screen/my_profile_screen.dart'; -import 'package:eatvio_app/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart'; -import 'package:eatvio_app/presentation/profile/my_profile_screen/models/my_profile_model.dart'; - -void main() { - group('MyProfileScreen', () { - testWidgets('renders CircularProgressIndicator in initial state', - (WidgetTester tester) async { - final myProfileBloc = MyProfileBloc(MyProfileState( - myProfileModelObj: - MyProfileModel(),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: MyProfileScreen(), - ), - ), - ); - }); - }); -} diff --git a/test/settings_test.dart b/test/settings_test.dart deleted file mode 100644 index c6058784..00000000 --- a/test/settings_test.dart +++ /dev/null @@ -1,26 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/profile/my_profile_screen/my_settings_screen.dart'; -import 'package:eatvio_app/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart'; -import 'package:eatvio_app/presentation/profile/my_profile_screen/models/my_profile_model.dart'; - -void main() { - group('MyProfileScreen', () { - testWidgets('renders CircularProgressIndicator in initial state', - (WidgetTester tester) async { - final myProfileBloc = MyProfileBloc(MyProfileState( - myProfileModelObj: - MyProfileModel(),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: MySettingsScreen(), - ), - ), - ); - }); - }); -} diff --git a/test/weight_test.dart b/test/weight_test.dart deleted file mode 100644 index e5f9fe0c..00000000 --- a/test/weight_test.dart +++ /dev/null @@ -1,55 +0,0 @@ -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:eatvio_app/presentation/registration/weight_screen/weight_screen.dart'; -import 'package:eatvio_app/presentation/registration/weight_screen/bloc/weight_bloc.dart'; -import 'package:eatvio_app/presentation/registration/weight_screen/models/weight_model.dart'; - -void main() { - group('AdditionalInfoScreen', () { - testWidgets('renders screen in initial state', (WidgetTester tester) async { - final myProfileBloc = WeightBloc(WeightState( - weightModelObj: WeightModel( - userRegistrationSheet: UserRegistrationSheet( - name: "name", - firstName: "firstName", - lastName: "lastName", - email: "email", - password: "password", - passwordConfirmation: "passwordConfirmation", - termsAccepted: "termsAccepted", - birthdate: "birthdate", - gender: "gender", - country: "country", - city: "city", - lang: "lang", - weight: "weight", - height: "height", - chestCircumference: 'asdasd', - waistCircumference: "waistCircumference", - hipCircumference: "hipCircumference", - bloodPressureUp: "bloodPressureUp", - bloodPressureDown: "bloodPressureDown", - hasHypo: "hasHypo", - hasHyper: "hasHyper", - aboutAllergy: "aboutAllergy", - aboutTakingPils: "aboutTakingPils", - aboutSportHobbies: "aboutSportHobbies", - favoriteFoods: "favoriteFoods", - unfavoriteFoods: "unfavoriteFoods", - additionalInfo: - "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable - - await tester.pumpWidget( - MaterialApp( - home: BlocProvider.value( - value: myProfileBloc, - child: WeightScreen(), - ), - ), - ); - }); - }); -} -//sports \ No newline at end of file