From eaa9247927f1667b576cd617ce301946d11f1e58 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Mon, 24 Jun 2024 11:15:43 +0300 Subject: [PATCH 001/110] feat(ci): rename artifact --- .gitea/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitea/workflows/test.yml b/.gitea/workflows/test.yml index a8fbb7d..ffd3281 100644 --- a/.gitea/workflows/test.yml +++ b/.gitea/workflows/test.yml @@ -107,5 +107,5 @@ jobs: - name: Upload APK artifact uses: actions/upload-artifact@v3 with: - name: EatvioApp-APK + name: ${{ env.APK_NAME }} path: ${{ env.APK_NAME }} -- 2.49.1 From 05ccfd289cc9340fc13037552181f382674e877e Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Mon, 24 Jun 2024 20:03:54 +0300 Subject: [PATCH 002/110] feat(chat): add websocket --- ios/Podfile | 6 +- ios/Runner.xcodeproj/project.pbxproj | 76 +-- lib/core/app_export.dart | 1 - .../initialization_cubit.dart | 46 ++ .../initialization_state.dart | 14 + .../initialization_state.freezed.dart | 589 ++++++++++++++++++ lib/core/network/network_info.dart | 47 -- .../chat/models/websocket_info_model.dart | 6 +- .../models/websocket_info_model.freezed.dart | 104 +++- .../chat/models/websocket_info_model.g.dart | 12 +- .../chat_select_screen/chat_search_view.dart | 53 +- .../chat_select_screen.dart | 2 +- lib/locator_service.dart | 2 + lib/main.dart | 84 ++- .../my_profile_screen/my_profile_screen.dart | 4 +- pubspec.yaml | 57 +- test/auth_test.dart | 3 - 17 files changed, 911 insertions(+), 195 deletions(-) create mode 100644 lib/core/initialization_cubit/initialization_cubit.dart create mode 100644 lib/core/initialization_cubit/initialization_state.dart create mode 100644 lib/core/initialization_cubit/initialization_state.freezed.dart delete mode 100644 lib/core/network/network_info.dart diff --git a/ios/Podfile b/ios/Podfile index 279576f..27c089c 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -1,5 +1,5 @@ # Uncomment this line to define a global platform for your project -# platform :ios, '12.0' +platform :ios, '14.0' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' @@ -37,5 +37,9 @@ end post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) + target.build_configurations.each do |config| + config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64" + config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '14.0' + end end end diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 68ec53f..7454c98 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -9,7 +9,7 @@ /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 68F4DD6659288F4CFDC41C5C /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7024DE075B2C1E5A149230E4 /* Pods_Runner.framework */; }; + 46B43B96F809CEC6058EFDD3 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 15ADDB2A35F334AF0AE50011 /* Pods_Runner.framework */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; @@ -32,13 +32,12 @@ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 1DC098B20AE17A152A9E7BC6 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + 15ADDB2A35F334AF0AE50011 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 4B6A3CFB60775CA626789750 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; - 7024DE075B2C1E5A149230E4 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 938EE8FB5BAA359AAEDEFFF8 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -46,7 +45,8 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - EC46FEE88A2E87A3510B5EC3 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + 9D8D6181877DE17809AFF936 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + DF0C4038A57E19D3ABA03C15 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -54,27 +54,19 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 68F4DD6659288F4CFDC41C5C /* Pods_Runner.framework in Frameworks */, + 46B43B96F809CEC6058EFDD3 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 28430AE518366E9EB19A31C9 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 7024DE075B2C1E5A149230E4 /* Pods_Runner.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; 6F201E010624CF963CC3A17B /* Pods */ = { isa = PBXGroup; children = ( - 1DC098B20AE17A152A9E7BC6 /* Pods-Runner.debug.xcconfig */, - 4B6A3CFB60775CA626789750 /* Pods-Runner.release.xcconfig */, - EC46FEE88A2E87A3510B5EC3 /* Pods-Runner.profile.xcconfig */, + 938EE8FB5BAA359AAEDEFFF8 /* Pods-Runner.debug.xcconfig */, + 9D8D6181877DE17809AFF936 /* Pods-Runner.release.xcconfig */, + DF0C4038A57E19D3ABA03C15 /* Pods-Runner.profile.xcconfig */, ); path = Pods; sourceTree = ""; @@ -97,7 +89,7 @@ 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, 6F201E010624CF963CC3A17B /* Pods */, - 28430AE518366E9EB19A31C9 /* Frameworks */, + AEE6B7943D197783DD1CB2EE /* Frameworks */, ); sourceTree = ""; }; @@ -124,6 +116,14 @@ path = Runner; sourceTree = ""; }; + AEE6B7943D197783DD1CB2EE /* Frameworks */ = { + isa = PBXGroup; + children = ( + 15ADDB2A35F334AF0AE50011 /* Pods_Runner.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -131,14 +131,14 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - C9531164650CD277994F87F5 /* [CP] Check Pods Manifest.lock */, + 9A49250058577CAA8C897A03 /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, - 8944C2327F94FA34E28A19A3 /* [CP] Embed Pods Frameworks */, + 1D324C14EB43C988423BC1AD /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -198,23 +198,7 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { - isa = PBXShellScriptBuildPhase; - alwaysOutOfDate = 1; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", - ); - name = "Thin Binary"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; - }; - 8944C2327F94FA34E28A19A3 /* [CP] Embed Pods Frameworks */ = { + 1D324C14EB43C988423BC1AD /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( @@ -231,6 +215,22 @@ shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -246,7 +246,7 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; - C9531164650CD277994F87F5 /* [CP] Check Pods Manifest.lock */ = { + 9A49250058577CAA8C897A03 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( diff --git a/lib/core/app_export.dart b/lib/core/app_export.dart index 233b58c..ae95a22 100644 --- a/lib/core/app_export.dart +++ b/lib/core/app_export.dart @@ -1,7 +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/network/network_info.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'; diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart new file mode 100644 index 0000000..e61d691 --- /dev/null +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -0,0 +1,46 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/core/initialization_cubit/initialization_state.dart'; +import 'package:eatvio_app/core/token_storage.dart'; +import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; +import 'package:pusher_client/pusher_client.dart'; + +class InitializationCubit extends Cubit { + late final webSocketChannel; + + final ChatRepository chatRepository; + + InitializationCubit({required this.chatRepository}) : super(const InitializationState.loading()); + + runInitialization() async { + try { + await TokenStorage.haveTokenInStorage(); + + final wsUrl = await chatRepository.getWebsocket(); + + PusherOptions options = PusherOptions( + host: 'socket.mobile-stage.eatvio.ru', + wsPort: 443, + encrypted: true, + auth: PusherAuth( + 'wss://' + wsUrl.host + '/app/' + wsUrl.key, + headers: { + 'Authorization': 'Bearer ${TokenStorage.getTokenFromStorage()}', + }, + ), + ); + + PusherClient pusher = PusherClient( + wsUrl.key, + options, + autoConnect: true, + enableLogging: true, + ); + + await pusher.connect(); + + emit(const InitializationState.success()); + } catch (e) { + emit(InitializationState.error(errorMessage: e.toString())); + } + } +} diff --git a/lib/core/initialization_cubit/initialization_state.dart b/lib/core/initialization_cubit/initialization_state.dart new file mode 100644 index 0000000..98f881c --- /dev/null +++ b/lib/core/initialization_cubit/initialization_state.dart @@ -0,0 +1,14 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'initialization_state.freezed.dart'; + +@freezed +abstract class InitializationState with _$InitializationState { + const factory InitializationState() = _InitializationState; + + const factory InitializationState.loading() = InitializationStateLoading; + + const factory InitializationState.success() = InitializationStateSuccess; + + const factory InitializationState.error({required String errorMessage}) = InitializationStateError; +} diff --git a/lib/core/initialization_cubit/initialization_state.freezed.dart b/lib/core/initialization_cubit/initialization_state.freezed.dart new file mode 100644 index 0000000..136672f --- /dev/null +++ b/lib/core/initialization_cubit/initialization_state.freezed.dart @@ -0,0 +1,589 @@ +// 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 'initialization_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 _$InitializationState { + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function() success, + required TResult Function(String errorMessage) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function()? success, + TResult? Function(String errorMessage)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function()? success, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map( + TResult Function(_InitializationState value) $default, { + required TResult Function(InitializationStateLoading value) loading, + required TResult Function(InitializationStateSuccess value) success, + required TResult Function(InitializationStateError value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_InitializationState value)? $default, { + TResult? Function(InitializationStateLoading value)? loading, + TResult? Function(InitializationStateSuccess value)? success, + TResult? Function(InitializationStateError value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap( + TResult Function(_InitializationState value)? $default, { + TResult Function(InitializationStateLoading value)? loading, + TResult Function(InitializationStateSuccess value)? success, + TResult Function(InitializationStateError value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $InitializationStateCopyWith<$Res> { + factory $InitializationStateCopyWith( + InitializationState value, $Res Function(InitializationState) then) = + _$InitializationStateCopyWithImpl<$Res, InitializationState>; +} + +/// @nodoc +class _$InitializationStateCopyWithImpl<$Res, $Val extends InitializationState> + implements $InitializationStateCopyWith<$Res> { + _$InitializationStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; +} + +/// @nodoc +abstract class _$$InitializationStateImplCopyWith<$Res> { + factory _$$InitializationStateImplCopyWith(_$InitializationStateImpl value, + $Res Function(_$InitializationStateImpl) then) = + __$$InitializationStateImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitializationStateImplCopyWithImpl<$Res> + extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateImpl> + implements _$$InitializationStateImplCopyWith<$Res> { + __$$InitializationStateImplCopyWithImpl(_$InitializationStateImpl _value, + $Res Function(_$InitializationStateImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$InitializationStateImpl implements _InitializationState { + const _$InitializationStateImpl(); + + @override + String toString() { + return 'InitializationState()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$InitializationStateImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function() success, + required TResult Function(String errorMessage) error, + }) { + return $default(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function()? success, + TResult? Function(String errorMessage)? error, + }) { + return $default?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function()? success, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_InitializationState value) $default, { + required TResult Function(InitializationStateLoading value) loading, + required TResult Function(InitializationStateSuccess value) success, + required TResult Function(InitializationStateError value) error, + }) { + return $default(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_InitializationState value)? $default, { + TResult? Function(InitializationStateLoading value)? loading, + TResult? Function(InitializationStateSuccess value)? success, + TResult? Function(InitializationStateError value)? error, + }) { + return $default?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_InitializationState value)? $default, { + TResult Function(InitializationStateLoading value)? loading, + TResult Function(InitializationStateSuccess value)? success, + TResult Function(InitializationStateError value)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(this); + } + return orElse(); + } +} + +abstract class _InitializationState implements InitializationState { + const factory _InitializationState() = _$InitializationStateImpl; +} + +/// @nodoc +abstract class _$$InitializationStateLoadingImplCopyWith<$Res> { + factory _$$InitializationStateLoadingImplCopyWith( + _$InitializationStateLoadingImpl value, + $Res Function(_$InitializationStateLoadingImpl) then) = + __$$InitializationStateLoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitializationStateLoadingImplCopyWithImpl<$Res> + extends _$InitializationStateCopyWithImpl<$Res, + _$InitializationStateLoadingImpl> + implements _$$InitializationStateLoadingImplCopyWith<$Res> { + __$$InitializationStateLoadingImplCopyWithImpl( + _$InitializationStateLoadingImpl _value, + $Res Function(_$InitializationStateLoadingImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$InitializationStateLoadingImpl implements InitializationStateLoading { + const _$InitializationStateLoadingImpl(); + + @override + String toString() { + return 'InitializationState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$InitializationStateLoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function() success, + required TResult Function(String errorMessage) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function()? success, + TResult? Function(String errorMessage)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function()? success, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_InitializationState value) $default, { + required TResult Function(InitializationStateLoading value) loading, + required TResult Function(InitializationStateSuccess value) success, + required TResult Function(InitializationStateError value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_InitializationState value)? $default, { + TResult? Function(InitializationStateLoading value)? loading, + TResult? Function(InitializationStateSuccess value)? success, + TResult? Function(InitializationStateError value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_InitializationState value)? $default, { + TResult Function(InitializationStateLoading value)? loading, + TResult Function(InitializationStateSuccess value)? success, + TResult Function(InitializationStateError value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class InitializationStateLoading implements InitializationState { + const factory InitializationStateLoading() = _$InitializationStateLoadingImpl; +} + +/// @nodoc +abstract class _$$InitializationStateSuccessImplCopyWith<$Res> { + factory _$$InitializationStateSuccessImplCopyWith( + _$InitializationStateSuccessImpl value, + $Res Function(_$InitializationStateSuccessImpl) then) = + __$$InitializationStateSuccessImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitializationStateSuccessImplCopyWithImpl<$Res> + extends _$InitializationStateCopyWithImpl<$Res, + _$InitializationStateSuccessImpl> + implements _$$InitializationStateSuccessImplCopyWith<$Res> { + __$$InitializationStateSuccessImplCopyWithImpl( + _$InitializationStateSuccessImpl _value, + $Res Function(_$InitializationStateSuccessImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$InitializationStateSuccessImpl implements InitializationStateSuccess { + const _$InitializationStateSuccessImpl(); + + @override + String toString() { + return 'InitializationState.success()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$InitializationStateSuccessImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function() success, + required TResult Function(String errorMessage) error, + }) { + return success(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function()? success, + TResult? Function(String errorMessage)? error, + }) { + return success?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function()? success, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_InitializationState value) $default, { + required TResult Function(InitializationStateLoading value) loading, + required TResult Function(InitializationStateSuccess value) success, + required TResult Function(InitializationStateError value) error, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_InitializationState value)? $default, { + TResult? Function(InitializationStateLoading value)? loading, + TResult? Function(InitializationStateSuccess value)? success, + TResult? Function(InitializationStateError value)? error, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_InitializationState value)? $default, { + TResult Function(InitializationStateLoading value)? loading, + TResult Function(InitializationStateSuccess value)? success, + TResult Function(InitializationStateError value)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class InitializationStateSuccess implements InitializationState { + const factory InitializationStateSuccess() = _$InitializationStateSuccessImpl; +} + +/// @nodoc +abstract class _$$InitializationStateErrorImplCopyWith<$Res> { + factory _$$InitializationStateErrorImplCopyWith( + _$InitializationStateErrorImpl value, + $Res Function(_$InitializationStateErrorImpl) then) = + __$$InitializationStateErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String errorMessage}); +} + +/// @nodoc +class __$$InitializationStateErrorImplCopyWithImpl<$Res> + extends _$InitializationStateCopyWithImpl<$Res, + _$InitializationStateErrorImpl> + implements _$$InitializationStateErrorImplCopyWith<$Res> { + __$$InitializationStateErrorImplCopyWithImpl( + _$InitializationStateErrorImpl _value, + $Res Function(_$InitializationStateErrorImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? errorMessage = null, + }) { + return _then(_$InitializationStateErrorImpl( + errorMessage: null == errorMessage + ? _value.errorMessage + : errorMessage // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$InitializationStateErrorImpl implements InitializationStateError { + const _$InitializationStateErrorImpl({required this.errorMessage}); + + @override + final String errorMessage; + + @override + String toString() { + return 'InitializationState.error(errorMessage: $errorMessage)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$InitializationStateErrorImpl && + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); + } + + @override + int get hashCode => Object.hash(runtimeType, errorMessage); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> + get copyWith => __$$InitializationStateErrorImplCopyWithImpl< + _$InitializationStateErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function() success, + required TResult Function(String errorMessage) error, + }) { + return error(errorMessage); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function()? success, + TResult? Function(String errorMessage)? error, + }) { + return error?.call(errorMessage); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function()? success, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(errorMessage); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_InitializationState value) $default, { + required TResult Function(InitializationStateLoading value) loading, + required TResult Function(InitializationStateSuccess value) success, + required TResult Function(InitializationStateError value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_InitializationState value)? $default, { + TResult? Function(InitializationStateLoading value)? loading, + TResult? Function(InitializationStateSuccess value)? success, + TResult? Function(InitializationStateError value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_InitializationState value)? $default, { + TResult Function(InitializationStateLoading value)? loading, + TResult Function(InitializationStateSuccess value)? success, + TResult Function(InitializationStateError value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class InitializationStateError implements InitializationState { + const factory InitializationStateError({required final String errorMessage}) = + _$InitializationStateErrorImpl; + + String get errorMessage; + @JsonKey(ignore: true) + _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> + get copyWith => throw _privateConstructorUsedError; +} diff --git a/lib/core/network/network_info.dart b/lib/core/network/network_info.dart deleted file mode 100644 index c92c521..0000000 --- a/lib/core/network/network_info.dart +++ /dev/null @@ -1,47 +0,0 @@ -import 'package:connectivity_plus/connectivity_plus.dart'; - -// For checking internet connectivity -abstract class NetworkInfoI { - Future isConnected(); - - Future get connectivityResult; - - Stream get onConnectivityChanged; -} - -class NetworkInfo implements NetworkInfoI { - Connectivity connectivity; - - static final NetworkInfo _networkInfo = NetworkInfo._internal(Connectivity()); - - factory NetworkInfo() { - return _networkInfo; - } - - NetworkInfo._internal(this.connectivity) { - connectivity = this.connectivity; - } - - ///checks internet is connected or not - ///returns [true] if internet is connected - ///else it will return [false] - @override - Future isConnected() async { - final result = await connectivity.checkConnectivity(); - if (result != ConnectivityResult.none) { - return true; - } - return false; - } - - // to check type of internet connectivity - @override - Future get connectivityResult async { - return connectivity.checkConnectivity(); - } - - //check the type on internet connection on changed of internet connection - @override - Stream get onConnectivityChanged => - connectivity.onConnectivityChanged; -} diff --git a/lib/features/chat/models/websocket_info_model.dart b/lib/features/chat/models/websocket_info_model.dart index 9fe8abc..281c71e 100644 --- a/lib/features/chat/models/websocket_info_model.dart +++ b/lib/features/chat/models/websocket_info_model.dart @@ -6,7 +6,11 @@ part 'websocket_info_model.g.dart'; @freezed class WebsocketInfoModel with _$WebsocketInfoModel { - const factory WebsocketInfoModel() = _WebsocketInfoModel; + const factory WebsocketInfoModel({ + required String key, + required String host, + required String port, + }) = _WebsocketInfoModel; factory WebsocketInfoModel.fromJson(Map json) => _$WebsocketInfoModelFromJson(json); } diff --git a/lib/features/chat/models/websocket_info_model.freezed.dart b/lib/features/chat/models/websocket_info_model.freezed.dart index fd9ef4b..9a26fee 100644 --- a/lib/features/chat/models/websocket_info_model.freezed.dart +++ b/lib/features/chat/models/websocket_info_model.freezed.dart @@ -20,7 +20,14 @@ WebsocketInfoModel _$WebsocketInfoModelFromJson(Map json) { /// @nodoc mixin _$WebsocketInfoModel { + String get key => throw _privateConstructorUsedError; + String get host => throw _privateConstructorUsedError; + String get port => throw _privateConstructorUsedError; + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $WebsocketInfoModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc @@ -28,6 +35,8 @@ abstract class $WebsocketInfoModelCopyWith<$Res> { factory $WebsocketInfoModelCopyWith( WebsocketInfoModel value, $Res Function(WebsocketInfoModel) then) = _$WebsocketInfoModelCopyWithImpl<$Res, WebsocketInfoModel>; + @useResult + $Res call({String key, String host, String port}); } /// @nodoc @@ -39,13 +48,40 @@ class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel> final $Val _value; // ignore: unused_field final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? key = null, + Object? host = null, + Object? port = null, + }) { + return _then(_value.copyWith( + key: null == key + ? _value.key + : key // ignore: cast_nullable_to_non_nullable + as String, + host: null == host + ? _value.host + : host // ignore: cast_nullable_to_non_nullable + as String, + port: null == port + ? _value.port + : port // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } } /// @nodoc -abstract class _$$WebsocketInfoModelImplCopyWith<$Res> { +abstract class _$$WebsocketInfoModelImplCopyWith<$Res> + implements $WebsocketInfoModelCopyWith<$Res> { factory _$$WebsocketInfoModelImplCopyWith(_$WebsocketInfoModelImpl value, $Res Function(_$WebsocketInfoModelImpl) then) = __$$WebsocketInfoModelImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String key, String host, String port}); } /// @nodoc @@ -55,30 +91,72 @@ class __$$WebsocketInfoModelImplCopyWithImpl<$Res> __$$WebsocketInfoModelImplCopyWithImpl(_$WebsocketInfoModelImpl _value, $Res Function(_$WebsocketInfoModelImpl) _then) : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? key = null, + Object? host = null, + Object? port = null, + }) { + return _then(_$WebsocketInfoModelImpl( + key: null == key + ? _value.key + : key // ignore: cast_nullable_to_non_nullable + as String, + host: null == host + ? _value.host + : host // ignore: cast_nullable_to_non_nullable + as String, + port: null == port + ? _value.port + : port // ignore: cast_nullable_to_non_nullable + as String, + )); + } } /// @nodoc @JsonSerializable() class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { - const _$WebsocketInfoModelImpl(); + const _$WebsocketInfoModelImpl( + {required this.key, required this.host, required this.port}); factory _$WebsocketInfoModelImpl.fromJson(Map json) => _$$WebsocketInfoModelImplFromJson(json); + @override + final String key; + @override + final String host; + @override + final String port; + @override String toString() { - return 'WebsocketInfoModel()'; + return 'WebsocketInfoModel(key: $key, host: $host, port: $port)'; } @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && other is _$WebsocketInfoModelImpl); + (other.runtimeType == runtimeType && + other is _$WebsocketInfoModelImpl && + (identical(other.key, key) || other.key == key) && + (identical(other.host, host) || other.host == host) && + (identical(other.port, port) || other.port == port)); } @JsonKey(ignore: true) @override - int get hashCode => runtimeType.hashCode; + int get hashCode => Object.hash(runtimeType, key, host, port); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith => + __$$WebsocketInfoModelImplCopyWithImpl<_$WebsocketInfoModelImpl>( + this, _$identity); @override Map toJson() { @@ -89,8 +167,22 @@ class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { } abstract class _WebsocketInfoModel implements WebsocketInfoModel { - const factory _WebsocketInfoModel() = _$WebsocketInfoModelImpl; + const factory _WebsocketInfoModel( + {required final String key, + required final String host, + required final String port}) = _$WebsocketInfoModelImpl; factory _WebsocketInfoModel.fromJson(Map json) = _$WebsocketInfoModelImpl.fromJson; + + @override + String get key; + @override + String get host; + @override + String get port; + @override + @JsonKey(ignore: true) + _$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/websocket_info_model.g.dart b/lib/features/chat/models/websocket_info_model.g.dart index 6573c3c..e5b5c32 100644 --- a/lib/features/chat/models/websocket_info_model.g.dart +++ b/lib/features/chat/models/websocket_info_model.g.dart @@ -8,8 +8,16 @@ part of 'websocket_info_model.dart'; _$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson( Map json) => - _$WebsocketInfoModelImpl(); + _$WebsocketInfoModelImpl( + key: json['key'] as String, + host: json['host'] as String, + port: json['port'] as String, + ); Map _$$WebsocketInfoModelImplToJson( _$WebsocketInfoModelImpl instance) => - {}; + { + 'key': instance.key, + 'host': instance.host, + 'port': instance.port, + }; 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 939bb42..22020a9 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 @@ -2,32 +2,30 @@ import 'package:flutter/material.dart'; import 'package:eatvio_app/core/app_export.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( - key: key, - ); + 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); final Alignment? alignment; @@ -73,13 +71,12 @@ class CustomSearchView extends StatelessWidget { @override Widget build(BuildContext context) { - return alignment != null ? Align(alignment: alignment ?? Alignment.center, child: searchViewWidget(context)) : searchViewWidget(context); + return searchViewWidget(context); } searchViewWidget(BuildContext context) => SizedBox( width: width ?? double.maxFinite, child: TextFormField( - scrollPadding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), controller: controller, focusNode: focusNode, onTapOutside: (event) => onTapOutside(), 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 fe468f3..74911c3 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 @@ -44,7 +44,7 @@ class ChatSelectScreen extends StatelessWidget { headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return [ SliverAppBar( - backgroundColor: Colors.white, + automaticallyImplyLeading: false, stretchTriggerOffset: 1, forceMaterialTransparency: true, floating: true, diff --git a/lib/locator_service.dart b/lib/locator_service.dart index 6823378..8759775 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/initialization_cubit/initialization_cubit.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; import 'package:eatvio_app/features/chat/services/chat_service.dart'; @@ -10,6 +11,7 @@ final sl = GetIt.instance; Future init() async { // BLoC sl.registerFactory(() => ChatRoomCubit(chatRepository: sl())); + sl.registerFactory(() => InitializationCubit(chatRepository: sl())); // Repository sl.registerLazySingleton(() => ChatRepository(chatService: sl())); diff --git a/lib/main.dart b/lib/main.dart index 8e0c1b9..ebe2289 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,6 +1,9 @@ import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.dart'; +import 'package:eatvio_app/core/initialization_cubit/initialization_state.dart'; 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/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'; import 'package:eatvio_app/presentation/feed/feed_screen/bloc/feed_bloc.dart'; @@ -40,64 +43,53 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MultiBlocProvider( providers: [ + BlocProvider(create: (context) => sl()..runInitialization()), BlocProvider( - create: (context) => ThemeBloc( - ThemeState(themeType: PrefUtils().getThemeData()), - ), + create: (context) => ThemeBloc(ThemeState(themeType: PrefUtils().getThemeData())), ), BlocProvider( - create: (context) => MyProfileBloc( - MyProfileState( - myProfileModelObj: MyProfileModel(), - ), - )..add(MyProfileInitialEvent()), + create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent()), ), BlocProvider( - create: (context) => FeedBloc(FeedState(myProfileModelObj: FeedModel())) - ..add( - FeedInitialEvent(), - ), + create: (context) => FeedBloc(FeedState(myProfileModelObj: FeedModel()))..add(FeedInitialEvent()), ), BlocProvider( - create: (context) => DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel())) - ..add( - DiaryEditInitialEvent(), - ), + create: (context) => DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel()))..add(DiaryEditInitialEvent()), ), BlocProvider( - create: (context) => ChatSelectBloc(ChatSelectState(chatSelectModelObj: ChatSelectModel())) - ..add( - ChatSelectInitialEvent(), - ), + create: (context) => ChatSelectBloc(ChatSelectState(chatSelectModelObj: ChatSelectModel()))..add(ChatSelectInitialEvent()), ), ], - child: BlocBuilder( - builder: (context, state) { - return KeyboardDismisser( - gestures: [ - GestureType.onTap, - GestureType.onPanUpdateDownDirection, - ], - child: MaterialApp.router( - theme: theme, - title: 'Eatvio', - routerConfig: AppRouter.appRouter, - debugShowCheckedModeBanner: false, - localizationsDelegates: [ - AppLocalizationDelegate(), - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, + child: BlocListener( + listener: (BuildContext context, InitializationState state) { }, + child: BlocBuilder( + builder: (context, state) { + return KeyboardDismisser( + gestures: [ + GestureType.onTap, + GestureType.onPanUpdateDownDirection, ], - supportedLocales: [ - Locale( - 'ru', - '', - ), - ], - ), - ); - }, + child: MaterialApp.router( + theme: theme, + title: 'Eatvio', + routerConfig: AppRouter.appRouter, + debugShowCheckedModeBanner: false, + localizationsDelegates: [ + AppLocalizationDelegate(), + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: [ + Locale( + 'ru', + '', + ), + ], + ), + ); + }, + ), ), ); } 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 e6f9706..48d1ed6 100644 --- a/lib/presentation/profile/my_profile_screen/my_profile_screen.dart +++ b/lib/presentation/profile/my_profile_screen/my_profile_screen.dart @@ -342,7 +342,7 @@ class MyProfileScreen extends StatelessWidget { lineTouchData: LineTouchData( touchTooltipData: LineTouchTooltipData( maxContentWidth: 100, - tooltipBgColor: Colors.black, + // tooltipBgColor: Colors.black, getTooltipItems: mapSpots(), ), handleBuiltInTouches: true, @@ -519,7 +519,7 @@ class MyProfileScreen extends StatelessWidget { lineTouchData: LineTouchData( touchTooltipData: LineTouchTooltipData( maxContentWidth: 100, - tooltipBgColor: Colors.black, + // tooltipBgColor: Colors.black, getTooltipItems: mapTouchedSpots(), ), handleBuiltInTouches: true, diff --git a/pubspec.yaml b/pubspec.yaml index 6000794..ad2e28f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -12,36 +12,55 @@ dependencies: flutter_localizations: sdk: flutter - flutter_bloc: ^8.0.0 - connectivity_plus: ^5.0.2 - shared_preferences: ^2.0.15 - cached_network_image: ^3.3.1 - flutter_svg: ^2.0.9 - equatable: ^2.0.0 - validators: ^3.0.0 + # BLoC state manager + flutter_bloc: ^8.1.6 + # local storage + shared_preferences: ^2.2.3 hive: ^2.2.3 hive_flutter: ^1.1.0 - isar_flutter_libs: ^4.0.0-dev.13 - path_provider: ^2.1.0 - fl_chart: ^0.66.0 - flutter_spinkit: ^5.0.0 + # + cached_network_image: ^3.3.1 + # + flutter_svg: ^2.0.9 + # + equatable: ^2.0.5 + # + freezed_annotation: ^2.4.1 + # + json_annotation: ^4.9.0 + # + validators: ^3.0.0 + # + isar_flutter_libs: ^3.1.0+1 + # + 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.2.1 - image_picker: ^1.0.7 + # + flutter_form_builder: ^9.3.0 + # + image_picker: ^1.1.2 + # flutter_typeahead: ^5.2.0 - bloc_test: ^9.1.6 # navigation go_router: ^14.1.4 + # keyboard_dismisser: ^3.0.0 - - freezed_annotation: ^2.4.1 - json_annotation: ^4.9.0 + # service generator retrofit: ^4.1.0 + # di get_it: ^7.7.0 + # http request dio: ^5.4.3+1 - - # photo viewer + # websocket + pusher_client: ^2.0.0 + # photo gallery viewer photo_view: ^0.15.0 #url launcher url_launcher: ^6.3.0 diff --git a/test/auth_test.dart b/test/auth_test.dart index 22de3a0..e131dc8 100644 --- a/test/auth_test.dart +++ b/test/auth_test.dart @@ -2,13 +2,10 @@ import 'package:eatvio_app/core/app_export.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; -import 'package:bloc_test/bloc_test.dart'; import 'package:eatvio_app/presentation/auth/auth_screen/auth_screen.dart'; import 'package:eatvio_app/presentation/auth/auth_screen/bloc/auth_bloc.dart'; import 'package:eatvio_app/presentation/auth/auth_screen/models/auth_model.dart'; -class MockAuthBloc extends MockBloc implements AuthBloc {} - void main() { group('AuthScreen', () { testWidgets('renders AuthScreen with initial state', -- 2.49.1 From 2337bdd3689cff64e2e6ad9c30afcecba55b9ddc Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Tue, 25 Jun 2024 15:26:03 +0300 Subject: [PATCH 003/110] feat(chat): hero animation + chat select scren --- lib/app_router.dart | 12 +- .../initialization_cubit.dart | 3 + .../chat/presentation/pages/chat_screen.dart | 194 +++++++++--------- .../bloc/chat_select_bloc.dart | 20 +- .../chat_select_screen.dart | 5 +- .../chat_select_screen/models/chat_entry.dart | 29 ++- .../models/chat_select_model.dart | 2 + .../widgets/chat_entry_widget.dart | 7 +- .../presentation/pages/photo_view_screen.dart | 92 ++++----- .../widgets/chat_bubble_widget.dart | 26 ++- .../my_profile_screen/my_profile_screen.dart | 14 +- pubspec.yaml | 7 +- 12 files changed, 211 insertions(+), 200 deletions(-) diff --git a/lib/app_router.dart b/lib/app_router.dart index 3c60e6e..f0aafe9 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -202,16 +202,14 @@ class AppRouter { path: '/chat-select-screen', name: 'chatSelectScreen', builder: (context, state) => ChatSelectScreen(), - routes: [ - GoRoute( - path: 'chat-screen', - name: 'chatScreen', - builder: (context, state) => ChatScreen(chatId: state.extra as String), - ), - ], ), ], ), + GoRoute( + path: '/chat-screen', + name: 'chatScreen', + builder: (context, state) => ChatScreen(chatId: state.extra as String), + ), GoRoute( path: '/my-settings-screen', name: 'mySettingsScreen', diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index e61d691..cd9828e 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -38,6 +38,9 @@ class InitializationCubit extends Cubit { await pusher.connect(); + // Channel channel = pusher.subscribe('private-direct-chat.'); + // channel.registerListener(classId, method); + emit(const InitializationState.success()); } catch (e) { emit(InitializationState.error(errorMessage: e.toString())); diff --git a/lib/features/chat/presentation/pages/chat_screen.dart b/lib/features/chat/presentation/pages/chat_screen.dart index c6ad9be..4c4bcfe 100644 --- a/lib/features/chat/presentation/pages/chat_screen.dart +++ b/lib/features/chat/presentation/pages/chat_screen.dart @@ -81,119 +81,121 @@ class ChatScreen extends StatelessWidget { ], ), ), - body: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Expanded( - child: Container( - color: Color(0xFFF0F2F5), - width: double.maxFinite, - child: CustomScrollView( - reverse: true, - slivers: [ - SliverPadding( - padding: EdgeInsets.symmetric(vertical: 16), - sliver: SliverList( - delegate: SliverChildBuilderDelegate( - (context, index) => ChatBubbleWidget( - text: state.chatRoomModel.messages[state.chatRoomModel.messages.length - index - 1].data, - isCurrentUser: state.chatRoomModel.users['to_chat_user']!.id != - state.chatRoomModel.messages[state.chatRoomModel.messages.length - index - 1].authorId, - mediaData: state.chatRoomModel.messages[state.chatRoomModel.messages.length - index - 1].mediaData, + body: SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Expanded( + child: Container( + color: Color(0xFFF0F2F5), + width: double.maxFinite, + child: CustomScrollView( + reverse: true, + slivers: [ + SliverPadding( + padding: EdgeInsets.symmetric(vertical: 16), + sliver: SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) => ChatBubbleWidget( + text: state.chatRoomModel.messages[state.chatRoomModel.messages.length - index - 1].data, + isCurrentUser: state.chatRoomModel.users['to_chat_user']!.id != + state.chatRoomModel.messages[state.chatRoomModel.messages.length - index - 1].authorId, + mediaData: state.chatRoomModel.messages[state.chatRoomModel.messages.length - index - 1].mediaData, + ), + childCount: state.chatRoomModel.messages.length, ), - childCount: state.chatRoomModel.messages.length, + ), + ), + ], + ), + ), + ), + Padding( + padding: EdgeInsets.symmetric(vertical: 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + SizedBox(width: 8), + InkWell( + onTap: () {}, + borderRadius: BorderRadiusStyle.circleBorder17, + child: Ink( + height: 32, + width: 32, + child: Icon( + Icons.attach_file_rounded, + size: 28, + color: Color(0xFF858E99), ), ), ), - ], - ), - ), - ), - Padding( - padding: EdgeInsets.symmetric(vertical: 8), - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - SizedBox(width: 8), - InkWell( - onTap: () {}, - borderRadius: BorderRadiusStyle.circleBorder17, - child: Ink( - height: 32, - width: 32, - child: Icon( - Icons.attach_file_rounded, - size: 28, - color: Color(0xFF858E99), - ), - ), - ), - SizedBox(width: 8), - SizedBox( - width: mediaQueryData.size.width - 96, - child: TextFormField( - maxLines: 5, - minLines: 1, - keyboardType: TextInputType.multiline, - style: TextStyle( - fontSize: 16, - fontFamily: 'Mulish', - fontWeight: FontWeight.w400, - color: Colors.black, - ), - decoration: InputDecoration( - contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 4), - hintText: 'Сообщение', - hintStyle: TextStyle( + SizedBox(width: 8), + SizedBox( + width: mediaQueryData.size.width - 96, + child: TextFormField( + maxLines: 5, + minLines: 1, + keyboardType: TextInputType.multiline, + style: TextStyle( fontSize: 16, fontFamily: 'Mulish', fontWeight: FontWeight.w400, - color: Color(0xFFAEAEB2), + color: Colors.black, ), - filled: true, - border: OutlineInputBorder( - borderRadius: BorderRadiusStyle.circleBorder17, - borderSide: BorderSide( - color: Color(0xFFD1D1D6), - width: 1, + decoration: InputDecoration( + contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 4), + hintText: 'Сообщение', + hintStyle: TextStyle( + fontSize: 16, + fontFamily: 'Mulish', + fontWeight: FontWeight.w400, + color: Color(0xFFAEAEB2), ), - ), - enabledBorder: OutlineInputBorder( - borderRadius: BorderRadiusStyle.circleBorder17, - borderSide: BorderSide( - color: Color(0xFFD1D1D6), - width: 1, + filled: true, + border: OutlineInputBorder( + borderRadius: BorderRadiusStyle.circleBorder17, + borderSide: BorderSide( + color: Color(0xFFD1D1D6), + width: 1, + ), ), - ), - focusedBorder: OutlineInputBorder( - borderRadius: BorderRadiusStyle.circleBorder17, - borderSide: BorderSide( - color: Color(0xFFD1D1D6), - width: 1, + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadiusStyle.circleBorder17, + borderSide: BorderSide( + color: Color(0xFFD1D1D6), + width: 1, + ), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadiusStyle.circleBorder17, + borderSide: BorderSide( + color: Color(0xFFD1D1D6), + width: 1, + ), ), ), ), ), - ), - SizedBox(width: 8), - InkWell( - borderRadius: BorderRadiusStyle.circleBorder17, - onTap: () {}, - child: Ink( - height: 32, - width: 32, - child: Icon( - Icons.send_outlined, - size: 28, - color: Color(0xFF858E99), + SizedBox(width: 8), + InkWell( + borderRadius: BorderRadiusStyle.circleBorder17, + onTap: () {}, + child: Ink( + height: 32, + width: 32, + child: Icon( + Icons.send_outlined, + size: 28, + color: Color(0xFF858E99), + ), ), ), - ), - SizedBox(width: 8), - ], + SizedBox(width: 8), + ], + ), ), - ), - ], + ], + ), ), ); } 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 ba44ade..d041db4 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 @@ -27,17 +27,22 @@ class ChatSelectBloc extends Bloc { List chats = []; for (int i = 0; i < chatRooms.length; i++) { String text = chatRooms[i]['last_message']['data']; - if (chatRooms[i]['last_message']['is_author_from_user']) { + if (chatRooms[i]['last_message']['is_author_message_auth_user'] != null) { text = "Вы: " + text; } - chats.add(ChatItemModel( + chats.add( + ChatItemModel( id: chatRooms[i]['id'], - userImage: chatRooms[i]['users']['to_chat_user'] - ['profile_photo_path'], + userImage: chatRooms[i]['users']['to_chat_user']['profile_photo_path'], username: chatRooms[i]['users']['to_chat_user']['name'], dateText: DateFormat('dd.MM').format( - DateTime.parse(chatRooms[i]['last_message']['updated_at'])), - greetingText: text)); + DateTime.parse( + chatRooms[i]['last_message']['updated_at'], + ), + ), + greetingText: text, + ), + ); } return chats; } @@ -75,8 +80,7 @@ class ChatSelectBloc extends Bloc { } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку - emit(ChatSelectErrorState( - 'Некоторые необходимые данные отсутствуют.')); + emit(ChatSelectErrorState('Некоторые необходимые данные отсутствуют.')); } } else { // Статус ответа не равен 200, обрабатываем ошибку 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 74911c3..60b889a 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 @@ -64,7 +64,10 @@ class ChatSelectScreen extends StatelessWidget { ), ); } else if (state is ChatSelectErrorState) { - return Center(child: Text(state.errorMessage)); + return Padding( + padding: const EdgeInsets.all(16), + child: Center(child: Text(state.errorMessage)), + ); } else { return Scaffold( body: Center( diff --git a/lib/features/chat/presentation/pages/chat_select_screen/models/chat_entry.dart b/lib/features/chat/presentation/pages/chat_select_screen/models/chat_entry.dart index 6738afb..cffee89 100644 --- a/lib/features/chat/presentation/pages/chat_select_screen/models/chat_entry.dart +++ b/lib/features/chat/presentation/pages/chat_select_screen/models/chat_entry.dart @@ -4,26 +4,23 @@ import 'package:eatvio_app/core/app_export.dart'; // ignore_for_file: must_be_immutable class ChatItemModel { - ChatItemModel( - {this.userImage, - this.username, - this.dateText, - this.greetingText, - required this.id}) { + String? userImage; + String? username; + String? dateText; + String? greetingText; + String id; + + ChatItemModel({ + this.userImage, + this.username, + this.dateText, + this.greetingText, + required this.id, + }) { userImage = userImage ?? ImageConstant.imageNotFound; username = username; dateText = dateText; greetingText = greetingText; id = id; } - - String? userImage; - - String? username; - - String? dateText; - - String? greetingText; - - String id; } diff --git a/lib/features/chat/presentation/pages/chat_select_screen/models/chat_select_model.dart b/lib/features/chat/presentation/pages/chat_select_screen/models/chat_select_model.dart index c95b52e..8a0ae04 100644 --- a/lib/features/chat/presentation/pages/chat_select_screen/models/chat_select_model.dart +++ b/lib/features/chat/presentation/pages/chat_select_screen/models/chat_select_model.dart @@ -5,9 +5,11 @@ import 'package:equatable/equatable.dart'; /// This class defines the variables used in the [chat_select_screen], /// and is typically used to hold data that is passed between different parts of the application. + class ChatSelectModel extends Equatable { ChatSelectModel({this.chatList = const []}); List chatList; + ChatSelectModel copyWith({List? chatList}) { return ChatSelectModel( chatList: chatList ?? this.chatList, 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 fbd6b1b..87a46ab 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 @@ -15,12 +15,13 @@ class ChatEntryWidget extends StatelessWidget { @override Widget build(BuildContext context) { - return GestureDetector( - onTap: () => GoRouter.of(context).goNamed( + return InkWell( + borderRadius: BorderRadiusStyle.circleBorder8, + onTap: () => GoRouter.of(context).pushNamed( 'chatScreen', extra: chatEntryObj.id.toString(), ), - child: Container( + child: Ink( padding: EdgeInsets.all(16), decoration: BoxDecoration( borderRadius: BorderRadiusStyle.circleBorder8, diff --git a/lib/features/chat/presentation/pages/photo_view_screen.dart b/lib/features/chat/presentation/pages/photo_view_screen.dart index 229ced5..f576a58 100644 --- a/lib/features/chat/presentation/pages/photo_view_screen.dart +++ b/lib/features/chat/presentation/pages/photo_view_screen.dart @@ -1,6 +1,7 @@ +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/services.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:go_router/go_router.dart'; import 'package:photo_view/photo_view.dart'; @@ -34,37 +35,32 @@ class _PhotoViewScreenState extends State { @override Widget build(BuildContext context) { - return Scaffold( - backgroundColor: Colors.black, - appBar: AppBar( - centerTitle: true, - systemOverlayStyle: SystemUiOverlayStyle( - statusBarColor: Colors.black, - statusBarBrightness: Brightness.dark, - statusBarIconBrightness: Brightness.light, + return DismissiblePage( + minScale: 1, + onDismissed: () => GoRouter.of(context).pop(), + direction: DismissiblePageDismissDirection.vertical, + isFullScreen: true, + child: PhotoViewGallery.builder( + backgroundDecoration: BoxDecoration( + color: Colors.transparent, ), - backgroundColor: Colors.black, - foregroundColor: Colors.white, - title: Text( - (imageIndex + 1).toString() + ' из ' + widget.imageUrls.length.toString(), - ), - ), - body: Dismissible( - direction: DismissDirection.vertical, - key: const Key('key'), - onDismissed: (_) => GoRouter.of(context).pop(), - resizeDuration: Duration(microseconds: 1), - child: Container( - child: PhotoViewGallery.builder( - scrollPhysics: const BouncingScrollPhysics(), - builder: (BuildContext context, int index) { - return PhotoViewGalleryPageOptions( - imageProvider: NetworkImage(widget.imageUrls[index]), - initialScale: PhotoViewComputedScale.contained, - minScale: PhotoViewComputedScale.contained, - heroAttributes: PhotoViewHeroAttributes(tag: widget.imageUrls[index]), - errorBuilder: (context, object, stackTrace) { - return Column( + scrollPhysics: const BouncingScrollPhysics(), + builder: (BuildContext context, int index) { + return PhotoViewGalleryPageOptions( + imageProvider: CachedNetworkImageProvider( + widget.imageUrls[index], + ), + initialScale: PhotoViewComputedScale.contained, + minScale: PhotoViewComputedScale.contained, + heroAttributes: PhotoViewHeroAttributes( + tag: widget.imageUrls[index], + transitionOnUserGestures: true, + ), + errorBuilder: (context, object, stackTrace) { + return Scaffold( + backgroundColor: Colors.black, + body: SafeArea( + child: Column( children: [ SizedBox(height: 32), Text('Файл'), @@ -96,28 +92,28 @@ class _PhotoViewScreenState extends State { ), ), ], - ); - }, + ), + ), ); }, - itemCount: widget.imageUrls.length, - loadingBuilder: (context, event) => Center( - child: Container( - width: 20.0, - height: 20.0, - child: CircularProgressIndicator( - value: event == null ? 0 : event.cumulativeBytesLoaded / event.expectedTotalBytes!, - ), - ), + ); + }, + itemCount: widget.imageUrls.length, + loadingBuilder: (context, event) => Center( + child: Container( + width: 20.0, + height: 20.0, + child: CircularProgressIndicator( + value: event == null ? 0 : event.cumulativeBytesLoaded / event.expectedTotalBytes!, ), - pageController: pageController, - onPageChanged: (page) { - setState(() { - imageIndex = page; - }); - }, ), ), + pageController: pageController, + onPageChanged: (page) { + setState(() { + imageIndex = page; + }); + }, ), ); } diff --git a/lib/features/chat/presentation/widgets/chat_bubble_widget.dart b/lib/features/chat/presentation/widgets/chat_bubble_widget.dart index 127795c..39a1325 100644 --- a/lib/features/chat/presentation/widgets/chat_bubble_widget.dart +++ b/lib/features/chat/presentation/widgets/chat_bubble_widget.dart @@ -1,8 +1,9 @@ import 'package:cached_network_image/cached_network_image.dart'; +import 'package:dismissible_page/dismissible_page.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:go_router/go_router.dart'; import 'package:url_launcher/url_launcher.dart'; class ChatBubbleWidget extends StatelessWidget { @@ -71,18 +72,21 @@ class ChatBubbleWidget extends StatelessWidget { } return GestureDetector( onTap: () { - GoRouter.of(context).pushNamed( - 'photoViewScreen', - extra: mediaData!.map((e) => dotenv.env['STORAGE_URL']! + e.toString()).toList(), - pathParameters: { - 'index': index.toString(), - }, + context.pushTransparentRoute( + PhotoViewScreen( + imageUrls: mediaData!.map((e) => dotenv.env['STORAGE_URL']! + e.toString()).toList(), + index: index, + ), ); }, - child: ClipRRect( - borderRadius: BorderRadiusStyle.roundedBorder8, - child: CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + '${mediaData![index]}', + child: Hero( + tag: dotenv.env['STORAGE_URL']! + '${mediaData![index]}', + transitionOnUserGestures: true, + child: ClipRRect( + borderRadius: BorderRadiusStyle.roundedBorder8, + child: CachedNetworkImage( + imageUrl: dotenv.env['STORAGE_URL']! + '${mediaData![index]}', + ), ), ), ); 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 48d1ed6..38b1561 100644 --- a/lib/presentation/profile/my_profile_screen/my_profile_screen.dart +++ b/lib/presentation/profile/my_profile_screen/my_profile_screen.dart @@ -175,13 +175,13 @@ 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)); - } + final picker = ImagePicker(); + List? images = await picker.pickMultiImage(); + if (images.isNotEmpty) { + for (var image in images) { + context.read().add(UploadAvatar(image)); } + } } onTapSettings(BuildContext context) { @@ -192,7 +192,7 @@ class MyProfileScreen extends StatelessWidget { _buildCarousel(BuildContext contex, MyProfileLoadedState state) { return CarouselSlider( - options: CarouselOptions(height: 320.0), + options: CarouselOptions(height: 340), items: [1, 2, 3].map((chartType) { return Builder( builder: (BuildContext context) { diff --git a/pubspec.yaml b/pubspec.yaml index ad2e28f..17ba3aa 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,7 +3,7 @@ description: A new Flutter project. version: 0.0.0+1 environment: - sdk: '>=3.3.4 <4.0.0' + sdk: ">=3.3.4 <4.0.0" dependencies: flutter: @@ -60,8 +60,9 @@ dependencies: dio: ^5.4.3+1 # websocket pusher_client: ^2.0.0 - # photo gallery viewer + # photo gallery viewer + dismissible page photo_view: ^0.15.0 + dismissible_page: ^1.0.2 #url launcher url_launcher: ^6.3.0 @@ -94,4 +95,4 @@ flutter: - asset: assets/fonts/MulishRegular.ttf weight: 400 - asset: assets/fonts/MulishSemiBold.ttf - weight: 600 \ No newline at end of file + weight: 600 -- 2.49.1 From 6ea4a23ad64dd550eb052738a514046ac8abbfd3 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Tue, 25 Jun 2024 16:01:52 +0300 Subject: [PATCH 004/110] feat(chat): change package for android build --- lib/main.dart | 75 +++++++++++++++++++++------------------------------ pubspec.yaml | 4 ++- 2 files changed, 34 insertions(+), 45 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index ebe2289..b907ba6 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -44,52 +44,39 @@ class MyApp extends StatelessWidget { return MultiBlocProvider( providers: [ BlocProvider(create: (context) => sl()..runInitialization()), - BlocProvider( - create: (context) => ThemeBloc(ThemeState(themeType: PrefUtils().getThemeData())), - ), - BlocProvider( - create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent()), - ), - BlocProvider( - create: (context) => FeedBloc(FeedState(myProfileModelObj: FeedModel()))..add(FeedInitialEvent()), - ), - BlocProvider( - create: (context) => DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel()))..add(DiaryEditInitialEvent()), - ), - BlocProvider( - create: (context) => ChatSelectBloc(ChatSelectState(chatSelectModelObj: ChatSelectModel()))..add(ChatSelectInitialEvent()), - ), + BlocProvider(create: (context) => ThemeBloc(ThemeState(themeType: PrefUtils().getThemeData()))), + BlocProvider(create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent())), + BlocProvider(create: (context) => FeedBloc(FeedState(myProfileModelObj: FeedModel()))..add(FeedInitialEvent())), + BlocProvider(create: (context) => DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel()))..add(DiaryEditInitialEvent())), + BlocProvider(create: (context) => ChatSelectBloc(ChatSelectState(chatSelectModelObj: ChatSelectModel()))..add(ChatSelectInitialEvent())) ], - child: BlocListener( - listener: (BuildContext context, InitializationState state) { }, - child: BlocBuilder( - builder: (context, state) { - return KeyboardDismisser( - gestures: [ - GestureType.onTap, - GestureType.onPanUpdateDownDirection, + child: BlocBuilder( + builder: (context, state) { + return KeyboardDismisser( + gestures: [ + GestureType.onTap, + GestureType.onPanUpdateDownDirection, + ], + child: MaterialApp.router( + theme: theme, + title: 'Eatvio', + routerConfig: AppRouter.appRouter, + debugShowCheckedModeBanner: false, + localizationsDelegates: [ + AppLocalizationDelegate(), + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, ], - child: MaterialApp.router( - theme: theme, - title: 'Eatvio', - routerConfig: AppRouter.appRouter, - debugShowCheckedModeBanner: false, - localizationsDelegates: [ - AppLocalizationDelegate(), - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - supportedLocales: [ - Locale( - 'ru', - '', - ), - ], - ), - ); - }, - ), + supportedLocales: [ + Locale( + 'ru', + '', + ), + ], + ), + ); + }, ), ); } diff --git a/pubspec.yaml b/pubspec.yaml index 17ba3aa..a3986db 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -59,7 +59,9 @@ dependencies: # http request dio: ^5.4.3+1 # websocket - pusher_client: ^2.0.0 + pusher_client: + git: + url: https://github.com/bihim/pusher_client # photo gallery viewer + dismissible page photo_view: ^0.15.0 dismissible_page: ^1.0.2 -- 2.49.1 From b1b6ffe0f3359f91d3c0391932918dd3d5996077 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Tue, 25 Jun 2024 16:05:55 +0300 Subject: [PATCH 005/110] feat(chat): add trailing comma rules --- analysis_options.yaml | 4 +- lib/core/utils/progress_dialog_utils.dart | 2 +- lib/core/utils/size_utils.dart | 2 +- .../bloc/chat_select_bloc.dart | 4 +- .../widgets/chat_entry_widget.dart | 4 +- lib/localization/app_localization.dart | 2 +- lib/main.dart | 5 +- .../auth/auth_screen/auth_screen.dart | 12 +- .../bloc/diary_edit_bloc.dart | 124 +++++++++--------- .../bloc/diary_edit_event.dart | 2 +- .../bloc/diary_edit_state.dart | 6 +- .../diary_edit_screen/diary_edit_screen.dart | 42 +++--- .../bloc/diet_create_bloc.dart | 10 +- .../diet_create_screen.dart | 10 +- .../diet_edit_screen/bloc/diet_edit_bloc.dart | 4 +- .../bloc/diet_edit_state.dart | 2 +- .../diet_edit_screen/diet_edit_screen.dart | 6 +- .../bloc/diet_select_bloc.dart | 4 +- .../diet_select_screen.dart | 8 +- .../diet_show_screen/diet_show_screen.dart | 8 +- .../bloc/blog_post_create_bloc.dart | 8 +- .../bloc/blog_post_create_state.dart | 4 +- .../blog_post_create_screen.dart | 4 +- .../bloc/blog_post_edit_bloc.dart | 4 +- .../bloc/blog_post_edit_state.dart | 2 +- .../blog_post_edit_screen.dart | 6 +- .../blog_post_screen/bloc/blog_post_bloc.dart | 18 +-- .../bloc/blog_post_state.dart | 6 +- .../blog_post_screen/blog_post_screen.dart | 16 +-- .../models/comment_model.dart | 2 +- .../widgets/comment_widget.dart | 4 +- .../feed/feed_screen/bloc/feed_bloc.dart | 4 +- .../feed/feed_screen/feed_screen.dart | 16 +-- .../feed_screen/widgets/feed_search_view.dart | 6 +- .../bloc/glossary_screen_bloc.dart | 12 +- .../bloc/glossary_screen_state.dart | 4 +- .../glossary_screen/glossary_screen.dart | 24 ++-- .../widgets/glossary_search_widget.dart | 6 +- .../bloc/plan_create_bloc.dart | 10 +- .../plan_create_screen.dart | 8 +- .../plan_edit_screen/bloc/plan_edit_bloc.dart | 4 +- .../bloc/plan_edit_state.dart | 2 +- .../plan_edit_screen/plan_edit_screen.dart | 6 +- .../bloc/plan_select_bloc.dart | 4 +- .../plan_select_screen.dart | 6 +- .../plan_show_screen/plan_show_screen.dart | 8 +- .../bloc/my_profile_bloc.dart | 48 +++---- .../bloc/my_profile_state.dart | 2 +- .../my_profile_screen/my_profile_screen.dart | 46 +++---- .../my_profile_screen/my_settings_screen.dart | 6 +- .../bloc/recipe_create_bloc.dart | 22 ++-- .../bloc/recipe_create_state.dart | 6 +- .../recipe_create_screen.dart | 18 +-- .../bloc/recipe_edit_bloc.dart | 8 +- .../bloc/recipe_edit_state.dart | 2 +- .../recipe_edit_screen.dart | 14 +- .../bloc/recipe_select_bloc.dart | 4 +- .../recipe_select_screen.dart | 6 +- .../bloc/recipe_show_bloc.dart | 8 +- .../bloc/recipe_show_state.dart | 6 +- .../recipe_show_screen.dart | 26 ++-- .../widgets/comment_widget.dart | 4 +- .../additional_information_screen.dart | 28 ++-- .../allergies_screen/allergies_screen.dart | 22 ++-- .../app_navigation_screen.dart | 2 +- .../bloc/blood_pressure_bloc.dart | 4 +- .../blood_pressure_screen.dart | 34 ++--- .../models/blood_pressure_model.dart | 2 +- .../bloc/body_circumferences_bloc.dart | 2 +- .../body_circumferences_screen.dart | 22 ++-- .../bloc/city_of_living_bloc.dart | 2 +- .../city_of_living_screen.dart | 22 ++-- .../models/city_of_living_model.dart | 2 +- .../bloc/credentials_bloc.dart | 2 +- .../credentials_screen.dart | 18 +-- .../date_of_birth_screen.dart | 20 +-- .../bloc/favorite_foods_bloc.dart | 2 +- .../favorite_foods_screen.dart | 28 ++-- .../favorite_sports_screen.dart | 22 ++-- .../gender_screen/gender_screen.dart | 14 +- .../gender_screen/models/gender_model.dart | 2 +- .../height_screen/bloc/height_bloc.dart | 2 +- .../height_screen/height_screen.dart | 6 +- .../height_screen/models/height_model.dart | 2 +- .../bloc/language_select_bloc.dart | 2 +- .../language_select_screen.dart | 2 +- .../medicine_intake_screen.dart | 24 ++-- .../name_screen/bloc/name_bloc.dart | 2 +- .../registration/name_screen/name_screen.dart | 18 +-- .../splash_screen/splash_screen.dart | 8 +- .../weight_screen/bloc/weight_bloc.dart | 2 +- .../weight_screen/models/weight_model.dart | 2 +- .../weight_screen/weight_screen.dart | 6 +- lib/theme/theme_helper.dart | 8 +- lib/widgets/bottom_navigation_bar_widget.dart | 2 +- lib/widgets/custom_about_list.dart | 4 +- lib/widgets/custom_expandable_list.dart | 28 ++-- lib/widgets/custom_hyper_switch.dart | 2 +- lib/widgets/custom_hypo_switch.dart | 2 +- lib/widgets/custom_icon_button.dart | 2 +- lib/widgets/custom_navigation_menu_item.dart | 2 +- lib/widgets/custom_notification_screen.dart | 2 +- test/add_info_test.dart | 2 +- test/allergies_test.dart | 2 +- test/blood_pressure_test.dart | 2 +- test/body_circumferences_test.dart | 2 +- test/city_of_living_test.dart | 2 +- test/credentials_test.dart | 2 +- test/date_of_birth_test.dart | 2 +- test/diary_test.dart | 2 +- test/favorite_foods_test.dart | 2 +- test/favorite_sports_test.dart | 2 +- test/gender_test.dart | 2 +- test/height_test.dart | 2 +- test/language_select_test.dart | 2 +- test/medicine_intake_test.dart | 2 +- test/name_test.dart | 2 +- test/profile_test.dart | 2 +- test/settings_test.dart | 2 +- test/weight_test.dart | 2 +- 120 files changed, 549 insertions(+), 546 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index 22f0401..ee44716 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -27,7 +27,9 @@ dart_code_metrics: # maximum-nesting-level: 5 # metrics-exclude: # - test/** -# rules: +linter: + rules: + require_trailing_commas: true # - newline-before-return # - no-boolean-literal-compare # - no-empty-block diff --git a/lib/core/utils/progress_dialog_utils.dart b/lib/core/utils/progress_dialog_utils.dart index ce4da75..98cdac0 100644 --- a/lib/core/utils/progress_dialog_utils.dart +++ b/lib/core/utils/progress_dialog_utils.dart @@ -19,7 +19,7 @@ class ProgressDialogUtils { ), ), ); - }); + },); isProgressVisible = true; } } diff --git a/lib/core/utils/size_utils.dart b/lib/core/utils/size_utils.dart index a6de3e6..5595377 100644 --- a/lib/core/utils/size_utils.dart +++ b/lib/core/utils/size_utils.dart @@ -3,7 +3,7 @@ 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. 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 d041db4..9bd2845 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 @@ -71,12 +71,12 @@ class ChatSelectBloc extends Bloc { emit(currentState.copyWith( chatSelectModelObj: currentState.chatSelectModelObj, chatRooms: currentState.chatRooms, - )); + ),); } else { emit(ChatSelectLoadedState( chatRooms: fillChatEntryList(data['chatRooms']), //chatRooms: [], - )); + ),); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку 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 87a46ab..334aa65 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 @@ -75,7 +75,7 @@ class ChatEntryWidget extends StatelessWidget { chatEntryObj.dateText!, style: theme.textTheme.bodyMedium, ), - ) + ), ], ), SizedBox(height: 6.v), @@ -85,7 +85,7 @@ class ChatEntryWidget extends StatelessWidget { ), ], ), - ) + ), ], ), ), diff --git a/lib/localization/app_localization.dart b/lib/localization/app_localization.dart index 2fc106d..5d003fc 100644 --- a/lib/localization/app_localization.dart +++ b/lib/localization/app_localization.dart @@ -26,7 +26,7 @@ class AppLocalization { return AppLocalization(Locale( 'ru', '', - )); // Возвращаем дефолтное значение или обработку ошибки + ),); // Возвращаем дефолтное значение или обработку ошибки } } diff --git a/lib/main.dart b/lib/main.dart index b907ba6..e1f081e 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,6 +1,5 @@ import 'package:eatvio_app/app_router.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.dart'; -import 'package:eatvio_app/core/initialization_cubit/initialization_state.dart'; 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/locator_service.dart'; @@ -48,7 +47,9 @@ class MyApp extends StatelessWidget { BlocProvider(create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent())), BlocProvider(create: (context) => FeedBloc(FeedState(myProfileModelObj: FeedModel()))..add(FeedInitialEvent())), BlocProvider(create: (context) => DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel()))..add(DiaryEditInitialEvent())), - BlocProvider(create: (context) => ChatSelectBloc(ChatSelectState(chatSelectModelObj: ChatSelectModel()))..add(ChatSelectInitialEvent())) + BlocProvider( + create: (context) => ChatSelectBloc(ChatSelectState(chatSelectModelObj: ChatSelectModel()))..add(ChatSelectInitialEvent()), + ), ], child: BlocBuilder( builder: (context, state) { diff --git a/lib/presentation/auth/auth_screen/auth_screen.dart b/lib/presentation/auth/auth_screen/auth_screen.dart index 9694a2c..4a74ba3 100644 --- a/lib/presentation/auth/auth_screen/auth_screen.dart +++ b/lib/presentation/auth/auth_screen/auth_screen.dart @@ -50,7 +50,7 @@ class AuthScreen extends StatelessWidget { 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), @@ -61,7 +61,7 @@ class AuthScreen extends StatelessWidget { obscureText: true, controller: passwordController, ); - }), + },), SizedBox(height: 50.v), NextStepButton( text: "no_account".tr.toUpperCase(), @@ -86,9 +86,9 @@ class AuthScreen extends StatelessWidget { text: "authentificate".tr.toUpperCase(), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapAuth(state, context)); - }), - ])))); + onPressed: onTapAuth(state, context),); + },), + ],),),),); } onTapAuth(AuthState state, BuildContext context) { @@ -100,7 +100,7 @@ class AuthScreen extends StatelessWidget { '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); + headers: {'Content-Type': 'application/json'}, body: json.encode(credentials), encoding: utf8,); print(response.statusCode); if (response.statusCode == 200) { var res = await jsonDecode(response.body); 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 4474110..591cad6 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 @@ -29,15 +29,15 @@ class DiaryEditBloc extends Bloc { on(_addPortion); //пользователь нажимает "Добавить продукт" on(_removePortion); on( - _removeImage); // пользователь нажимает на крестик около продукта + _removeImage,); // пользователь нажимает на крестик около продукта on(_uploadImages); //пользователь нажимает "Добавить фото" on(_addComment); //пользователь нажимает "Добавить комментарий" on( - _inputProduct); //пользователь нажимает "Добавить комментарий" + _inputProduct,); //пользователь нажимает "Добавить комментарий" on(_finishDay); //пользователь нажимает "Добавить комментарий" on(_sendModeration); on( - reloadScreen); //пользователь нажимает "Добавить комментарий" + reloadScreen,); //пользователь нажимает "Добавить комментарий" on(_clearInput); } @@ -89,7 +89,7 @@ class DiaryEditBloc extends Bloc { recommendedChartValues: currentState.recommendedChartValues, consumedChartValues: currentState.consumedChartValues, autocompleteList: currentState.autocompleteList, - diaryEditModelObj: currentState.diaryEditModelObj)); + diaryEditModelObj: currentState.diaryEditModelObj,),); } else { // Если текущее состояние - начальное, создаем новое загруженное состояние final List meals = @@ -97,7 +97,7 @@ class DiaryEditBloc extends Bloc { emit(DiaryEditLoadedState( currentMeal: meals[0], portionController: SelectionPopupModel( - id: 0, title: "порций", isSelected: true), + id: 0, title: "порций", isSelected: true,), wakeupExpanded: true, moodExpanded: true, moderationExpanded: false, @@ -125,7 +125,7 @@ class DiaryEditBloc extends Bloc { diaryDate: diaryDate, autocompleteList: [], diaryEditModelObj: state.diaryEditModelObj - ?.copyWith(mealList: meals, portionList: fillPortions()))); + ?.copyWith(mealList: meals, portionList: fillPortions()),),); } } } catch (e) { @@ -177,10 +177,10 @@ class DiaryEditBloc extends Bloc { } fetchChartValues( - String token, int diaryID, Emitter emit) async { + String token, int diaryID, Emitter emit,) async { final responseChart = await http.get( Uri.parse( - dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/dailyNutritionData/'), + dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/dailyNutritionData/',), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $token', @@ -250,7 +250,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/'), + '/diary/$diaryId/dailyNutritionData/',), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $token', @@ -258,7 +258,7 @@ class DiaryEditBloc extends Bloc { ); if (responseChart.statusCode == 200) { final recommendedChartValues = jsonDecode( - responseChart.body)['dailyNutritionRecommendation']; + responseChart.body,)['dailyNutritionRecommendation']; final consumedChartValues = jsonDecode(responseChart.body)['dailyNutritionIntake']; final List meals = @@ -266,10 +266,10 @@ class DiaryEditBloc extends Bloc { try { await Future(() => emit(DiaryEditLoadedState( diaryEditModelObj: state.diaryEditModelObj?.copyWith( - mealList: meals, portionList: fillPortions()), + mealList: meals, portionList: fillPortions(),), currentMeal: meals[0], portionController: SelectionPopupModel( - id: 0, title: "порций", isSelected: true), + id: 0, title: "порций", isSelected: true,), wakeupExpanded: true, moodExpanded: true, moderationExpanded: false, @@ -301,7 +301,7 @@ class DiaryEditBloc extends Bloc { diaryDate: diaryDate, isLoading: false, autocompleteList: [], - ))); + ),),); print("Updated"); } catch (e) { @@ -312,11 +312,11 @@ class DiaryEditBloc extends Bloc { } } else { emit(DiaryEditErrorState( - 'Ошибка при декодировании данных дневника')); + 'Ошибка при декодировании данных дневника',),); } } else { emit( - DiaryEditErrorState('Некоторые необходимые данные отсутствуют.')); + DiaryEditErrorState('Некоторые необходимые данные отсутствуют.'),); } } else { emit(DiaryEditErrorState('Ошибка сервера: ${response.statusCode}')); @@ -327,7 +327,7 @@ class DiaryEditBloc extends Bloc { } Future _changeSatiety( - ChangeSatiety event, Emitter emit) async { + ChangeSatiety event, Emitter emit,) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; var updatedState = @@ -338,7 +338,7 @@ class DiaryEditBloc extends Bloc { currentState.token, event.selectedElement, currentState.currentMeal?.id, - currentState.diaryId); + currentState.diaryId,); if (response.statusCode == 200) { updatedState.selectedSatiety = event.selectedElement; @@ -364,12 +364,12 @@ class DiaryEditBloc extends Bloc { 'Authorization': 'Bearer $token', }, body: json.encode(credentials), - encoding: utf8); + encoding: utf8,); return response; } Future _changeMood( - ChangeMood event, Emitter emit) async { + ChangeMood event, Emitter emit,) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; var updatedState = @@ -380,11 +380,11 @@ class DiaryEditBloc extends Bloc { currentState.token, event.selectedElement, currentState.currentMeal?.id, - currentState.diaryId); + currentState.diaryId,); if (response.statusCode == 200) { print( - 'Mood change success! meal_id: ${currentState.currentMeal?.id}, mood: ${event.selectedElement}'); + 'Mood change success! meal_id: ${currentState.currentMeal?.id}, mood: ${event.selectedElement}',); updatedState.selectedMood = event.selectedElement; emit(updatedState); // Передаем обновленное состояние в emit } @@ -409,17 +409,17 @@ class DiaryEditBloc extends Bloc { 'Authorization': 'Bearer $token', }, body: json.encode(credentials), - encoding: utf8); + encoding: utf8,); return response; } FutureOr _changeWakeup( - WakeupEvent event, Emitter emit) async { + WakeupEvent event, Emitter emit,) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; var response = await sendWakeupData( - currentState.token, event.selectedTime, currentState.diaryId); + currentState.token, event.selectedTime, currentState.diaryId,); if (response.statusCode == 200) { await reloadScreen(event, emit); var updatedState = @@ -432,11 +432,11 @@ class DiaryEditBloc extends Bloc { } FutureOr _changeRetire( - RetireEvent event, Emitter emit) async { + RetireEvent event, Emitter emit,) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; var response = await sendRetireData( - currentState.token, event.selectedTime, currentState.diaryId); + currentState.token, event.selectedTime, currentState.diaryId,); if (response.statusCode == 200) { await reloadScreen(event, emit); var updatedState = @@ -467,13 +467,13 @@ class DiaryEditBloc extends Bloc { 'Authorization': 'Bearer $token', }, body: json.encode(credentials), - encoding: utf8); + encoding: utf8,); return response; } Future sendRetireData( - String? token, TimeOfDay retire, int diaryID) async { + String? token, TimeOfDay retire, int diaryID,) async { String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill'; final formatter = DateFormat('HH:mm'); final retireString = @@ -488,13 +488,13 @@ class DiaryEditBloc extends Bloc { 'Authorization': 'Bearer $token', }, body: json.encode(credentials), - encoding: utf8); + encoding: utf8,); return response; } FutureOr _changeMealTime( - ChangeMealTime event, Emitter emit) async { + ChangeMealTime event, Emitter emit,) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; var updatedState = currentState.copyWith(mealTimeController: event.time); @@ -522,18 +522,18 @@ class DiaryEditBloc extends Bloc { 'Authorization': 'Bearer $token', }, body: json.encode(credentials), - encoding: utf8); + encoding: utf8,); return response; } FutureOr _changeMeal( - ChangeMeal event, Emitter emit) async { + ChangeMeal event, Emitter emit,) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; final meal = currentState.meals?.firstWhere( (meal) => meal['id'] == event.value.id, - orElse: () => null); + orElse: () => null,); int? id = event.value.id; print(meal['photos']); DiaryEditLoadedState updatedState = currentState.copyWith( @@ -542,7 +542,7 @@ class DiaryEditBloc extends Bloc { photos: meal['photos'], mealTimeController: toTime(meal['time'] ?? "1$id:00"), selectedMood: meal['mood'], - selectedSatiety: meal['satiety']); + selectedSatiety: meal['satiety'],); print(updatedState.photos); emit(updatedState); } @@ -550,7 +550,7 @@ class DiaryEditBloc extends Bloc { FutureOr _clearInput( - ClearInput event, Emitter emit) { + ClearInput event, Emitter emit,) { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; DiaryEditLoadedState updatedState = currentState.copyWith( @@ -560,7 +560,7 @@ class DiaryEditBloc extends Bloc { } FutureOr _changePortion( - ChangePortion event, Emitter emit) { + ChangePortion event, Emitter emit,) { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; DiaryEditLoadedState updatedState = currentState.copyWith( @@ -571,7 +571,7 @@ class DiaryEditBloc extends Bloc { } FutureOr _toggleMood( - ToggleMoodExpandedEvent event, Emitter emit) { + ToggleMoodExpandedEvent event, Emitter emit,) { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; @@ -581,7 +581,7 @@ class DiaryEditBloc extends Bloc { } FutureOr _toggleWakeup( - ToggleWakeupExpandedEvent event, Emitter emit) { + ToggleWakeupExpandedEvent event, Emitter emit,) { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; @@ -591,7 +591,7 @@ class DiaryEditBloc extends Bloc { } FutureOr _addPortion( - AddPortionEvent event, Emitter emit) async { + AddPortionEvent event, Emitter emit,) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; @@ -609,13 +609,13 @@ class DiaryEditBloc extends Bloc { await reloadScreen(event, emit); } else { print( - 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}'); + 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}',); } } } FutureOr sendPortionData(String? token, String? name, - String portion, int? quantity, int? mealID, int diaryID) async { + String portion, int? quantity, int? mealID, int diaryID,) async { String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/create'; @@ -639,14 +639,14 @@ class DiaryEditBloc extends Bloc { } Future _inputProduct( - ProductInput event, Emitter emit) async { + ProductInput event, Emitter emit,) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; String? token = currentState.token; final Map credentials = {'name': event.input}; final uri = Uri.parse( - '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/filter?${Uri(queryParameters: credentials).query}'); + '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/filter?${Uri(queryParameters: credentials).query}',); final response = await http.get( uri, @@ -679,7 +679,7 @@ class DiaryEditBloc extends Bloc { } Future _removePortion( - RemovePortionEvent event, Emitter emit) async { + RemovePortionEvent event, Emitter emit,) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; @@ -697,13 +697,13 @@ class DiaryEditBloc extends Bloc { await reloadScreen(event, emit); } else { print( - 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}'); + 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}',); } } } Future sendRemovePortion( - String? token, int? portionID, int? mealID, int diaryID) async { + String? token, int? portionID, int? mealID, int diaryID,) async { String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete'; @@ -720,7 +720,7 @@ class DiaryEditBloc extends Bloc { } FutureOr _removeImage( - RemoveImageEvent event, Emitter emit) async { + RemoveImageEvent event, Emitter emit,) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; @@ -736,13 +736,13 @@ class DiaryEditBloc extends Bloc { await reloadScreen(event, emit); } else { print( - 'Failed to remove photo. Status Code: ${response.statusCode} ${response.body}'); + 'Failed to remove photo. Status Code: ${response.statusCode} ${response.body}',); } } } Future sendRemovePhoto(String? token, String? path, - String? photoID, int? mealID, int diaryID) async { + String? photoID, int? mealID, int diaryID,) async { String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete'; final Map credentials = { @@ -781,7 +781,7 @@ class DiaryEditBloc extends Bloc { } Future sendFinishDay(String? token, int diaryID, - TimeOfDay? wakeup, TimeOfDay? retire, String? comment) async { + TimeOfDay? wakeup, TimeOfDay? retire, String? comment,) async { final formatter = DateFormat('HH:mm'); final wakeupString = formatter.format(DateTime(2022, 1, 1, wakeup!.hour, wakeup.minute)); @@ -810,19 +810,19 @@ class DiaryEditBloc extends Bloc { } Future _uploadImages( - UploadImages event, Emitter emit) async { + UploadImages event, Emitter emit,) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; emit(currentState.copyWith(isLoading: true)); await uploadImageToServer(event.image.path, currentState.diaryId, - currentState.currentMeal!.id!, currentState.token); + currentState.currentMeal!.id!, currentState.token,); await reloadScreen(event, emit); } } Future uploadImageToServer( - String imagePath, int diaryID, int mealId, String? token) async { + String imagePath, int diaryID, int mealId, String? token,) async { String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload'; @@ -841,12 +841,12 @@ class DiaryEditBloc extends Bloc { return imageUrl; } else { throw Exception( - 'Failed to upload image. Status code: ${streamedResponse.statusCode}}'); + 'Failed to upload image. Status code: ${streamedResponse.statusCode}}',); } } FutureOr _sendModeration( - SendModeration event, Emitter emit) async { + SendModeration event, Emitter emit,) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; final response = await _sendModerationData( @@ -871,9 +871,9 @@ class DiaryEditBloc extends Bloc { String proteins_on_100gr, String fats_on_100gr, String carbohydrates_on_100gr, - String? token) async { + String? token,) async { final Uri url = Uri.parse( - '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/sendToModeration'); + '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/sendToModeration',); final Uri serverURL = Uri.parse('${dotenv.env['SERVER_ROOT']!}'); String host = serverURL.host; final Map credentials = { @@ -901,12 +901,12 @@ class DiaryEditBloc extends Bloc { return response; } else { throw Exception( - 'Failed to send a product for moderation ${response.statusCode}'); + 'Failed to send a product for moderation ${response.statusCode}',); } } FutureOr _addComment( - AddComment event, Emitter emit) async { + AddComment event, Emitter emit,) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; var updatedState = currentState.copyWith( @@ -915,7 +915,7 @@ class DiaryEditBloc extends Bloc { // Отправляем данные по HTTP маршруту и ждем ответ var response = await sendCommentData( - currentState.token, event.comment, currentState.diaryId); + currentState.token, event.comment, currentState.diaryId,); if (response.statusCode == 200) { emit(updatedState); // Передаем обновленное состояние в emit @@ -924,7 +924,7 @@ class DiaryEditBloc extends Bloc { } Future sendCommentData( - String? token, String comment, int diaryID) async { + String? token, String comment, int diaryID,) async { String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill'; final Map credentials = { 'comment': comment, @@ -936,7 +936,7 @@ class DiaryEditBloc extends Bloc { 'Authorization': 'Bearer $token', }, body: json.encode(credentials), - encoding: utf8); + encoding: utf8,); return response; } 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 8185fa2..c2c5dad 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 @@ -159,7 +159,7 @@ class SendModeration extends DiaryEditEvent { required this.energyOn100gr, required this.proteinsOn100gr, required this.fatsOn100gr, - required this.carbohydratesOn100gr}); + required this.carbohydratesOn100gr,}); String name; String energyOn100gr; String proteinsOn100gr; diff --git a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart index 61762f0..fc8e197 100644 --- a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart +++ b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart @@ -47,7 +47,7 @@ class DiaryEditLoadedState extends DiaryEditState { required this.selectedSatiety, required this.moderationExpanded, required this.wakeupExpanded, - required this.moodExpanded}) + required this.moodExpanded,}) : super(diaryEditModelObj: null); DiaryEditModel? diaryEditModelObj; @@ -109,7 +109,7 @@ class DiaryEditLoadedState extends DiaryEditState { moderationExpanded, isLoading, isAdded, - currentMeal + currentMeal, ]; DiaryEditLoadedState copyWith({ DiaryEditModel? diaryEditModelObj, @@ -174,7 +174,7 @@ class DiaryEditLoadedState extends DiaryEditState { moderationExpanded: moderationExpanded ?? this.moderationExpanded, moodExpanded: moodExpanded ?? this.moodExpanded, isAdded: isAdded ?? this.isAdded, - isLoading: isLoading ?? this.isLoading); + isLoading: isLoading ?? this.isLoading,); } } 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 e2be948..77aa77f 100644 --- a/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart +++ b/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart @@ -21,7 +21,7 @@ class DiaryEditScreen extends StatelessWidget { static Widget builder(BuildContext context) { return BlocProvider( - create: (context) => DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel()))..add(DiaryEditInitialEvent()), child: DiaryEditScreen()); + create: (context) => DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel()))..add(DiaryEditInitialEvent()), child: DiaryEditScreen(),); } Widget build(BuildContext context) { @@ -221,7 +221,7 @@ class DiaryEditScreen extends StatelessWidget { Icon( Icons.photo_library, color: appTheme.blueGray300, - ) + ), ], ), ), @@ -332,7 +332,7 @@ class DiaryEditScreen extends StatelessWidget { defaultValue: diaryEditModelObj?.mealList[0], onChanged: changeMeal(context, state), ); - })), + },),), SizedBox(height: 20.v), Padding( padding: EdgeInsets.symmetric(horizontal: 10.h), @@ -381,7 +381,7 @@ class DiaryEditScreen extends StatelessWidget { ), ), ); - }), + },), ), SizedBox(height: 20.v), if (state.moderationExpanded) @@ -492,9 +492,9 @@ class DiaryEditScreen extends StatelessWidget { return Container(); // Возвращаем пустой контейнер, если состояние не является DiaryEditLoadedState } }, - ) + ), ], - )); + ),); } openCaloriesDialog(BuildContext context, DiaryEditLoadedState state) { @@ -543,7 +543,7 @@ class DiaryEditScreen extends StatelessWidget { ), TextButton( onPressed: triggerModeration(context, state.productNameController!.text, state.caloriesController!.text, state.proteinsController!.text, - state.fatsController!.text, state.carbsController!.text, dialogContext), + state.fatsController!.text, state.carbsController!.text, dialogContext,), child: Text('Отправить'), ), ], @@ -553,11 +553,11 @@ class DiaryEditScreen extends StatelessWidget { } triggerModeration(BuildContext context, String name, String energyOn100gr, String proteinsOn100gr, String fatsOn100gr, String carbohydratesOn100gr, - BuildContext dialogContext) { + BuildContext dialogContext,) { return () { // Call function to send moderation with the entered values context.read().add(SendModeration( - name: name, energyOn100gr: energyOn100gr, proteinsOn100gr: proteinsOn100gr, fatsOn100gr: fatsOn100gr, carbohydratesOn100gr: carbohydratesOn100gr)); + name: name, energyOn100gr: energyOn100gr, proteinsOn100gr: proteinsOn100gr, fatsOn100gr: fatsOn100gr, carbohydratesOn100gr: carbohydratesOn100gr,),); Navigator.of(dialogContext).pop(); // Dismiss the dialog }; } @@ -647,7 +647,7 @@ class DiaryEditScreen extends StatelessWidget { child: Text( portion['product_name'].length > 8 ? portion['product_name'].substring(0, 8) : portion['product_name'], style: CustomTextStyles.titleMedium16, - )), + ),), Padding( padding: EdgeInsets.only( left: 20.h, @@ -667,7 +667,7 @@ class DiaryEditScreen extends StatelessWidget { Icons.close, color: appTheme.blueGray300, ), - )), + ),), ], ), ); @@ -783,26 +783,26 @@ class DiaryEditScreen extends StatelessWidget { BarChartRodData( toY: consumedValues[0] / recommendedValues[0] * 100, color: checkConsumedValues([recommendedValues[0]], [consumedValues[1]]) ? Colors.red : Colors.blue, - ) - ]), + ), + ],), BarChartGroupData(x: 1, barRods: [ BarChartRodData( toY: consumedValues[1] / recommendedValues[1] * 100, color: checkConsumedValues([recommendedValues[1]], [consumedValues[1]]) ? Colors.red : Colors.blue, - ) - ]), + ), + ],), BarChartGroupData(x: 2, barRods: [ BarChartRodData( toY: consumedValues[2] / recommendedValues[2] * 100, color: checkConsumedValues([recommendedValues[2]], [consumedValues[2]]) ? Colors.red : Colors.blue, - ) - ]), + ), + ],), BarChartGroupData(x: 3, barRods: [ BarChartRodData( toY: consumedValues[3] / recommendedValues[3] * 100, color: checkConsumedValues([recommendedValues[3]], [consumedValues[3]]) ? Colors.red : Colors.blue, - ) - ]), + ), + ],), ], ), ), @@ -909,7 +909,7 @@ class DiaryEditScreen extends StatelessWidget { Text( "*Превышенная суточная норма", style: theme.textTheme.labelLarge, - ) + ), ], ), ); @@ -1147,7 +1147,7 @@ class DiaryEditScreen extends StatelessWidget { // Остальные элементы шкалы ], ), - ])); + ],),); } changeMood(BuildContext context, int satiety) { 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 e4e0cbc..a28b79d 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 @@ -36,17 +36,17 @@ class DietCreateBloc extends Bloc { dietModelObj: currentState.dietModelObj, name: currentState.name, details: currentState.details, - )); + ),); } else { 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 +59,7 @@ 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}',); } } } @@ -77,7 +77,7 @@ class DietCreateBloc extends Bloc { 'state': 'active', 'type': '{"meat": true}', 'daily_schedule': - '{"1": {"lunch": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 494}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 12}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 432}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 195}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 710}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "grams", "quantity": 119}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 287}], "snacks": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 445}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "grams", "quantity": 500}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 764}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 735}], "breakfast": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 127}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 89}]}, "2": {"lunch": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 436}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 700}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 766}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 194}], "dinner": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 426}], "snacks": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 58}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 152}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 925}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 224}], "breakfast": [{"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 918}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 81}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 308}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 579}]}, "3": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 266}], "dinner": [{"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 790}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 26}], "snacks": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 549}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 446}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "grams", "quantity": 406}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 92}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 403}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 894}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 457}]}, "4": {"lunch": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 698}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 43}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 994}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 965}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 42}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 948}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 28}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 54}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 112}], "supper": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 891}], "breakfast": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 538}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 635}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "pcs", "quantity": 586}]}, "5": {"lunch": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 900}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "milliliters", "quantity": 242}], "dinner": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 375}], "snacks": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 604}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 510}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 887}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 554}], "supper": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 731}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 574}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 274}], "breakfast": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 276}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 80}]}, "6": {"lunch": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 359}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 358}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 639}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 861}], "dinner": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 124}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 122}], "snacks": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 980}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 837}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 444}], "supper": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 577}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 706}], "breakfast": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 839}]}, "7": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 118}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 664}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 665}], "dinner": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 986}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 296}], "snacks": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 807}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 493}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "milliliters", "quantity": 227}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 385}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 448}], "breakfast": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 784}]}, "8": {"lunch": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 433}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 871}], "dinner": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 332}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 41}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 388}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 649}], "supper": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 114}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "milliliters", "quantity": 968}], "breakfast": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 180}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 269}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 998}]}, "9": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 68}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 505}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 554}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 579}], "snacks": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 751}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 144}], "supper": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 677}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 263}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "pcs", "quantity": 304}], "breakfast": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 963}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 258}]}, "10": {"lunch": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 167}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 306}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 243}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 79}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 560}], "snacks": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 294}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 145}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 639}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 108}], "supper": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 924}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 894}], "breakfast": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 280}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 336}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 338}]}, "11": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 817}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 968}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 525}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 864}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 457}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 548}], "snacks": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 658}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 239}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 358}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 406}], "supper": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "grams", "quantity": 416}], "breakfast": [{"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 220}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 323}]}, "12": {"lunch": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 377}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 138}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 654}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 237}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 902}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 76}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 723}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 481}], "breakfast": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 571}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 515}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 188}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 411}]}, "13": {"lunch": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 379}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 231}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 376}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 147}], "dinner": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 871}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 679}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 359}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 561}], "snacks": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 414}], "supper": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 827}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 649}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 363}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 161}], "breakfast": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 185}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 464}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 387}]}, "14": {"lunch": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 248}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 5}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 693}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 655}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 709}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 881}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 588}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 36}], "snacks": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 453}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 692}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 186}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 721}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 740}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 731}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 842}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 850}]}, "15": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 124}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 380}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 211}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 689}], "dinner": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 326}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 629}], "snacks": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 201}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 129}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 749}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 315}], "breakfast": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 444}]}, "16": {"lunch": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 953}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 101}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 684}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 506}], "dinner": [{"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 333}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 416}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 796}], "snacks": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 799}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 799}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 756}], "supper": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 858}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 619}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 800}], "breakfast": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 363}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 539}]}, "17": {"lunch": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 134}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 977}], "snacks": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 211}], "supper": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 209}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "grams", "quantity": 227}], "breakfast": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 195}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 917}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 706}]}, "18": {"lunch": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "pcs", "quantity": 296}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 239}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 798}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 155}], "dinner": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 959}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 958}], "snacks": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 984}], "supper": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 134}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 432}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 242}]}, "19": {"lunch": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 906}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 152}], "dinner": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 610}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 605}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 498}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 616}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 512}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 146}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 200}], "supper": [{"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 764}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 353}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 181}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 783}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 506}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 887}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 130}]}, "20": {"lunch": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 48}], "dinner": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 266}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 143}], "snacks": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 55}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 174}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 855}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 6}], "supper": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 296}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 878}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 376}], "breakfast": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 442}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 528}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "milliliters", "quantity": 558}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 885}]}, "21": {"lunch": [{"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 504}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 652}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 996}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 200}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 641}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 87}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 689}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 143}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 528}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 475}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 924}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 98}], "breakfast": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 438}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 383}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 462}]}}' + '{"1": {"lunch": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 494}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 12}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 432}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 195}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 710}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "grams", "quantity": 119}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 287}], "snacks": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 445}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "grams", "quantity": 500}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 764}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 735}], "breakfast": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 127}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 89}]}, "2": {"lunch": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 436}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 700}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 766}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 194}], "dinner": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 426}], "snacks": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 58}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 152}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 925}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 224}], "breakfast": [{"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 918}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 81}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 308}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 579}]}, "3": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 266}], "dinner": [{"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 790}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 26}], "snacks": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 549}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 446}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "grams", "quantity": 406}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 92}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 403}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 894}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 457}]}, "4": {"lunch": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 698}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 43}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 994}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 965}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 42}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 948}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 28}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 54}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 112}], "supper": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 891}], "breakfast": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 538}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 635}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "pcs", "quantity": 586}]}, "5": {"lunch": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 900}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "milliliters", "quantity": 242}], "dinner": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 375}], "snacks": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 604}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 510}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 887}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 554}], "supper": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 731}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 574}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 274}], "breakfast": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 276}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 80}]}, "6": {"lunch": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 359}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 358}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 639}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 861}], "dinner": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 124}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 122}], "snacks": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 980}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 837}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 444}], "supper": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 577}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 706}], "breakfast": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 839}]}, "7": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 118}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 664}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 665}], "dinner": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 986}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 296}], "snacks": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 807}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 493}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "milliliters", "quantity": 227}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 385}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 448}], "breakfast": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 784}]}, "8": {"lunch": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 433}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 871}], "dinner": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 332}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 41}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 388}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 649}], "supper": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 114}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "milliliters", "quantity": 968}], "breakfast": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 180}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 269}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 998}]}, "9": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 68}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 505}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 554}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 579}], "snacks": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 751}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 144}], "supper": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 677}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 263}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "pcs", "quantity": 304}], "breakfast": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 963}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 258}]}, "10": {"lunch": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 167}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 306}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 243}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 79}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 560}], "snacks": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 294}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 145}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 639}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 108}], "supper": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 924}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 894}], "breakfast": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 280}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 336}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 338}]}, "11": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 817}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 968}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 525}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 864}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 457}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 548}], "snacks": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 658}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 239}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 358}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 406}], "supper": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "grams", "quantity": 416}], "breakfast": [{"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 220}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 323}]}, "12": {"lunch": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 377}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 138}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 654}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 237}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 902}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 76}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 723}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 481}], "breakfast": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 571}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 515}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 188}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 411}]}, "13": {"lunch": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 379}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 231}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 376}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 147}], "dinner": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 871}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 679}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 359}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 561}], "snacks": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 414}], "supper": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 827}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 649}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 363}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 161}], "breakfast": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 185}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 464}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 387}]}, "14": {"lunch": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 248}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 5}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 693}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 655}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 709}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 881}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 588}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 36}], "snacks": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 453}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 692}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 186}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 721}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 740}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 731}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 842}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 850}]}, "15": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 124}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 380}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 211}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 689}], "dinner": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 326}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 629}], "snacks": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 201}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 129}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 749}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 315}], "breakfast": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 444}]}, "16": {"lunch": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 953}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 101}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 684}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 506}], "dinner": [{"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 333}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 416}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 796}], "snacks": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 799}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 799}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 756}], "supper": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 858}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 619}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 800}], "breakfast": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 363}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 539}]}, "17": {"lunch": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 134}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 977}], "snacks": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 211}], "supper": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 209}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "grams", "quantity": 227}], "breakfast": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 195}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 917}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 706}]}, "18": {"lunch": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "pcs", "quantity": 296}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 239}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 798}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 155}], "dinner": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 959}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 958}], "snacks": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 984}], "supper": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 134}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 432}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 242}]}, "19": {"lunch": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 906}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 152}], "dinner": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 610}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 605}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 498}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 616}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 512}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 146}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 200}], "supper": [{"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 764}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 353}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 181}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 783}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 506}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 887}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 130}]}, "20": {"lunch": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 48}], "dinner": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 266}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 143}], "snacks": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 55}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 174}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 855}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 6}], "supper": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 296}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 878}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 376}], "breakfast": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 442}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 528}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "milliliters", "quantity": 558}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 885}]}, "21": {"lunch": [{"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 504}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 652}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 996}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 200}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 641}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 87}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 689}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 143}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 528}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 475}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 924}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 98}], "breakfast": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 438}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 383}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 462}]}}', }; var response = await http.post( 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 516a931..619e8f7 100644 --- a/lib/presentation/diets/diet_create_screen/diet_create_screen.dart +++ b/lib/presentation/diets/diet_create_screen/diet_create_screen.dart @@ -10,7 +10,7 @@ class DietCreateScreen extends StatelessWidget { final dietID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( create: (context) => DietCreateBloc(DietCreateState(dietModelObj: DietCreateModel(dietID: dietID.toString())))..add(DietCreateInitialEvent()), - child: DietCreateScreen()); + child: DietCreateScreen(),); } Widget build(BuildContext context) { @@ -80,10 +80,10 @@ class DietCreateScreen extends StatelessWidget { 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 e69101c..22cc1aa 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 @@ -49,13 +49,13 @@ class DietEditBloc extends Bloc { diet: currentState.diet, name: currentState.name, duration: currentState.duration, - details: currentState.details)); + details: currentState.details,),); } else { 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 { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку 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 1c10a40..bfc5e24 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 @@ -23,7 +23,7 @@ class DietEditState extends Equatable { class DietEditLoadedState extends DietEditState { DietEditLoadedState( - {this.dietModelObj, this.diet, this.name, this.details, this.duration}); + {this.dietModelObj, this.diet, this.name, this.details, this.duration,}); DietEditModel? dietModelObj; Map? diet; 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 a0f988d..aa7cf20 100644 --- a/lib/presentation/diets/diet_edit_screen/diet_edit_screen.dart +++ b/lib/presentation/diets/diet_edit_screen/diet_edit_screen.dart @@ -12,7 +12,7 @@ class DietEditScreen extends StatelessWidget { final dietID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( create: (context) => DietEditBloc(DietEditState(dietModelObj: DietEditModel(dietID: dietID.toString())))..add(DietEditInitialEvent()), - child: DietEditScreen()); + child: DietEditScreen(),); } Widget build(BuildContext context) { @@ -98,10 +98,10 @@ class DietEditScreen extends StatelessWidget { ElevatedButton( onPressed: () => context.read().add(EditDiet()), child: Text('Сохранить'), - ) + ), ], ), - ) + ), ], ), ), 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 dbc622f..e12eab5 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 @@ -50,12 +50,12 @@ class DietSelectBloc extends Bloc { emit((currentState).copyWith( posts: data, myProfileModelObj: currentState.myProfileModelObj, - )); + ),); } else { print('Got unloaded'); emit(DietSelectLoadedState( posts: data, - )); + ),); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку 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 68834d0..4b026cb 100644 --- a/lib/presentation/diets/diet_select_screen/diet_select_screen.dart +++ b/lib/presentation/diets/diet_select_screen/diet_select_screen.dart @@ -13,7 +13,7 @@ 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) { @@ -95,14 +95,14 @@ class DietSelectScreen extends StatelessWidget { onTap: () => GoRouter.of(context).goNamed('dietCreateScreen'), child: Icon(Icons.create_outlined), ), - ) + ), ], ), ), ), ), SizedBox(height: 20), - _buildDietList(context, state) + _buildDietList(context, state), ], ), ), @@ -161,7 +161,7 @@ class DietSelectScreen extends StatelessWidget { ), child: Icon(Icons.edit), ), - )); + ),); }, ); } 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 0c06f5d..950e47a 100644 --- a/lib/presentation/diets/diet_show_screen/diet_show_screen.dart +++ b/lib/presentation/diets/diet_show_screen/diet_show_screen.dart @@ -13,7 +13,7 @@ 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) { @@ -104,9 +104,9 @@ class DietScreen extends StatelessWidget { 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 77f0f1a..3e6c540 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 @@ -37,18 +37,18 @@ class BlogPostCreateBloc title: currentState.title, description: currentState.description, youtube_url: currentState.youtube_url, - token: currentState.token)); + token: currentState.token,),); } else { emit(BlogPostCreateLoadedState( token: token, title: TextEditingController(), description: TextEditingController(), - youtube_url: TextEditingController())); + youtube_url: TextEditingController(),),); } } FutureOr _createBlogPost( - CreateBlogPost event, Emitter emit) async { + CreateBlogPost event, Emitter emit,) async { if (state is BlogPostCreateLoadedState) { var currentState = state as BlogPostCreateLoadedState; @@ -62,7 +62,7 @@ class BlogPostCreateBloc AppRouter.navigatorKey.currentContext?.goNamed('feedScreen'); } else { print( - 'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}'); + 'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}',); } } } 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 de3bab4..6012dd4 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 @@ -27,7 +27,7 @@ class BlogPostCreateLoadedState extends BlogPostCreateState { this.blog_postModelObj, this.title, this.description, - this.youtube_url}); + this.youtube_url,}); BlogPostCreateModel? blog_postModelObj; TextEditingController? title; @@ -42,7 +42,7 @@ class BlogPostCreateLoadedState extends BlogPostCreateState { TextEditingController? title, TextEditingController? description, TextEditingController? youtube_url, - String? token}) { + String? token,}) { return BlogPostCreateLoadedState( blog_postModelObj: blog_postModelObj ?? this.blog_postModelObj, title: title ?? this.title, diff --git a/lib/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart b/lib/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart index be78f7e..444800a 100644 --- a/lib/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart +++ b/lib/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart @@ -13,7 +13,7 @@ class BlogPostCreateScreen extends StatelessWidget { return BlocProvider( create: (context) => BlogPostCreateBloc(BlogPostCreateState(blog_postModelObj: BlogPostCreateModel(blog_postID: blog_postID.toString()))) ..add(BlogPostCreateInitialEvent()), - child: BlogPostCreateScreen()); + child: BlogPostCreateScreen(),); } Widget build(BuildContext context) { @@ -100,7 +100,7 @@ class BlogPostCreateScreen extends StatelessWidget { ), ], ), - ) + ), ], ), ), 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 b3a3027..6b45f84 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 @@ -49,13 +49,13 @@ class BlogPostEditBloc extends Bloc { blog_post: currentState.blog_post, title: currentState.title, description: currentState.description, - youtube_url: currentState.youtube_url)); + youtube_url: currentState.youtube_url,),); } else { emit(BlogPostEditLoadedState( blog_post: data, title: TextEditingController(text: data['title']), description: TextEditingController(text: data['description']), - youtube_url: TextEditingController(text: data['youtube_url']))); + youtube_url: TextEditingController(text: data['youtube_url']),),); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку 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 321448e..4381948 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 @@ -27,7 +27,7 @@ class BlogPostEditLoadedState extends BlogPostEditState { this.blog_post, this.title, this.description, - this.youtube_url}); + this.youtube_url,}); BlogPostEditModel? blog_postModelObj; Map? blog_post; 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 5c38ffb..6af1c51 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 @@ -12,7 +12,7 @@ class BlogPostEditScreen extends StatelessWidget { return BlocProvider( create: (context) => BlogPostEditBloc(BlogPostEditState(blog_postModelObj: BlogPostEditModel(blog_postID: blog_postID.toString())))..add(BlogPostEditInitialEvent()), - child: BlogPostEditScreen()); + child: BlogPostEditScreen(),); } Widget build(BuildContext context) { @@ -106,10 +106,10 @@ class BlogPostEditScreen extends StatelessWidget { ElevatedButton( onPressed: () => context.read().add(EditBlogPost()), child: Text('Сохранить'), - ) + ), ], ), - ) + ), ], ), ), diff --git a/lib/presentation/feed/blog_post_screen/bloc/blog_post_bloc.dart b/lib/presentation/feed/blog_post_screen/bloc/blog_post_bloc.dart index 9f5f11f..b93c18c 100644 --- a/lib/presentation/feed/blog_post_screen/bloc/blog_post_bloc.dart +++ b/lib/presentation/feed/blog_post_screen/bloc/blog_post_bloc.dart @@ -50,14 +50,14 @@ class BlogPostBloc extends Bloc { blog_post: currentState.blog_post, author: currentState.author, comments: currentState.comments, - token: currentState.token)); + token: currentState.token,),); } else { emit(BlogPostLoadedState( blog_post: data, token: token, commentController: TextEditingController(), author: await _fetchAuthor(data['id']), - comments: fillCommentList(await _fetchComments(data['id'])))); + comments: fillCommentList(await _fetchComments(data['id'])),),); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку @@ -74,15 +74,15 @@ class BlogPostBloc extends Bloc { } FutureOr _createComment( - CreateComment event, Emitter emit) async { + CreateComment event, Emitter emit,) async { if (state is BlogPostLoadedState) { var currentState = state as BlogPostLoadedState; // Отправляем данные по HTTP маршруту и ждем ответ var response = await _sendCommentData( - currentState.token, event.body, currentState.blog_post?['id']); + currentState.token, event.body, currentState.blog_post?['id'],); if (response.statusCode == 200) { var updatedComments = fillCommentList( - await _fetchComments(currentState.blog_post?['id'])); + await _fetchComments(currentState.blog_post?['id']),); var updatedState = currentState.copyWith( comments: updatedComments, commentController: @@ -94,7 +94,7 @@ class BlogPostBloc extends Bloc { } FutureOr _deleteEntry( - DeleteEntry event, Emitter emit) async { + DeleteEntry event, Emitter emit,) async { final box = await Hive.openBox('token'); final token = box.get('token'); if (token == null) { @@ -158,13 +158,13 @@ class BlogPostBloc extends Bloc { 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? token, String body, int id,) async { String url = dotenv.env['SERVER_ROOT']! + '/feed/createComment/$id'; final Map credentials = { 'id': id, @@ -177,7 +177,7 @@ class BlogPostBloc extends Bloc { 'Authorization': 'Bearer $token', }, body: json.encode(credentials), - encoding: utf8); + encoding: utf8,); return response; } diff --git a/lib/presentation/feed/blog_post_screen/bloc/blog_post_state.dart b/lib/presentation/feed/blog_post_screen/bloc/blog_post_state.dart index 7622602..982eac9 100644 --- a/lib/presentation/feed/blog_post_screen/bloc/blog_post_state.dart +++ b/lib/presentation/feed/blog_post_screen/bloc/blog_post_state.dart @@ -28,7 +28,7 @@ class BlogPostLoadedState extends BlogPostState { this.author, this.comments, this.token, - this.commentController}); + this.commentController,}); BlogPostModel? blog_postModelObj; Map? blog_post; @@ -44,14 +44,14 @@ class BlogPostLoadedState extends BlogPostState { Map? author, TextEditingController? commentController, String? token, - List? comments}) { + List? comments,}) { return BlogPostLoadedState( blog_postModelObj: blog_postModelObj ?? this.blog_postModelObj, blog_post: blog_post ?? this.blog_post, author: author ?? this.author, comments: comments ?? this.comments, token: token ?? this.token, - commentController: commentController ?? this.commentController); + commentController: commentController ?? this.commentController,); } } diff --git a/lib/presentation/feed/blog_post_screen/blog_post_screen.dart b/lib/presentation/feed/blog_post_screen/blog_post_screen.dart index 37a2ce2..dd2252b 100644 --- a/lib/presentation/feed/blog_post_screen/blog_post_screen.dart +++ b/lib/presentation/feed/blog_post_screen/blog_post_screen.dart @@ -197,7 +197,7 @@ class BlogPostScreen extends StatelessWidget { child: Text( DateFormat('dd.MM.yyyy').format(DateTime.parse(state.blog_post?['updated_at'])), style: theme.textTheme.bodyMedium, - )), + ),), SizedBox(height: 16.0), Row(children: [ Padding( @@ -210,8 +210,8 @@ class BlogPostScreen extends StatelessWidget { Text( "Нравится", style: CustomTextStyles.titleMediumSemiBold, - ) - ]), + ), + ],), ), Spacer(), Padding( @@ -224,10 +224,10 @@ class BlogPostScreen extends StatelessWidget { Text( "Поделиться", style: CustomTextStyles.titleMediumSemiBold, - ) - ])) - ]), - ]), + ), + ],),), + ],), + ],), ); } @@ -356,7 +356,7 @@ class BlogPostScreen extends StatelessWidget { ), onPressed: () => context.read().add(CreateComment(state.commentController!.text)), // Установите прозрачный фон - ) + ), ], ), ], 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 3c8c593..feecc7c 100644 --- a/lib/presentation/feed/blog_post_screen/models/comment_model.dart +++ b/lib/presentation/feed/blog_post_screen/models/comment_model.dart @@ -9,7 +9,7 @@ class CommentModel { this.username, this.dateText, this.greetingText, - required this.id}) { + 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 c224966..ab177fa 100644 --- a/lib/presentation/feed/blog_post_screen/widgets/comment_widget.dart +++ b/lib/presentation/feed/blog_post_screen/widgets/comment_widget.dart @@ -82,7 +82,7 @@ class CommentWidget extends StatelessWidget { commentModelObj.dateText!, style: theme.textTheme.bodyMedium, ), - ) + ), ], ), ), @@ -99,7 +99,7 @@ class CommentWidget extends StatelessWidget { imagePath: ImageConstant.imgSend, height: 30.v, width: 30.h, - margin: EdgeInsets.only(left: 5)), + margin: EdgeInsets.only(left: 5),), ], ), ); diff --git a/lib/presentation/feed/feed_screen/bloc/feed_bloc.dart b/lib/presentation/feed/feed_screen/bloc/feed_bloc.dart index 1eda1fe..0055e61 100644 --- a/lib/presentation/feed/feed_screen/bloc/feed_bloc.dart +++ b/lib/presentation/feed/feed_screen/bloc/feed_bloc.dart @@ -50,12 +50,12 @@ class FeedBloc extends Bloc { emit((currentState).copyWith( posts: data, myProfileModelObj: currentState.myProfileModelObj, - )); + ),); } else { print('Got unloaded'); emit(FeedLoadedState( posts: data, - )); + ),); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку diff --git a/lib/presentation/feed/feed_screen/feed_screen.dart b/lib/presentation/feed/feed_screen/feed_screen.dart index 1af8a84..52105c6 100644 --- a/lib/presentation/feed/feed_screen/feed_screen.dart +++ b/lib/presentation/feed/feed_screen/feed_screen.dart @@ -56,7 +56,7 @@ class FeedScreen extends StatelessWidget { SizedBox(height: 20), _buildMenu(context, state), SizedBox(height: 20), - _buildBlogPostList(context, state) + _buildBlogPostList(context, state), ], ), ), @@ -108,7 +108,7 @@ class FeedScreen extends StatelessWidget { ), ), ], - ) + ), ], ), ), @@ -235,8 +235,8 @@ class FeedScreen extends StatelessWidget { ), Text( "Комментировать", - ) - ]), + ), + ],), ), Spacer(), Row(children: [ @@ -246,18 +246,18 @@ class FeedScreen extends StatelessWidget { ), Text( "Нравится", - ) - ]), + ), + ],), Spacer(), Padding( padding: EdgeInsets.only(right: 4), child: Icon(Icons.share_outlined), ), - ]), + ],), ], ), ), - ])); + ],),); } Function onTapBack(BuildContext context) { 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 20cce2e..cef2304 100644 --- a/lib/presentation/feed/feed_screen/widgets/feed_search_view.dart +++ b/lib/presentation/feed/feed_screen/widgets/feed_search_view.dart @@ -24,7 +24,7 @@ class CustomSearchView extends StatelessWidget { this.fillColor, this.filled = true, this.validator, - this.onChanged}) + this.onChanged,}) : super( key: key, ); @@ -76,7 +76,7 @@ class CustomSearchView extends StatelessWidget { return alignment != null ? Align( alignment: alignment ?? Alignment.center, - child: searchViewWidget(context)) + child: searchViewWidget(context),) : searchViewWidget(context); } @@ -113,7 +113,7 @@ class CustomSearchView extends StatelessWidget { SizedBox( child: Padding( padding: EdgeInsets.only(left: 10), - child: Icon(Icons.search)), + 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 5f63f29..f78c3ff 100644 --- a/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_bloc.dart +++ b/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_bloc.dart @@ -45,14 +45,14 @@ class GlossaryBloc extends Bloc { glossaryModelObj: currentState.glossaryModelObj, token: currentState.token, productGroups: currentState.productGroups, - productList: currentState.productList)); + productList: currentState.productList,),); } else { List productGroupsModel = _fillProductGroups(dataProductGroups); emit(GlossaryLoadedState( token: token, productGroups: productGroupsModel, - productList: [])); + productList: [],),); await _getProductListById(token, emit, productGroupsModel[0].id); } } else { @@ -62,7 +62,7 @@ class GlossaryBloc extends Bloc { } else { // Статус ответа не равен 200, обрабатываем ошибку emit(GlossaryErrorState( - 'Ошибка сервера: ${responseProductGroups.statusCode}')); + 'Ошибка сервера: ${responseProductGroups.statusCode}',),); } } catch (e) { // Ошибка при декодировании JSON или другая ошибка выполнения @@ -71,7 +71,7 @@ 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,7 +79,7 @@ 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'), headers: { @@ -93,7 +93,7 @@ class GlossaryBloc extends Bloc { 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 7536386..a6f8cf5 100644 --- a/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_state.dart +++ b/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_state.dart @@ -26,7 +26,7 @@ class GlossaryLoadedState extends GlossaryState { {this.glossaryModelObj, this.productGroups, this.productList, - this.token}); + this.token,}); GlossaryModel? glossaryModelObj; String? token; @@ -39,7 +39,7 @@ class GlossaryLoadedState extends GlossaryState { {GlossaryModel? glossaryModelObj, String? token, List? productGroups, - List? productList}) { + List? productList,}) { return GlossaryLoadedState( glossaryModelObj: glossaryModelObj ?? this.glossaryModelObj, productGroups: productGroups ?? this.productGroups, diff --git a/lib/presentation/glossary/glossary_screen/glossary_screen.dart b/lib/presentation/glossary/glossary_screen/glossary_screen.dart index ada1e86..b421b87 100644 --- a/lib/presentation/glossary/glossary_screen/glossary_screen.dart +++ b/lib/presentation/glossary/glossary_screen/glossary_screen.dart @@ -14,7 +14,7 @@ class GlossaryScreen extends StatelessWidget { 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) { @@ -67,7 +67,7 @@ class GlossaryScreen extends StatelessWidget { SizedBox(height: 20), _buildMenu(context), SizedBox(height: 20), - _buildProducts(context, state) + _buildProducts(context, state), ], ), ), @@ -142,7 +142,7 @@ class GlossaryScreen extends StatelessWidget { children: List.generate(33, _fillAlphabet), ), ), - ]), + ],), ); } @@ -196,8 +196,8 @@ class GlossaryScreen extends StatelessWidget { SizedBox( height: 8, ), - _buildProductList(context, state) - ]), + _buildProductList(context, state), + ],), ); } @@ -259,22 +259,22 @@ class GlossaryScreen extends StatelessWidget { Column(children: [ Text("Ккал - ${product['energy_on_100gr'].toString()}"), SizedBox(height: 8), - Text("Белки - ${product['proteins_on_100gr'].toString()}") - ]), + 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()}") - ]), - ) - ]) + Text("Углеводы - ${product['carbohydrates_on_100gr'].toString()}"), + ],), + ), + ],), ], ), ), - ])); + ],),); } Widget _fillAlphabet(int index) { 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 20cce2e..cef2304 100644 --- a/lib/presentation/glossary/glossary_screen/widgets/glossary_search_widget.dart +++ b/lib/presentation/glossary/glossary_screen/widgets/glossary_search_widget.dart @@ -24,7 +24,7 @@ class CustomSearchView extends StatelessWidget { this.fillColor, this.filled = true, this.validator, - this.onChanged}) + this.onChanged,}) : super( key: key, ); @@ -76,7 +76,7 @@ class CustomSearchView extends StatelessWidget { return alignment != null ? Align( alignment: alignment ?? Alignment.center, - child: searchViewWidget(context)) + child: searchViewWidget(context),) : searchViewWidget(context); } @@ -113,7 +113,7 @@ class CustomSearchView extends StatelessWidget { SizedBox( child: Padding( padding: EdgeInsets.only(left: 10), - child: Icon(Icons.search)), + 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 51e08b9..fd30edd 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 @@ -35,17 +35,17 @@ class PlanCreateBloc extends Bloc { planModelObj: currentState.planModelObj, name: currentState.name, details: currentState.details, - )); + ),); } else { 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 +58,7 @@ 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}',); } } } @@ -76,7 +76,7 @@ class PlanCreateBloc extends Bloc { 'state': 'active', 'type': '{"meat": true}', 'daily_schedule': - '{"1": {"lunch": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 494}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 12}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 432}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 195}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 710}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "grams", "quantity": 119}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 287}], "snacks": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 445}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "grams", "quantity": 500}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 764}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 735}], "breakfast": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 127}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 89}]}, "2": {"lunch": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 436}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 700}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 766}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 194}], "dinner": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 426}], "snacks": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 58}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 152}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 925}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 224}], "breakfast": [{"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 918}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 81}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 308}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 579}]}, "3": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 266}], "dinner": [{"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 790}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 26}], "snacks": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 549}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 446}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "grams", "quantity": 406}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 92}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 403}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 894}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 457}]}, "4": {"lunch": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 698}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 43}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 994}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 965}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 42}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 948}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 28}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 54}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 112}], "supper": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 891}], "breakfast": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 538}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 635}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "pcs", "quantity": 586}]}, "5": {"lunch": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 900}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "milliliters", "quantity": 242}], "dinner": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 375}], "snacks": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 604}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 510}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 887}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 554}], "supper": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 731}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 574}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 274}], "breakfast": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 276}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 80}]}, "6": {"lunch": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 359}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 358}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 639}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 861}], "dinner": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 124}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 122}], "snacks": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 980}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 837}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 444}], "supper": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 577}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 706}], "breakfast": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 839}]}, "7": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 118}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 664}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 665}], "dinner": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 986}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 296}], "snacks": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 807}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 493}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "milliliters", "quantity": 227}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 385}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 448}], "breakfast": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 784}]}, "8": {"lunch": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 433}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 871}], "dinner": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 332}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 41}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 388}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 649}], "supper": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 114}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "milliliters", "quantity": 968}], "breakfast": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 180}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 269}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 998}]}, "9": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 68}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 505}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 554}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 579}], "snacks": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 751}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 144}], "supper": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 677}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 263}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "pcs", "quantity": 304}], "breakfast": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 963}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 258}]}, "10": {"lunch": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 167}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 306}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 243}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 79}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 560}], "snacks": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 294}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 145}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 639}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 108}], "supper": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 924}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 894}], "breakfast": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 280}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 336}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 338}]}, "11": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 817}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 968}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 525}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 864}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 457}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 548}], "snacks": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 658}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 239}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 358}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 406}], "supper": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "grams", "quantity": 416}], "breakfast": [{"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 220}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 323}]}, "12": {"lunch": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 377}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 138}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 654}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 237}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 902}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 76}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 723}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 481}], "breakfast": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 571}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 515}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 188}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 411}]}, "13": {"lunch": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 379}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 231}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 376}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 147}], "dinner": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 871}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 679}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 359}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 561}], "snacks": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 414}], "supper": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 827}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 649}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 363}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 161}], "breakfast": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 185}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 464}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 387}]}, "14": {"lunch": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 248}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 5}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 693}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 655}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 709}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 881}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 588}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 36}], "snacks": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 453}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 692}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 186}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 721}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 740}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 731}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 842}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 850}]}, "15": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 124}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 380}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 211}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 689}], "dinner": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 326}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 629}], "snacks": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 201}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 129}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 749}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 315}], "breakfast": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 444}]}, "16": {"lunch": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 953}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 101}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 684}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 506}], "dinner": [{"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 333}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 416}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 796}], "snacks": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 799}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 799}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 756}], "supper": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 858}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 619}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 800}], "breakfast": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 363}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 539}]}, "17": {"lunch": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 134}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 977}], "snacks": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 211}], "supper": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 209}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "grams", "quantity": 227}], "breakfast": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 195}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 917}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 706}]}, "18": {"lunch": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "pcs", "quantity": 296}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 239}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 798}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 155}], "dinner": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 959}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 958}], "snacks": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 984}], "supper": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 134}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 432}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 242}]}, "19": {"lunch": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 906}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 152}], "dinner": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 610}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 605}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 498}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 616}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 512}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 146}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 200}], "supper": [{"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 764}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 353}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 181}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 783}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 506}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 887}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 130}]}, "20": {"lunch": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 48}], "dinner": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 266}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 143}], "snacks": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 55}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 174}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 855}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 6}], "supper": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 296}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 878}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 376}], "breakfast": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 442}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 528}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "milliliters", "quantity": 558}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 885}]}, "21": {"lunch": [{"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 504}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 652}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 996}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 200}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 641}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 87}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 689}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 143}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 528}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 475}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 924}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 98}], "breakfast": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 438}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 383}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 462}]}}' + '{"1": {"lunch": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 494}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 12}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 432}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 195}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 710}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "grams", "quantity": 119}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 287}], "snacks": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 445}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "grams", "quantity": 500}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 764}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 735}], "breakfast": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 127}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 89}]}, "2": {"lunch": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 436}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 700}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 766}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 194}], "dinner": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 426}], "snacks": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 58}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 152}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 925}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 224}], "breakfast": [{"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 918}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 81}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 308}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 579}]}, "3": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 266}], "dinner": [{"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 790}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 26}], "snacks": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 549}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 446}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "grams", "quantity": 406}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 92}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 403}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 894}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 457}]}, "4": {"lunch": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 698}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 43}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 994}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 965}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 42}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 948}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 28}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 54}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 112}], "supper": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 891}], "breakfast": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 538}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 635}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "pcs", "quantity": 586}]}, "5": {"lunch": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 900}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "milliliters", "quantity": 242}], "dinner": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 375}], "snacks": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 604}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 510}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 887}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 554}], "supper": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 731}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 574}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 274}], "breakfast": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 276}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 80}]}, "6": {"lunch": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 359}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 358}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 639}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 861}], "dinner": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 124}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 122}], "snacks": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 980}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 837}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 444}], "supper": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 577}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 706}], "breakfast": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 839}]}, "7": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 118}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 664}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 665}], "dinner": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 986}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 296}], "snacks": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 807}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 493}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "milliliters", "quantity": 227}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 385}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 448}], "breakfast": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 784}]}, "8": {"lunch": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 433}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 871}], "dinner": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 332}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 41}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 388}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 649}], "supper": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 114}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "milliliters", "quantity": 968}], "breakfast": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 180}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 269}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 998}]}, "9": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 68}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 505}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 554}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 579}], "snacks": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 751}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 144}], "supper": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 677}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 263}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "pcs", "quantity": 304}], "breakfast": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 963}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 258}]}, "10": {"lunch": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 167}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 306}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 243}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 79}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 560}], "snacks": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 294}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 145}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 639}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 108}], "supper": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 924}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 894}], "breakfast": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 280}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 336}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 338}]}, "11": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 817}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 968}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 525}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 864}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "pcs", "quantity": 457}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 548}], "snacks": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 658}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 239}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 358}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 406}], "supper": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "grams", "quantity": 416}], "breakfast": [{"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 220}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 323}]}, "12": {"lunch": [{"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 377}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 138}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 654}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 237}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 902}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 76}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 723}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 481}], "breakfast": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 571}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 515}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 188}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 411}]}, "13": {"lunch": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 379}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "grams", "quantity": 231}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 376}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 147}], "dinner": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 871}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 679}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 359}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 561}], "snacks": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 414}], "supper": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 827}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 649}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 363}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 161}], "breakfast": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 185}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 464}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 387}]}, "14": {"lunch": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 248}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 5}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 693}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 655}], "dinner": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 709}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 881}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 588}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 36}], "snacks": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "pcs", "quantity": 453}], "supper": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 692}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 186}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 721}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 740}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 731}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 842}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 850}]}, "15": {"lunch": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "grams", "quantity": 124}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 380}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 211}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 689}], "dinner": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 326}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 629}], "snacks": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 201}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 129}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 749}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "milliliters", "quantity": 315}], "breakfast": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 444}]}, "16": {"lunch": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 953}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 101}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 684}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "pcs", "quantity": 506}], "dinner": [{"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 333}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 416}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "milliliters", "quantity": 796}], "snacks": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 799}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 799}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "pcs", "quantity": 756}], "supper": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 858}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 619}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 800}], "breakfast": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "pcs", "quantity": 363}, {"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "grams", "quantity": 539}]}, "17": {"lunch": [{"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 134}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 977}], "snacks": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "pcs", "quantity": 211}], "supper": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 209}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "grams", "quantity": 227}], "breakfast": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 195}, {"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "pcs", "quantity": 917}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 706}]}, "18": {"lunch": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "pcs", "quantity": 296}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 239}, {"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 798}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 155}], "dinner": [{"name": "Little Hamburger", "uniq": "Little Hamburger-1709115623", "portion": "grams", "quantity": 959}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 958}], "snacks": [{"name": "Pasta", "uniq": "Pasta-1709115623", "portion": "milliliters", "quantity": 984}], "supper": [{"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 134}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 432}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "milliliters", "quantity": 242}]}, "19": {"lunch": [{"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 906}, {"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 152}], "dinner": [{"name": "Cheeseburger", "uniq": "Cheeseburger-1709115623", "portion": "milliliters", "quantity": 610}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 605}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "grams", "quantity": 498}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 616}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 512}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 146}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 200}], "supper": [{"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 764}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 353}, {"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 181}], "breakfast": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 783}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 506}, {"name": "Bacon Cheeseburger", "uniq": "Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 887}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 130}]}, "20": {"lunch": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 48}], "dinner": [{"name": "Bacon Dog", "uniq": "Bacon Dog-1709115623", "portion": "milliliters", "quantity": 266}, {"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 143}], "snacks": [{"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "grams", "quantity": 55}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "grams", "quantity": 174}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 855}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "milliliters", "quantity": 6}], "supper": [{"name": "Grilled Cheese", "uniq": "Grilled Cheese-1709115623", "portion": "pcs", "quantity": 296}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 878}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "pcs", "quantity": 376}], "breakfast": [{"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "milliliters", "quantity": 442}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "pcs", "quantity": 528}, {"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "milliliters", "quantity": 558}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 885}]}, "21": {"lunch": [{"name": "Little Bacon Burger", "uniq": "Little Bacon Burger-1709115623", "portion": "grams", "quantity": 504}, {"name": "Little Bacon Cheeseburger", "uniq": "Little Bacon Cheeseburger-1709115623", "portion": "milliliters", "quantity": 652}, {"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 996}], "dinner": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "milliliters", "quantity": 200}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "pcs", "quantity": 641}, {"name": "Cheese Veggie Sandwich", "uniq": "Cheese Veggie Sandwich-1709115623", "portion": "milliliters", "quantity": 87}, {"name": "Cheese Dog", "uniq": "Cheese Dog-1709115623", "portion": "pcs", "quantity": 689}], "snacks": [{"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 143}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "pcs", "quantity": 528}, {"name": "Veggie Sandwich", "uniq": "Veggie Sandwich-1709115623", "portion": "grams", "quantity": 475}], "supper": [{"name": "Little Cheeseburger", "uniq": "Little Cheeseburger-1709115623", "portion": "grams", "quantity": 924}, {"name": "Hamburger", "uniq": "Hamburger-1709115623", "portion": "grams", "quantity": 98}], "breakfast": [{"name": "Bacon Cheese Dog", "uniq": "Bacon Cheese Dog-1709115623", "portion": "grams", "quantity": 438}, {"name": "Cheese Pizza", "uniq": "Cheese Pizza-1709115623", "portion": "milliliters", "quantity": 383}, {"name": "Bacon Burger", "uniq": "Bacon Burger-1709115623", "portion": "grams", "quantity": 462}]}}', }; var response = await http.post( 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 bd354af..8126259 100644 --- a/lib/presentation/plans/plan_create_screen/plan_create_screen.dart +++ b/lib/presentation/plans/plan_create_screen/plan_create_screen.dart @@ -10,7 +10,7 @@ class PlanCreateScreen extends StatelessWidget { final planID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( create: (context) => PlanCreateBloc(PlanCreateState(planModelObj: PlanCreateModel(planID: planID.toString())))..add(PlanCreateInitialEvent()), - child: PlanCreateScreen()); + child: PlanCreateScreen(),); } Widget build(BuildContext context) { @@ -81,9 +81,9 @@ class PlanCreateScreen extends StatelessWidget { 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 1e7e4f2..e150c8b 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 @@ -49,13 +49,13 @@ class PlanEditBloc extends Bloc { plan: currentState.plan, name: currentState.name, duration: currentState.duration, - details: currentState.details)); + details: currentState.details,),); } else { 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 { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку 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 427bf0d..6676962 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 @@ -23,7 +23,7 @@ class PlanEditState extends Equatable { class PlanEditLoadedState extends PlanEditState { PlanEditLoadedState( - {this.planModelObj, this.plan, this.name, this.details, this.duration}); + {this.planModelObj, this.plan, this.name, this.details, this.duration,}); PlanEditModel? planModelObj; Map? plan; 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 7baa33d..abea8b9 100644 --- a/lib/presentation/plans/plan_edit_screen/plan_edit_screen.dart +++ b/lib/presentation/plans/plan_edit_screen/plan_edit_screen.dart @@ -12,7 +12,7 @@ class PlanEditScreen extends StatelessWidget { final planID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( create: (context) => PlanEditBloc(PlanEditState(planModelObj: PlanEditModel(planID: planID.toString())))..add(PlanEditInitialEvent()), - child: PlanEditScreen()); + child: PlanEditScreen(),); } Widget build(BuildContext context) { @@ -98,10 +98,10 @@ class PlanEditScreen extends StatelessWidget { ElevatedButton( onPressed: () => context.read().add(EditPlan()), child: Text('Сохранить'), - ) + ), ], ), - ) + ), ], ), ), 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 b74c0ed..e65409f 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 @@ -47,12 +47,12 @@ class PlanSelectBloc extends Bloc { emit((currentState).copyWith( posts: data, myProfileModelObj: currentState.myProfileModelObj, - )); + ),); } else { print('Got unloaded'); emit(PlanSelectLoadedState( posts: data, - )); + ),); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку 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 810bd3a..022e4e2 100644 --- a/lib/presentation/plans/plan_select_screen/plan_select_screen.dart +++ b/lib/presentation/plans/plan_select_screen/plan_select_screen.dart @@ -13,7 +13,7 @@ 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) { @@ -95,14 +95,14 @@ class PlanSelectScreen extends StatelessWidget { onTap: () => GoRouter.of(context).goNamed('planCreateScreen'), child: Icon(Icons.create_outlined), ), - ) + ), ], ), ), ), ), SizedBox(height: 20), - _buildPlanList(context, state) + _buildPlanList(context, state), ], ), ), 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 a19f6da..98cefd4 100644 --- a/lib/presentation/plans/plan_show_screen/plan_show_screen.dart +++ b/lib/presentation/plans/plan_show_screen/plan_show_screen.dart @@ -14,7 +14,7 @@ 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) { @@ -104,9 +104,9 @@ class PlanScreen extends StatelessWidget { 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 db799d2..cfecf5a 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 @@ -100,7 +100,7 @@ class MyProfileBloc extends Bloc { selectedCountry: currentState.selectedCountry, selectedActivity: currentState.selectedActivity, myProfileModelObj: currentState.myProfileModelObj, - )); + ),); } else { var plans = [] ..addAll(data["finishedPlans"]) @@ -135,7 +135,7 @@ class MyProfileBloc extends Bloc { "0000-00-00 00:00:00", "0000-00-00 00:00:00", "0000-00-00 00:00:00", - "0000-00-00 00:00:00" + "0000-00-00 00:00:00", ]; for (int i = 0; i < data["circumferences"].length; i++) { dates[i] = data["circumferences"]['$i']["created_at"]; @@ -147,7 +147,7 @@ class MyProfileBloc extends Bloc { "user_id": 0, "weight": 0, "created_at": "0000-00-00 00:00:00", - "updated_at": "0000-00-00 00:00:00" + "updated_at": "0000-00-00 00:00:00", }; } } @@ -161,7 +161,7 @@ class MyProfileBloc extends Bloc { "waist_circumference": 0, "hip_circumference": 0, "created_at": "0000-00-00 00:00:00", - "updated_at": "0000-00-00 00:00:00" + "updated_at": "0000-00-00 00:00:00", }; } } @@ -180,17 +180,17 @@ class MyProfileBloc extends Bloc { hypoFormController: data['userDetails']['has_hypo'].toString(), hyperFormController: data['userDetails']['has_hyper'].toString(), chestCircumferenceFormController: TextEditingController( - text: data['userDetails']['chest_circumference']?.toString()), + text: data['userDetails']['chest_circumference']?.toString(),), waistCircumferenceFormController: TextEditingController( - text: data['userDetails']['waist_circumference']?.toString()), + text: data['userDetails']['waist_circumference']?.toString(),), hipCircumferenceFormController: TextEditingController( - text: data['userDetails']['hip_circumference']?.toString()), + text: data['userDetails']['hip_circumference']?.toString(),), weightController: TextEditingController( - text: data['userDetails']['weight']?.toString()), + text: data['userDetails']['weight']?.toString(),), weightFormController: TextEditingController( - text: data['userDetails']['weight']?.toString()), + text: data['userDetails']['weight']?.toString(),), firstNameFormController: TextEditingController( - text: data['userDetails']['first_name']), + text: data['userDetails']['first_name'],), lastNameFormController: TextEditingController(text: data['userDetails']['last_name']), countryFormController: @@ -198,35 +198,35 @@ class MyProfileBloc extends Bloc { cityFormController: TextEditingController(text: data['userDetails']['city']), heightFormController: TextEditingController( - text: data['userDetails']['height']?.toString()), + text: data['userDetails']['height']?.toString(),), upPressureFormController: TextEditingController( - text: data['userDetails']['blood_pressure_up']?.toString()), + text: data['userDetails']['blood_pressure_up']?.toString(),), downPressureFormController: TextEditingController( - text: data['userDetails']['blood_pressure_down']?.toString()), + text: data['userDetails']['blood_pressure_down']?.toString(),), allergiesFormController: TextEditingController( - text: data['userDetails']['about_alergy']), + text: data['userDetails']['about_alergy'],), pillsFormController: TextEditingController( - text: data['userDetails']['about_taking_pils']), + text: data['userDetails']['about_taking_pils'],), sportsFormController: TextEditingController( - text: data['userDetails']['about_sport_hobbies']), + text: data['userDetails']['about_sport_hobbies'],), favoriteFormController: TextEditingController( - text: data['userDetails']['favorite_foods']), + text: data['userDetails']['favorite_foods'],), unfavoriteFormController: TextEditingController( - text: data['userDetails']['unfavorite_foods']), + text: data['userDetails']['unfavorite_foods'],), additionalFormController: TextEditingController( - text: data['userDetails']['additional_info']), + text: data['userDetails']['additional_info'],), dateFormController: TextEditingController(text: data['userDetails']['birthdate']), selectedCity: data['userDetails']['city'], selectedCountry: data['userDetails']['country'], selectedActivity: determineActivityLevel( - data['userDetails']['activity_coefficient']), - )); + data['userDetails']['activity_coefficient'],), + ),); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку emit( - MyProfileErrorState('Некоторые необходимые данные отсутствуют.')); + MyProfileErrorState('Некоторые необходимые данные отсутствуют.'),); } } else { // Статус ответа не равен 200, обрабатываем ошибку @@ -253,7 +253,7 @@ class MyProfileBloc extends Bloc { } // колхоз, но свитчкейсы в дарте странно ведут себя при сравнении double Future _uploadAvatar( - UploadAvatar event, Emitter emit) async { + UploadAvatar event, Emitter emit,) async { if (state is MyProfileLoadedState) { var currentState = state as MyProfileLoadedState; @@ -279,7 +279,7 @@ class MyProfileBloc extends Bloc { return imageUrl; } else { throw Exception( - 'Failed to upload image. Status code: ${streamedResponse.statusCode} ${streamedResponse}}'); + 'Failed to upload image. Status code: ${streamedResponse.statusCode} ${streamedResponse}}',); } } } 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 acf4823..7c66b4c 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 @@ -53,7 +53,7 @@ class MyProfileLoadedState extends MyProfileState { this.additionalFormController, this.hypoFormController, this.hyperFormController, - this.circumferences}) + this.circumferences,}) : super(myProfileModelObj: null); MyProfileModel? myProfileModelObj; 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 38b1561..8df3294 100644 --- a/lib/presentation/profile/my_profile_screen/my_profile_screen.dart +++ b/lib/presentation/profile/my_profile_screen/my_profile_screen.dart @@ -112,7 +112,7 @@ class MyProfileScreen extends StatelessWidget { ), ], ), - child: _buildCarousel(context, state)), + child: _buildCarousel(context, state),), SizedBox(height: 15.v), if (!state.plans!.isEmpty) Container( @@ -137,7 +137,7 @@ class MyProfileScreen extends StatelessWidget { 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), ], ), @@ -212,8 +212,8 @@ class MyProfileScreen extends StatelessWidget { context, 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( @@ -226,9 +226,9 @@ class MyProfileScreen extends StatelessWidget { _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), - ]); + state.userDetails?['height'].toInt() ?? 160,), + state.chartDates,), + ],); case 3: //График обхватов return GestureDetector( onTap: () => _editCircumference(context, state), @@ -241,8 +241,8 @@ class MyProfileScreen extends StatelessWidget { ), SizedBox(height: 30.v), _buildCircumferenceChart(context, state.circumferences, state.chartDates), - _buildChartLegend() - ])); + _buildChartLegend(), + ],),); default: return Text('text', style: TextStyle(fontSize: 16.0)); } @@ -640,7 +640,7 @@ class MyProfileScreen extends StatelessWidget { child: Column(children: [ Padding( padding: EdgeInsets.only(left: 15.h), - child: Text("plans_complete".tr, style: CustomTextStyles.titleMediumBlack.copyWith(color: appTheme.black900))), + child: Text("plans_complete".tr, style: CustomTextStyles.titleMediumBlack.copyWith(color: appTheme.black900)),), SizedBox(height: 5.v), Container( decoration: AppDecoration.outlineBlueGray.copyWith(borderRadius: BorderRadiusStyle.roundedBorder5), @@ -683,12 +683,12 @@ class MyProfileScreen extends StatelessWidget { child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: EdgeInsets.only(bottom: 1.v), - child: Text(plans![i], style: CustomTextStyles.titleSmallBluegray800Bold)), + child: Text(plans![i], style: CustomTextStyles.titleSmallBluegray800Bold),), Container( height: 19.v, width: 100.h, - decoration: BoxDecoration(color: boxColor, borderRadius: BorderRadius.circular(5.h))) - ]))), + decoration: BoxDecoration(color: boxColor, borderRadius: BorderRadius.circular(5.h)),), + ],),),), Align( alignment: Alignment.center, child: Container( @@ -697,18 +697,18 @@ class MyProfileScreen extends StatelessWidget { 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))) - ])); - })), - ])) - ])) - ])); + child: Text("$state".tr, maxLines: 3, overflow: TextOverflow.ellipsis, style: theme.textTheme.titleSmall),),), + ],),); + },),), + ],),), + ],),), + ],),); } List _bodyMassIndex(List weightPoints, int height) { @@ -770,7 +770,7 @@ class MyProfileScreen extends StatelessWidget { ], ), ], - )), + ),), actions: [ TextButton( onPressed: onTapOk(context), @@ -781,7 +781,7 @@ class MyProfileScreen extends StatelessWidget { child: Text("Изменить", style: CustomTextStyles.titleMediumBlack.copyWith( color: Colors.blue, - )), + ),), ), ], backgroundColor: Colors.white, @@ -862,7 +862,7 @@ class MyProfileScreen extends StatelessWidget { child: Text("Изменить", style: CustomTextStyles.titleMediumBlack.copyWith( color: Colors.blue, - )), + ),), ), ], backgroundColor: Colors.white, 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 a5be7c0..cb3aeb6 100644 --- a/lib/presentation/profile/my_profile_screen/my_settings_screen.dart +++ b/lib/presentation/profile/my_profile_screen/my_settings_screen.dart @@ -16,7 +16,7 @@ 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) { @@ -86,8 +86,8 @@ class MySettingsScreen extends StatelessWidget { ), 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: 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 881e14a..ebb0ec0 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 @@ -42,7 +42,7 @@ 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': '', @@ -55,12 +55,12 @@ class RecipeCreateBloc extends Bloc { 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; @@ -74,13 +74,13 @@ class RecipeCreateBloc extends Bloc { }); updatedStepDescriptions!.add(TextEditingController()); emit(currentState.copyWith( - steps: updatedSteps, stepDescriptions: updatedStepDescriptions)); + 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; @@ -91,13 +91,13 @@ class RecipeCreateBloc extends Bloc { updatedSteps!.removeAt(event.id); updatedStepDescriptions!.removeAt(event.id); emit(currentState.copyWith( - steps: updatedSteps, stepDescriptions: updatedStepDescriptions)); + 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,13 +112,13 @@ 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? description, List? steps,) async { String url = '${dotenv.env['SERVER_ROOT']!}/recipe/create'; final Map credentials = { 'title': title, @@ -141,7 +141,7 @@ 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'); @@ -158,7 +158,7 @@ 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 8545b83..4865bf3 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 @@ -30,7 +30,7 @@ class RecipeCreateLoadedState extends RecipeCreateState { this.video_url, this.tags, this.stepDescriptions, - this.steps}); + this.steps,}); RecipeCreateModel? recipeModelObj; String? token; @@ -49,7 +49,7 @@ class RecipeCreateLoadedState extends RecipeCreateState { video_url, steps, tags, - stepDescriptions + stepDescriptions, ]; RecipeCreateLoadedState copyWith({ RecipeCreateModel? recipeModelObj, @@ -69,7 +69,7 @@ class RecipeCreateLoadedState extends RecipeCreateState { token: token ?? this.token, steps: steps ?? this.steps, tags: tags ?? this.tags, - stepDescriptions: stepDescriptions ?? this.stepDescriptions); + stepDescriptions: stepDescriptions ?? this.stepDescriptions,); } } 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 3a81754..5afb164 100644 --- a/lib/presentation/recipe/recipe_create_screen/recipe_create_screen.dart +++ b/lib/presentation/recipe/recipe_create_screen/recipe_create_screen.dart @@ -18,7 +18,7 @@ class RecipeCreateScreen extends StatelessWidget { return BlocProvider( create: (context) => RecipeCreateBloc(RecipeCreateState(recipeModelObj: RecipeCreateModel(recipeID: recipeID.toString())))..add(RecipeCreateInitialEvent()), - child: RecipeCreateScreen()); + child: RecipeCreateScreen(),); } Widget build(BuildContext context) { @@ -73,9 +73,9 @@ class RecipeCreateScreen extends StatelessWidget { children: steps, ), SizedBox(height: 20.v), - _buildAdditional(context, state) - ]), - ))); + _buildAdditional(context, state), + ],), + ),),); } _buldAppBar(BuildContext context) { @@ -105,7 +105,7 @@ class RecipeCreateScreen extends StatelessWidget { alignment: Alignment.center, child: AppbarSubtitle( text: "Добавление рецепта", - )), + ),), ), ); } @@ -164,7 +164,7 @@ class RecipeCreateScreen extends StatelessWidget { ), ), SizedBox(height: 16.0), - ]), + ],), ); } @@ -206,7 +206,7 @@ class RecipeCreateScreen extends StatelessWidget { Icon( Icons.photo_library, color: appTheme.blueGray300, - ) + ), ], ), ), @@ -318,7 +318,7 @@ class RecipeCreateScreen extends StatelessWidget { text: "x", buttonStyle: CustomButtonStyles.outlinePrimaryTL15, ), - ]), + ],), ); } @@ -375,7 +375,7 @@ class RecipeCreateScreen extends StatelessWidget { 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 9c982dd..00dbfcd 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 @@ -56,7 +56,7 @@ 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': '', @@ -85,7 +85,7 @@ class RecipeEditBloc extends Bloc { tags: await _fetchTags(data['id']), stepDescriptions: stepDescriptions, steps: steps, - )); + ),); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку @@ -171,7 +171,7 @@ class RecipeEditBloc extends Bloc { 'steps': '[{"image": "steps/bT91V52zY2hIkjZezUxO4jW4njfhDfCe2PcMxciZ.jpg", "description": "Excepturi fuga sed quaerat impedit facere recusandae. Nihil exercitationem architecto accusantium ut. Qui consequuntur rerum quam asperiores repellendus molestias."}, {"image": "steps/7vaLlotrw65NXbqaD0dK4OTLVyxMgmB9wL3xBzg3.jpg", "description": "Sit hic sint ullam qui. Odit nihil possimus quo id itaque nisi non."}, {"image": "steps/et7cKUsnQkegcRAE72TS0mfAf2jLJXW93QDAGfjz.jpg", "description": "Ab dolores qui voluptatem sed quasi vero. Culpa minus optio in voluptatibus aut corrupti. Dolor expedita minus aut nesciunt quos quibusdam rerum."}, {"image": "steps/260401J6r71r9kuUt694VcsuMMQKTlQMrlIwfaKo.jpg", "description": "Eos dolores corrupti cupiditate aut. Nam nesciunt eveniet eos nam vitae ut. Quibusdam ab commodi ut natus. Nisi earum porro quidem et eligendi iste doloribus."}, {"image": "steps/Ol10BkOFeZ9EG4BAShgB1wnVwtCimoUMcSNDh2EB.jpg", "description": "Consectetur optio porro nobis voluptas quibusdam. Consequatur dolor dolorem laboriosam magnam iste atque."}, {"image": "steps/8PanRq2aWWdXG1xCYkRyJ0M3Z39y6jMPfnHCqlVi.jpg", "description": "A optio porro eligendi ullam. Sed numquam ullam quasi aperiam inventore corrupti enim. Alias id et consequatur perferendis. Ullam consequatur incidunt nesciunt ut et aut."}, {"image": "steps/19U2sYSGDkprS3L8SIFT3xz59OwQJ5xs0A8etZjr.jpg", "description": "In doloribus vel voluptas dolorum. Temporibus iusto est repellat quo sed. Perspiciatis enim sit beatae in dolor ut. Quis ad qui eligendi nisi. Est suscipit dolore ratione dolores suscipit molestiae."}, {"image": "steps/CRxJtjgQw84kG3teJVtl9GqwWUQ1WKpvOeBbwf9a.jpg", "description": "Aut quia maiores et aut. Quidem ab voluptates blanditiis. Est quam quia repellat exercitationem rerum et iste mollitia. Et sed dolores tempore nam et similique qui."}, {"image": "steps/NoG9rHtvHNLrYI2LujURT3DMQCmEe68UbpiXco2y.jpg", "description": "Nam et dolorum delectus. Labore fuga asperiores nam cumque sit. Eum hic officiis ea asperiores qui. Soluta totam enim quasi explicabo sed aut."}]', 'ingredients': - '[{"name": "Cheeseburger", "unit": "pcs", "portion": 336}, {"name": "Little Cheeseburger", "unit": "gr", "portion": 623}, {"name": "Bacon Burger", "unit": "ml", "portion": 713}, {"name": "Little Bacon Burger", "unit": "pcs", "portion": 160}, {"name": "Hamburger", "unit": "tablespoon", "portion": 390}, {"name": "Bacon Cheese Dog", "unit": "teespons", "portion": 295}, {"name": "Hamburger", "unit": "pcs", "portion": 813}, {"name": "Cheeseburger", "unit": "gr", "portion": 951}]' + '[{"name": "Cheeseburger", "unit": "pcs", "portion": 336}, {"name": "Little Cheeseburger", "unit": "gr", "portion": 623}, {"name": "Bacon Burger", "unit": "ml", "portion": 713}, {"name": "Little Bacon Burger", "unit": "pcs", "portion": 160}, {"name": "Hamburger", "unit": "tablespoon", "portion": 390}, {"name": "Bacon Cheese Dog", "unit": "teespons", "portion": 295}, {"name": "Hamburger", "unit": "pcs", "portion": 813}, {"name": "Cheeseburger", "unit": "gr", "portion": 951}]', }; var response = await http.post( @@ -222,7 +222,7 @@ 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 af03fcf..e9086e6 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 @@ -32,7 +32,7 @@ class RecipeEditLoadedState extends RecipeEditState { this.tagsController, this.stepDescriptions, this.tags, - this.steps}); + this.steps,}); RecipeEditModel? recipeModelObj; Map? recipe; 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 c9ce266..6621fc8 100644 --- a/lib/presentation/recipe/recipe_edit_screen/recipe_edit_screen.dart +++ b/lib/presentation/recipe/recipe_edit_screen/recipe_edit_screen.dart @@ -19,7 +19,7 @@ class RecipeEditScreen extends StatelessWidget { final recipeID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( create: (context) => RecipeEditBloc(RecipeEditState(recipeModelObj: RecipeEditModel(recipeID: recipeID.toString())))..add(RecipeEditInitialEvent()), - child: RecipeEditScreen()); + child: RecipeEditScreen(),); } Widget build(BuildContext context) { @@ -76,7 +76,7 @@ class RecipeEditScreen extends StatelessWidget { children: steps, ), SizedBox(height: 20.v), - _buildAdditional(context, state) + _buildAdditional(context, state), ], ), ), @@ -112,7 +112,7 @@ class RecipeEditScreen extends StatelessWidget { alignment: Alignment.center, child: AppbarSubtitle( text: "Редактирование рецепта", - )), + ),), ), ); } @@ -182,7 +182,7 @@ class RecipeEditScreen extends StatelessWidget { ), ), SizedBox(height: 16.0), - ]), + ],), ); } @@ -224,7 +224,7 @@ class RecipeEditScreen extends StatelessWidget { Icon( Icons.photo_library, color: appTheme.blueGray300, - ) + ), ], ), ), @@ -348,7 +348,7 @@ class RecipeEditScreen extends StatelessWidget { text: "x", buttonStyle: CustomButtonStyles.outlinePrimaryTL15, ), - ]), + ],), ); } @@ -394,7 +394,7 @@ class RecipeEditScreen extends StatelessWidget { 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 a7b0d37..6f5bdfd 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 @@ -46,12 +46,12 @@ class RecipeSelectBloc extends Bloc { emit((currentState).copyWith( posts: data, myProfileModelObj: currentState.myProfileModelObj, - )); + ),); } else { print('Got unloaded'); emit(RecipeSelectLoadedState( posts: data, - )); + ),); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку 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 2a3a108..fa0a950 100644 --- a/lib/presentation/recipe/recipe_select_screen/recipe_select_screen.dart +++ b/lib/presentation/recipe/recipe_select_screen/recipe_select_screen.dart @@ -14,7 +14,7 @@ class RecipeSelectScreen extends StatelessWidget { static Widget builder(BuildContext context) { return BlocProvider( create: (context) => RecipeSelectBloc(RecipeSelectState(myProfileModelObj: RecipeSelectModel()))..add(RecipeSelectInitialEvent()), - child: RecipeSelectScreen()); + child: RecipeSelectScreen(),); } Widget build(BuildContext context) { @@ -94,7 +94,7 @@ class RecipeSelectScreen extends StatelessWidget { onTap: () => GoRouter.of(context).goNamed('recipeCreateScreen'), child: Icon(Icons.create_outlined), ), - ) + ), ], ), ), @@ -160,7 +160,7 @@ class RecipeSelectScreen extends StatelessWidget { ), 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 a8b5e19..ed9b6ef 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 @@ -54,7 +54,7 @@ class RecipeBloc extends Bloc { commentController: currentState.commentController, comments: currentState.comments, steps: currentState.steps, - author: currentState.author)); + author: currentState.author,),); } else { emit(RecipeLoadedState( token: token, @@ -63,7 +63,7 @@ class RecipeBloc extends Bloc { author: await _fetchAuthor(data['id']), comments: fillCommentList(await _fetchComments(data['id'])), tags: await _fetchTags(data['id']), - commentController: TextEditingController())); + commentController: TextEditingController(),),); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку @@ -176,7 +176,7 @@ class RecipeBloc extends Bloc { 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; } @@ -194,7 +194,7 @@ class RecipeBloc extends Bloc { 'Authorization': 'Bearer $token', }, body: json.encode(credentials), - encoding: utf8); + 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 fc3a9f4..efc80d6 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 @@ -30,7 +30,7 @@ class RecipeLoadedState extends RecipeState { this.token, this.commentController, this.tags, - this.steps}); + this.steps,}); RecipeModel? recipeModelObj; Map? recipe; @@ -48,7 +48,7 @@ class RecipeLoadedState extends RecipeState { comments, token, commentController, - steps + steps, ]; RecipeLoadedState copyWith( {RecipeModel? recipeModelObj, @@ -58,7 +58,7 @@ class RecipeLoadedState extends RecipeState { String? token, List? tags, List? steps, - List? comments}) { + List? comments,}) { return RecipeLoadedState( recipeModelObj: recipeModelObj ?? this.recipeModelObj, recipe: recipe ?? this.recipe, 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 f1835f8..30fd4e9 100644 --- a/lib/presentation/recipe/recipe_show_screen/recipe_show_screen.dart +++ b/lib/presentation/recipe/recipe_show_screen/recipe_show_screen.dart @@ -18,7 +18,7 @@ class RecipeScreen extends StatelessWidget { final recipeID = ModalRoute.of(context)!.settings.arguments; return BlocProvider( create: (context) => RecipeBloc(RecipeState(recipeModelObj: RecipeModel(recipeID: recipeID.toString())))..add(RecipeInitialEvent()), - child: RecipeScreen()); + child: RecipeScreen(),); } Widget build(BuildContext context) { @@ -77,7 +77,7 @@ class RecipeScreen extends StatelessWidget { _buildCommentSection(context, state), ], ), - )); + ),); } _buildHeaderRow(BuildContext context, RecipeLoadedState state) { @@ -195,7 +195,7 @@ class RecipeScreen extends StatelessWidget { 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), @@ -210,8 +210,8 @@ class RecipeScreen extends StatelessWidget { Text( "Нравится", style: CustomTextStyles.titleMediumSemiBold, - ) - ]), + ), + ],), ), Spacer(), Padding( @@ -224,10 +224,10 @@ class RecipeScreen extends StatelessWidget { Text( "Поделиться", style: CustomTextStyles.titleMediumSemiBold, - ) - ])) - ]), - ]), + ), + ],),), + ],), + ],), ); } @@ -368,7 +368,7 @@ class RecipeScreen extends StatelessWidget { ), onPressed: () => context.read().add(CreateComment(state.commentController!.text)), // Установите прозрачный фон - ) + ), ], ), ], @@ -400,7 +400,7 @@ class RecipeScreen extends StatelessWidget { ), SizedBox( height: 20, - ) + ), ], ); } @@ -451,8 +451,8 @@ class RecipeScreen extends StatelessWidget { errorWidget: (context, url, error) => Icon(Icons.error), ), SizedBox(height: 16.0), - Text(state.steps?[i]['description']) - ]), + 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 c224966..ab177fa 100644 --- a/lib/presentation/recipe/recipe_show_screen/widgets/comment_widget.dart +++ b/lib/presentation/recipe/recipe_show_screen/widgets/comment_widget.dart @@ -82,7 +82,7 @@ class CommentWidget extends StatelessWidget { commentModelObj.dateText!, style: theme.textTheme.bodyMedium, ), - ) + ), ], ), ), @@ -99,7 +99,7 @@ class CommentWidget extends StatelessWidget { imagePath: ImageConstant.imgSend, height: 30.v, width: 30.h, - margin: EdgeInsets.only(left: 5)), + 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 index c855fb4..1ade582 100644 --- a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart +++ b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart @@ -23,7 +23,7 @@ class AdditionalInformationScreen extends StatelessWidget { create: (context) => AdditionalInformationBloc(AdditionalInformationState(additionalInformationModelObj: AdditionalInformationModel(userRegistrationSheet: sheet))) ..add(AdditionalInformationInitialEvent()), - child: AdditionalInformationScreen()); + child: AdditionalInformationScreen(),); } @override @@ -42,11 +42,11 @@ class AdditionalInformationScreen extends StatelessWidget { decoration: BoxDecoration( color: theme.colorScheme.onPrimary, borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.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)))), + value: 1, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation(appTheme.blueA400),),),), SizedBox(height: 20.v), SizedBox(height: 73.v), _buildTextFormField(context), @@ -56,9 +56,9 @@ class AdditionalInformationScreen extends StatelessWidget { text: "finish".tr.toUpperCase(), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapFinish(state, context)); - }), - ]))); + onPressed: onTapFinish(state, context),); + },), + ],),),); } onTapFinish(AdditionalInformationState state, BuildContext context) { @@ -67,7 +67,7 @@ class AdditionalInformationScreen extends StatelessWidget { 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); + headers: {'Content-Type': 'application/json', 'Accept': 'application/json'}, body: jsonEncode(sheet.toJson()), encoding: utf8,); var res = await jsonDecode(response.body); if (response.statusCode == 200) { @@ -88,7 +88,7 @@ class AdditionalInformationScreen extends StatelessWidget { 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)); + title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); } onTapBack(BuildContext context) { @@ -110,7 +110,7 @@ class AdditionalInformationScreen extends StatelessWidget { 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)), + maxLines: 2, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: CustomTextStyles.titleMediumSegoeUI,),), SizedBox(height: 10.v), BlocSelector( selector: (state) => state.editTextController, @@ -119,10 +119,10 @@ class AdditionalInformationScreen extends StatelessWidget { controller: editTextController, hintText: "У меня крепкое здоровье, но последнее время часто утомляюсь, однако, это мне не мешает радоваться жизни", textInputAction: TextInputAction.done, - maxLines: 8); - }) - ])) - ])); + maxLines: 8,); + },), + ],),), + ],),); } /// Navigates to the previous screen. @@ -139,7 +139,7 @@ class AdditionalInformationScreen extends StatelessWidget { title: const Text('Ошибка'), content: Text(text), actions: [TextButton(onPressed: onTapOk(context), child: const Text('Ok'))], - )); + ),); } onTapOk(BuildContext context) { diff --git a/lib/presentation/registration/allergies_screen/allergies_screen.dart b/lib/presentation/registration/allergies_screen/allergies_screen.dart index 50d056b..30e218c 100644 --- a/lib/presentation/registration/allergies_screen/allergies_screen.dart +++ b/lib/presentation/registration/allergies_screen/allergies_screen.dart @@ -17,7 +17,7 @@ class AllergiesScreen extends StatefulWidget { static Widget builder(BuildContext context, sheet) { return BlocProvider( create: (context) => AllergiesBloc(AllergiesState(allergiesModelObj: AllergiesModel(userRegistrationSheet: sheet)))..add(AllergiesInitialEvent()), - child: AllergiesScreen()); + child: AllergiesScreen(),); } @override @@ -41,11 +41,11 @@ class _AllergiesScreenState extends State { decoration: BoxDecoration( color: theme.colorScheme.onPrimary, borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.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)))), + 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), @@ -56,15 +56,15 @@ class _AllergiesScreenState extends State { text: "continue".tr.toUpperCase(), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapContinue(state, context)); - }), + 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) { @@ -89,7 +89,7 @@ class _AllergiesScreenState extends State { 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)); + title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); } onTapBack(BuildContext context) { @@ -107,9 +107,9 @@ class _AllergiesScreenState extends State { selector: (state) => state.enterInformationController, builder: (context, enterInformationController) { return CustomTextFormField( - controller: enterInformationController, hintText: "enter_information".tr, textInputAction: TextInputAction.done, maxLines: 8); - }) - ]); + controller: enterInformationController, hintText: "enter_information".tr, textInputAction: TextInputAction.done, maxLines: 8,); + },), + ],); } /// Navigates to the previous screen. diff --git a/lib/presentation/registration/app_navigation_screen/app_navigation_screen.dart b/lib/presentation/registration/app_navigation_screen/app_navigation_screen.dart index 781552e..29c5748 100644 --- a/lib/presentation/registration/app_navigation_screen/app_navigation_screen.dart +++ b/lib/presentation/registration/app_navigation_screen/app_navigation_screen.dart @@ -15,7 +15,7 @@ class AppNavigationScreen extends StatefulWidget { return BlocProvider( create: (context) => AppNavigationBloc(AppNavigationState( appNavigationModelObj: AppNavigationModel(), - )) + ),) ..add(AppNavigationInitialEvent()), child: AppNavigationScreen(), ); 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 index e5a0c6a..4741654 100644 --- a/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_bloc.dart +++ b/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_bloc.dart @@ -53,9 +53,9 @@ class BloodPressureBloc extends Bloc { ) async { emit(state.copyWith( upPressureController: TextEditingController(), - downPressureController: TextEditingController())); + downPressureController: TextEditingController(),),); emit(state.copyWith( bloodPressureModelObj: state.bloodPressureModelObj - ?.copyWith(dropdownItemList: fillDropdownItemList()))); + ?.copyWith(dropdownItemList: fillDropdownItemList()),),); } } diff --git a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart b/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart index 5d4d8cc..1aabdbd 100644 --- a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart +++ b/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart @@ -21,7 +21,7 @@ class BloodPressureScreen extends StatefulWidget { return BlocProvider( create: (context) => BloodPressureBloc(BloodPressureState(bloodPressureModelObj: BloodPressureModel(userRegistrationSheet: sheet)))..add(BloodPressureInitialEvent()), - child: BloodPressureScreen()); + child: BloodPressureScreen(),); } @override @@ -66,7 +66,7 @@ class _BloodPressureScreenState extends State { SizedBox( width: 224.h, child: Text("your_blood_pressure".tr, - maxLines: 2, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: theme.textTheme.headlineSmall)), + maxLines: 2, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: theme.textTheme.headlineSmall,),), SizedBox(height: 21.v), Container( margin: EdgeInsets.only(right: 1.h), @@ -78,8 +78,8 @@ class _BloodPressureScreenState extends State { 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), @@ -91,8 +91,8 @@ class _BloodPressureScreenState extends State { 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), @@ -105,11 +105,11 @@ class _BloodPressureScreenState extends State { 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)), + child: CustomImageView(imagePath: ImageConstant.imgFavorite, height: 12.adaptSize, width: 12.adaptSize),), hintText: "Не выбрано".tr, items: bloodPressureModelObj?.dropdownItemList ?? [], - onChanged: onChangeHyper(context)); - })), + onChanged: onChangeHyper(context),); + },),), SizedBox(height: 22.v), Text("do_you_have_hypertension_tendency".tr, style: theme.textTheme.bodyLarge), SizedBox(height: 2.v), @@ -122,26 +122,26 @@ class _BloodPressureScreenState extends State { 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)), + child: CustomImageView(imagePath: ImageConstant.imgFavorite, height: 12.adaptSize, width: 12.adaptSize),), hintText: "Не выбрано".tr, items: bloodPressureModelObj?.dropdownItemList ?? [], - onChanged: onChangeHypo(context)); - })), + 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)); - }), + 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) { @@ -208,7 +208,7 @@ class _BloodPressureScreenState extends State { 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)); + title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); } Function onTapBack(BuildContext context) { 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 index 328d1c5..2d8463e 100644 --- a/lib/presentation/registration/blood_pressure_screen/models/blood_pressure_model.dart +++ b/lib/presentation/registration/blood_pressure_screen/models/blood_pressure_model.dart @@ -9,7 +9,7 @@ import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_m class BloodPressureModel extends Equatable { UserRegistrationSheet userRegistrationSheet; BloodPressureModel( - {required this.userRegistrationSheet, this.dropdownItemList = const []}); + {required this.userRegistrationSheet, this.dropdownItemList = const [],}); List dropdownItemList; 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 index 13f1a27..871ff8d 100644 --- a/lib/presentation/registration/body_circumferences_screen/bloc/body_circumferences_bloc.dart +++ b/lib/presentation/registration/body_circumferences_screen/bloc/body_circumferences_bloc.dart @@ -20,6 +20,6 @@ class BodyCircumferencesBloc emit(state.copyWith( chestCircumferenceController: TextEditingController(), waistCircumferenceController: TextEditingController(), - hipCircumferenceController: TextEditingController())); + hipCircumferenceController: TextEditingController(),),); } } diff --git a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart b/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart index 3610697..3326d45 100644 --- a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart +++ b/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart @@ -41,11 +41,11 @@ class BodyCircumferencesScreen extends StatelessWidget { decoration: BoxDecoration( color: theme.colorScheme.onPrimary, borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.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)))), + 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), @@ -56,8 +56,8 @@ class BodyCircumferencesScreen extends StatelessWidget { 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), @@ -65,7 +65,7 @@ class BodyCircumferencesScreen extends StatelessWidget { 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), @@ -73,17 +73,17 @@ class BodyCircumferencesScreen extends StatelessWidget { selector: (state) => state.hipCircumferenceController, builder: (context, hipCircumferenceController) { return CustomTextFormField( - inputFormatters: [digitsOnly], controller: hipCircumferenceController, hintText: "90".tr, textInputAction: TextInputAction.done); - }), + 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)); - }), - ]))); + onPressed: onTapContinue(state, context),); + },), + ],),),); } onTapContinue(BodyCircumferencesState state, BuildContext context) { @@ -133,7 +133,7 @@ class BodyCircumferencesScreen extends StatelessWidget { 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)); + title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); } Function onTapBack(BuildContext context) { 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 index ce4073f..71864db 100644 --- 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 @@ -19,7 +19,7 @@ class CityOfLivingBloc extends Bloc { emit(state.copyWith( cityOfLivingModelObj: state.cityOfLivingModelObj?.copyWith( dropdownItemList: fillDropdownItemList(), - ))); + ),),); } _changeDropDown( 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 index 5ce9150..82da493 100644 --- 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 @@ -1142,7 +1142,7 @@ class CityOfLivingScreen extends StatelessWidget { "Ярцево", "Ясногорск", "Ясный", - "Яхрома" + "Яхрома", ]; return Scaffold( appBar: _buildAppBar(context), @@ -1157,11 +1157,11 @@ class CityOfLivingScreen extends StatelessWidget { decoration: BoxDecoration( color: theme.colorScheme.onPrimary, borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.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)))), + 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), @@ -1174,11 +1174,11 @@ class CityOfLivingScreen extends StatelessWidget { 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)), + child: CustomImageView(imagePath: ImageConstant.imgFavorite, height: 12.adaptSize, width: 12.adaptSize),), hintText: "Не выбрано".tr, items: cityOfLivingModelObj?.dropdownItemList ?? [], - onChanged: onDropDownChange(context)); - }), + onChanged: onDropDownChange(context),); + },), SizedBox(height: 22.v), Text("Населенный пункт", style: theme.textTheme.bodyLarge), SizedBox(height: 2.v), @@ -1228,16 +1228,16 @@ class CityOfLivingScreen extends StatelessWidget { ); }, ); - }), + },), 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)); - }), - ]))); + onPressed: onTapContinue(state, context),); + },), + ],),),); } onTapContinue(CityOfLivingState state, BuildContext context) { @@ -1260,7 +1260,7 @@ class CityOfLivingScreen extends StatelessWidget { 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)); + title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); } Function onTapBack(BuildContext context) { 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 index 10366f3..24eb6d9 100644 --- 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 @@ -1128,7 +1128,7 @@ class CityOfLivingModel extends Equatable { "Ярцево", "Ясногорск", "Ясный", - "Яхрома" + "Яхрома", ], }); diff --git a/lib/presentation/registration/credentials_screen/bloc/credentials_bloc.dart b/lib/presentation/registration/credentials_screen/bloc/credentials_bloc.dart index 91090d2..f0d45cc 100644 --- a/lib/presentation/registration/credentials_screen/bloc/credentials_bloc.dart +++ b/lib/presentation/registration/credentials_screen/bloc/credentials_bloc.dart @@ -19,6 +19,6 @@ class CredentialsBloc extends Bloc { emailController: TextEditingController(), nameController: TextEditingController(), passwordController: TextEditingController(), - passwordConfirmationController: TextEditingController())); + passwordConfirmationController: TextEditingController(),),); } } diff --git a/lib/presentation/registration/credentials_screen/credentials_screen.dart b/lib/presentation/registration/credentials_screen/credentials_screen.dart index 90723f6..cbf3171 100644 --- a/lib/presentation/registration/credentials_screen/credentials_screen.dart +++ b/lib/presentation/registration/credentials_screen/credentials_screen.dart @@ -40,11 +40,11 @@ class CredentialsScreen extends StatelessWidget { decoration: BoxDecoration( color: theme.colorScheme.onPrimary, borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.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)))), + 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), @@ -54,7 +54,7 @@ class CredentialsScreen extends StatelessWidget { 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), @@ -62,7 +62,7 @@ class CredentialsScreen extends StatelessWidget { 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), @@ -73,7 +73,7 @@ class CredentialsScreen extends StatelessWidget { obscureText: true, controller: passwordController, ); - }), + },), SizedBox(height: 21.v), Text("password_confirmation".tr, style: theme.textTheme.bodyLarge), SizedBox(height: 3.v), @@ -81,16 +81,16 @@ class CredentialsScreen extends StatelessWidget { 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)); - }), - ]))); + onPressed: onTapContinue(state, context),); + },), + ],),),); } onTapContinue(CredentialsState state, BuildContext context) { 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 index 5f68a3d..a6b2da0 100644 --- 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 @@ -49,11 +49,11 @@ class _DateOfBirthScreenState extends State { decoration: BoxDecoration( color: theme.colorScheme.onPrimary, borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.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)))), + 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), @@ -64,10 +64,10 @@ class _DateOfBirthScreenState extends State { text: "continue".tr.toUpperCase(), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapContinue(state, context)); - }), - ]))); - }); + onPressed: onTapContinue(state, context),); + },), + ],),),); + },); } onTapContinue(DateOfBirthState state, BuildContext context) { @@ -85,7 +85,7 @@ class _DateOfBirthScreenState extends State { 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)); + title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); } Function onTapBack(BuildContext context) { @@ -107,9 +107,9 @@ class _DateOfBirthScreenState extends State { alignment: Alignment.center, child: GestureDetector( onTap: onTapCalendar(context), - child: Text('${selectedDate.day}.${selectedDate.month}.${selectedDate.year}', style: theme.textTheme.titleMedium))), - SizedBox(height: 6.v) - ])); + child: Text('${selectedDate.day}.${selectedDate.month}.${selectedDate.year}', style: theme.textTheme.titleMedium),),), + SizedBox(height: 6.v), + ],),); } onTapCalendar(BuildContext context) { 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 index 05f9d90..b949491 100644 --- a/lib/presentation/registration/favorite_foods_screen/bloc/favorite_foods_bloc.dart +++ b/lib/presentation/registration/favorite_foods_screen/bloc/favorite_foods_bloc.dart @@ -17,6 +17,6 @@ class FavoriteFoodsBloc extends Bloc { ) async { emit(state.copyWith( favoriteFoodsController: TextEditingController(), - unfavoriteFoodsController: TextEditingController())); + unfavoriteFoodsController: TextEditingController(),),); } } diff --git a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart b/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart index 94771a1..ea90d98 100644 --- a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart +++ b/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart @@ -18,7 +18,7 @@ class FavoriteFoodsScreen extends StatefulWidget { return BlocProvider( create: (context) => FavoriteFoodsBloc(FavoriteFoodsState(favoriteFoodsModelObj: FavoriteFoodsModel(userRegistrationSheet: sheet)))..add(FavoriteFoodsInitialEvent()), - child: FavoriteFoodsScreen()); + child: FavoriteFoodsScreen(),); } @override @@ -42,17 +42,17 @@ class _FavoriteFoodsScreenState extends State { decoration: BoxDecoration( color: theme.colorScheme.onPrimary, borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.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)))), + 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)), + maxLines: 2, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: theme.textTheme.headlineSmall,),), SizedBox(height: 13.v), _buildTextFormFieldFav(context), SizedBox(height: 12.v), @@ -63,15 +63,15 @@ class _FavoriteFoodsScreenState extends State { text: "continue".tr.toUpperCase(), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 40.v), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapContinue(state, context)); - }), + 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) { @@ -97,7 +97,7 @@ class _FavoriteFoodsScreenState extends State { 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)); + title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); } Function onTapBack(BuildContext context) { @@ -115,8 +115,8 @@ class _FavoriteFoodsScreenState extends State { selector: (state) => state.favoriteFoodsController, builder: (context, favoriteFoodsController) { return CustomTextFormField(controller: favoriteFoodsController, hintText: "enter_information".tr, maxLines: 7); - }) - ]); + },), + ],); } /// Section Widget @@ -128,9 +128,9 @@ class _FavoriteFoodsScreenState extends State { selector: (state) => state.unfavoriteFoodsController, builder: (context, unfavoriteFoodsController) { return CustomTextFormField( - controller: unfavoriteFoodsController, hintText: "enter_information".tr, textInputAction: TextInputAction.done, maxLines: 7); - }) - ]); + controller: unfavoriteFoodsController, hintText: "enter_information".tr, textInputAction: TextInputAction.done, maxLines: 7,); + },), + ],); } /// Navigates to the previous screen. diff --git a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart b/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart index 66f98d2..498b24c 100644 --- a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart +++ b/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart @@ -18,7 +18,7 @@ class FavoriteSportsScreen extends StatefulWidget { return BlocProvider( create: (context) => FavoriteSportsBloc(FavoriteSportsState(favoriteSportsModelObj: FavoriteSportsModel(userRegistrationSheet: sheet))) ..add(FavoriteSportsInitialEvent()), - child: FavoriteSportsScreen()); + child: FavoriteSportsScreen(),); } @override @@ -42,11 +42,11 @@ class _FavoriteSportsScreenState extends State { decoration: BoxDecoration( color: theme.colorScheme.onPrimary, borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.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)))), + 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), @@ -57,15 +57,15 @@ class _FavoriteSportsScreenState extends State { text: "continue".tr.toUpperCase(), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapContinue(state, context)); - }), + 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) { @@ -89,7 +89,7 @@ class _FavoriteSportsScreenState extends State { 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)); + title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); } Function onTapBack(BuildContext context) { @@ -111,9 +111,9 @@ class _FavoriteSportsScreenState extends State { hintText: "Я занимаюсь плаванием , почти каждый вечер прогулки на свежем воздухе, пару раз в месяц играю в волейбол. Стараюсь не сидеть на месте!", textInputAction: TextInputAction.done, - maxLines: 8); - }) - ]); + maxLines: 8,); + },), + ],); } onTapArrowLeft(BuildContext context) { diff --git a/lib/presentation/registration/gender_screen/gender_screen.dart b/lib/presentation/registration/gender_screen/gender_screen.dart index 68909d7..d6a9b63 100644 --- a/lib/presentation/registration/gender_screen/gender_screen.dart +++ b/lib/presentation/registration/gender_screen/gender_screen.dart @@ -20,7 +20,7 @@ class GenderScreen extends StatefulWidget { genderModelObj: GenderModel(userRegistrationSheet: sheet), ), )..add(GenderInitialEvent()), - child: GenderScreen()); + child: GenderScreen(),); } @override @@ -45,11 +45,11 @@ class _GenderScreenState extends State { decoration: BoxDecoration( color: theme.colorScheme.onPrimary, borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.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)))), + value: 0.16, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation(appTheme.blueA400),),),), SizedBox(height: 36.v), Text("your_gender".tr, style: theme.textTheme.headlineSmall), RadioListTile( @@ -80,10 +80,10 @@ class _GenderScreenState extends State { text: "continue".tr.toUpperCase(), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapNext(state, context)); - }), - ]))); - }); + onPressed: onTapNext(state, context),); + },), + ],),),); + },); } onTapNext(GenderState state, BuildContext context) { diff --git a/lib/presentation/registration/gender_screen/models/gender_model.dart b/lib/presentation/registration/gender_screen/models/gender_model.dart index b314fba..69779b4 100644 --- a/lib/presentation/registration/gender_screen/models/gender_model.dart +++ b/lib/presentation/registration/gender_screen/models/gender_model.dart @@ -12,7 +12,7 @@ class GenderModel extends Equatable { GenderModel copyWith({UserRegistrationSheet? userRegistrationSheet, gender}) { return GenderModel( userRegistrationSheet: - userRegistrationSheet ?? this.userRegistrationSheet); + userRegistrationSheet ?? this.userRegistrationSheet,); } @override diff --git a/lib/presentation/registration/height_screen/bloc/height_bloc.dart b/lib/presentation/registration/height_screen/bloc/height_bloc.dart index 70b8ba6..223f719 100644 --- a/lib/presentation/registration/height_screen/bloc/height_bloc.dart +++ b/lib/presentation/registration/height_screen/bloc/height_bloc.dart @@ -17,6 +17,6 @@ class HeightBloc extends Bloc { ) async { emit(state.copyWith( heightModelObj: state.heightModelObj?.copyWith(), - heightController: state.heightController)); + heightController: state.heightController,),); } } diff --git a/lib/presentation/registration/height_screen/height_screen.dart b/lib/presentation/registration/height_screen/height_screen.dart index 071285f..22ada6c 100644 --- a/lib/presentation/registration/height_screen/height_screen.dart +++ b/lib/presentation/registration/height_screen/height_screen.dart @@ -18,7 +18,7 @@ class HeightScreen extends StatelessWidget { static Widget builder(BuildContext context, sheet) { return BlocProvider( create: (context) => HeightBloc(HeightState(heightModelObj: HeightModel(userRegistrationSheet: sheet)))..add(HeightInitialEvent()), - child: HeightScreen()); + child: HeightScreen(),); } @override @@ -79,7 +79,7 @@ class HeightScreen extends StatelessWidget { FilteringTextInputFormatter.digitsOnly, ], ); - }) + },), ], ), ], @@ -119,7 +119,7 @@ class HeightScreen extends StatelessWidget { 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)); + title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); } Function onTapBack(BuildContext context) { diff --git a/lib/presentation/registration/height_screen/models/height_model.dart b/lib/presentation/registration/height_screen/models/height_model.dart index caa3b75..3a56580 100644 --- a/lib/presentation/registration/height_screen/models/height_model.dart +++ b/lib/presentation/registration/height_screen/models/height_model.dart @@ -9,7 +9,7 @@ import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_m class HeightModel extends Equatable { UserRegistrationSheet userRegistrationSheet; HeightModel( - {this.dropdownItemList = const [], required this.userRegistrationSheet}); + {this.dropdownItemList = const [], required this.userRegistrationSheet,}); List dropdownItemList; 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 index e9b6959..b0592bb 100644 --- a/lib/presentation/registration/language_select_screen/bloc/language_select_bloc.dart +++ b/lib/presentation/registration/language_select_screen/bloc/language_select_bloc.dart @@ -19,7 +19,7 @@ class LanguageSelectBloc ) async { emit(state.copyWith( languageSelectModelObj: state.languageSelectModelObj - ?.copyWith(dropdownItemList: fillDropdownItemList()))); + ?.copyWith(dropdownItemList: fillDropdownItemList()),),); } _changeDropDown( diff --git a/lib/presentation/registration/language_select_screen/language_select_screen.dart b/lib/presentation/registration/language_select_screen/language_select_screen.dart index 75a7c1a..a682d9d 100644 --- a/lib/presentation/registration/language_select_screen/language_select_screen.dart +++ b/lib/presentation/registration/language_select_screen/language_select_screen.dart @@ -87,7 +87,7 @@ class LanguageSelectScreen extends StatelessWidget { items: languageSelectModelObj?.dropdownItemList ?? [], onChanged: (value) => _onDropDownChanged(context, value), ); - }), + },), Spacer(flex: 63), ], ), diff --git a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart b/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart index 9f01f6f..bce9049 100644 --- a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart +++ b/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart @@ -18,7 +18,7 @@ class MedicineIntakeScreen extends StatefulWidget { return BlocProvider( create: (context) => MedicineIntakeBloc(MedicineIntakeState(medicineIntakeModelObj: MedicineIntakeModel(userRegistrationSheet: sheet))) ..add(MedicineIntakeInitialEvent()), - child: MedicineIntakeScreen()); + child: MedicineIntakeScreen(),); } @override @@ -43,17 +43,17 @@ class _MedicineIntakeScreenState extends State { decoration: BoxDecoration( color: theme.colorScheme.onPrimary, borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.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)))), + 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)), + maxLines: 2, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: theme.textTheme.headlineSmall,),), SizedBox(height: 86.v), _buildTextFormField(context), Spacer(), @@ -62,15 +62,15 @@ class _MedicineIntakeScreenState extends State { text: "continue".tr.toUpperCase(), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapNext(state, context)); - }), + 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) { @@ -101,7 +101,7 @@ class _MedicineIntakeScreenState extends State { 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)); + title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); } Function onTapBack(BuildContext context) { @@ -119,9 +119,9 @@ class _MedicineIntakeScreenState extends State { selector: (state) => state.enterInformationController, builder: (context, enterInformationController) { return CustomTextFormField( - controller: enterInformationController, hintText: "enter_information".tr, textInputAction: TextInputAction.done, maxLines: 8); - }) - ]); + controller: enterInformationController, hintText: "enter_information".tr, textInputAction: TextInputAction.done, maxLines: 8,); + },), + ],); } /// Navigates to the previous screen. diff --git a/lib/presentation/registration/name_screen/bloc/name_bloc.dart b/lib/presentation/registration/name_screen/bloc/name_bloc.dart index f9c47e3..e4a5143 100644 --- a/lib/presentation/registration/name_screen/bloc/name_bloc.dart +++ b/lib/presentation/registration/name_screen/bloc/name_bloc.dart @@ -17,6 +17,6 @@ class NameBloc extends Bloc { ) async { emit(state.copyWith( firstNameController: TextEditingController(), - lastNameController: TextEditingController())); + lastNameController: TextEditingController(),),); } } diff --git a/lib/presentation/registration/name_screen/name_screen.dart b/lib/presentation/registration/name_screen/name_screen.dart index e1f0327..880c3ae 100644 --- a/lib/presentation/registration/name_screen/name_screen.dart +++ b/lib/presentation/registration/name_screen/name_screen.dart @@ -22,7 +22,7 @@ class NameScreen extends StatelessWidget { nameModelObj: NameModel(userRegistrationSheet: sheet), ), )..add(NameInitialEvent()), - child: NameScreen()); + child: NameScreen(),); } @override @@ -42,11 +42,11 @@ class NameScreen extends StatelessWidget { decoration: BoxDecoration( color: theme.colorScheme.onPrimary, borderRadius: BorderRadius.circular(8.h), - border: Border.all(color: theme.colorScheme.primary, width: 1.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)))), + 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), @@ -56,7 +56,7 @@ class NameScreen extends StatelessWidget { 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), @@ -66,7 +66,7 @@ class NameScreen extends StatelessWidget { return CustomTextFormField( controller: lastNameController, ); - }), + },), Spacer(), BlocBuilder(builder: (context, state) { return NextStepButton( @@ -75,8 +75,8 @@ class NameScreen extends StatelessWidget { buttonStyle: CustomButtonStyles.outlinePrimaryTL15, onPressed: () => _onTapNext(context, state), // Assign callback function here ); - }), - ]))); + },), + ],),),); } /// Section Widget @@ -84,9 +84,9 @@ class NameScreen extends StatelessWidget { 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)), + 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)); + title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); } /// Navigates to the previous screen. diff --git a/lib/presentation/registration/splash_screen/splash_screen.dart b/lib/presentation/registration/splash_screen/splash_screen.dart index 501586f..f8355f0 100644 --- a/lib/presentation/registration/splash_screen/splash_screen.dart +++ b/lib/presentation/registration/splash_screen/splash_screen.dart @@ -11,7 +11,7 @@ class SplashScreen extends StatelessWidget { create: (context) => SplashBloc(SplashState(splashModelObj: SplashModel())) ..add(SplashInitialEvent()), - child: SplashScreen()); + child: SplashScreen(),); } @override @@ -29,8 +29,8 @@ class SplashScreen extends StatelessWidget { CustomImageView( imagePath: ImageConstant.img2456927096976, height: 137.adaptSize, - width: 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 index 69161cc..f03c8c3 100644 --- a/lib/presentation/registration/weight_screen/bloc/weight_bloc.dart +++ b/lib/presentation/registration/weight_screen/bloc/weight_bloc.dart @@ -17,6 +17,6 @@ class WeightBloc extends Bloc { ) async { emit(state.copyWith( weightModelObj: state.weightModelObj?.copyWith(), - weightController: state.weightController)); + weightController: state.weightController,),); } } diff --git a/lib/presentation/registration/weight_screen/models/weight_model.dart b/lib/presentation/registration/weight_screen/models/weight_model.dart index e26b49a..d5edd07 100644 --- a/lib/presentation/registration/weight_screen/models/weight_model.dart +++ b/lib/presentation/registration/weight_screen/models/weight_model.dart @@ -9,7 +9,7 @@ import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_m class WeightModel extends Equatable { UserRegistrationSheet userRegistrationSheet; WeightModel( - {this.dropdownItemList = const [], required this.userRegistrationSheet}); + {this.dropdownItemList = const [], required this.userRegistrationSheet,}); List dropdownItemList; diff --git a/lib/presentation/registration/weight_screen/weight_screen.dart b/lib/presentation/registration/weight_screen/weight_screen.dart index 7bf28f1..5d47e8d 100644 --- a/lib/presentation/registration/weight_screen/weight_screen.dart +++ b/lib/presentation/registration/weight_screen/weight_screen.dart @@ -18,7 +18,7 @@ class WeightScreen extends StatelessWidget { static Widget builder(BuildContext context, sheet) { return BlocProvider( create: (context) => WeightBloc(WeightState(weightModelObj: WeightModel(userRegistrationSheet: sheet)))..add(WeightInitialEvent()), - child: WeightScreen()); + child: WeightScreen(),); } @override @@ -78,7 +78,7 @@ class WeightScreen extends StatelessWidget { FilteringTextInputFormatter.digitsOnly, ], ); - }) + },), ], ), ], @@ -118,7 +118,7 @@ class WeightScreen extends StatelessWidget { 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)); + title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),); } Function onTapBack(BuildContext context) { diff --git a/lib/theme/theme_helper.dart b/lib/theme/theme_helper.dart index 7226e37..8a5d5ed 100644 --- a/lib/theme/theme_helper.dart +++ b/lib/theme/theme_helper.dart @@ -9,12 +9,12 @@ class ThemeHelper { // A map of custom color themes supported by the app Map _supportedCustomColor = { - 'primary': PrimaryColors() + 'primary': PrimaryColors(), }; // A map of color schemes supported by the app Map _supportedColorScheme = { - 'primary': ColorSchemes.primaryColorScheme + 'primary': ColorSchemes.primaryColorScheme, }; /// Returns the primary colors for the current theme. @@ -22,7 +22,7 @@ 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,7 +34,7 @@ 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 diff --git a/lib/widgets/bottom_navigation_bar_widget.dart b/lib/widgets/bottom_navigation_bar_widget.dart index 68197c1..51fd3e9 100644 --- a/lib/widgets/bottom_navigation_bar_widget.dart +++ b/lib/widgets/bottom_navigation_bar_widget.dart @@ -51,7 +51,7 @@ class _BottomNavigationBarWidgetState extends State { items: [ PopupMenuItem( child: CustomNavigationMenu(), - ) + ), ], position: RelativeRect.fromLTRB(size.width, size.height, 0, 0), ); diff --git a/lib/widgets/custom_about_list.dart b/lib/widgets/custom_about_list.dart index f4b91b2..4b4e709 100644 --- a/lib/widgets/custom_about_list.dart +++ b/lib/widgets/custom_about_list.dart @@ -28,7 +28,7 @@ class _AboutListState extends State { style: TextStyle( color: Colors.black, fontSize: 14, - fontWeight: FontWeight.bold), + fontWeight: FontWeight.bold,), ), Icon(isExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), ], @@ -39,7 +39,7 @@ class _AboutListState extends State { padding: const EdgeInsets.only(left: 16.0), child: Column( //children: widget.items.map((item) => Text(item)).toList(), - children: [Text(widget.items.join('\n'))]), + children: [Text(widget.items.join('\n'))],), ), Divider(), ], diff --git a/lib/widgets/custom_expandable_list.dart b/lib/widgets/custom_expandable_list.dart index c3d552b..79d62d1 100644 --- a/lib/widgets/custom_expandable_list.dart +++ b/lib/widgets/custom_expandable_list.dart @@ -39,7 +39,7 @@ class _ExpandableListState extends State { style: TextStyle( color: Colors.black, fontSize: 14, - fontWeight: FontWeight.bold), + fontWeight: FontWeight.bold,), ), Icon(isExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), ], @@ -66,7 +66,7 @@ class _ExpandableListState extends State { // Другие состояния, если они есть. return Container(); // Пустой контейнер для необработанных состояний. } - }), + },), ), Divider(), ], @@ -122,7 +122,7 @@ class _ExpandableListState extends State { 'низкий (1-3 тренировки в неделю по 20 мин)', 'умеренный (3-4 тренировки в неделю по 30-60 мин)', 'высокий (5-7 тренировок по 30-60 мин)', - 'экстремальный (несколько интенсивных тренировок в день)' + 'экстремальный (несколько интенсивных тренировок в день)', ]; final digitsOnly = FilteringTextInputFormatter.digitsOnly; return Column(children: [ @@ -137,7 +137,7 @@ class _ExpandableListState extends State { TextField( decoration: InputDecoration(labelText: 'date_of_birth'.tr), controller: state.dateFormController, - onTap: inputTime(context, state)), + onTap: inputTime(context, state),), DropdownButtonFormField( value: state.selectedCountry, hint: Text(state.selectedCountry ?? "Не выбрано"), @@ -166,37 +166,37 @@ class _ExpandableListState extends State { controller: state.weightFormController, decoration: InputDecoration(labelText: 'weight_measurements'.tr), keyboardType: TextInputType.number, - inputFormatters: [digitsOnly]), + inputFormatters: [digitsOnly],), TextField( controller: state.heightFormController, decoration: InputDecoration(labelText: 'height_measurements'.tr), keyboardType: TextInputType.number, - inputFormatters: [digitsOnly]), + inputFormatters: [digitsOnly],), TextField( controller: state.chestCircumferenceFormController, decoration: InputDecoration(labelText: 'chest_circumference'.tr), keyboardType: TextInputType.number, - inputFormatters: [digitsOnly]), + inputFormatters: [digitsOnly],), TextField( controller: state.waistCircumferenceFormController, decoration: InputDecoration(labelText: 'waist_circumference'.tr), keyboardType: TextInputType.number, - inputFormatters: [digitsOnly]), + inputFormatters: [digitsOnly],), TextField( controller: state.hipCircumferenceFormController, decoration: InputDecoration(labelText: 'hip_circumference'.tr), keyboardType: TextInputType.number, - inputFormatters: [digitsOnly]), + inputFormatters: [digitsOnly],), TextField( controller: state.upPressureFormController, decoration: InputDecoration(labelText: 'up_pressure'.tr), keyboardType: TextInputType.number, - inputFormatters: [digitsOnly]), + inputFormatters: [digitsOnly],), TextField( controller: state.downPressureFormController, decoration: InputDecoration(labelText: 'down_pressure'.tr), keyboardType: TextInputType.number, - inputFormatters: [digitsOnly]), + inputFormatters: [digitsOnly],), TextField( controller: state.allergiesFormController, decoration: InputDecoration(labelText: 'allergies_presence'.tr), @@ -259,8 +259,8 @@ class _ExpandableListState extends State { 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) { @@ -382,7 +382,7 @@ class _ExpandableListState extends State { } 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 92ebf00..e25c462 100644 --- a/lib/widgets/custom_hyper_switch.dart +++ b/lib/widgets/custom_hyper_switch.dart @@ -30,7 +30,7 @@ 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 1c625fe..173de64 100644 --- a/lib/widgets/custom_hypo_switch.dart +++ b/lib/widgets/custom_hypo_switch.dart @@ -30,7 +30,7 @@ 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 55766f1..2937b5a 100644 --- a/lib/widgets/custom_icon_button.dart +++ b/lib/widgets/custom_icon_button.dart @@ -45,7 +45,7 @@ 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_item.dart b/lib/widgets/custom_navigation_menu_item.dart index f33d534..2ee47a8 100644 --- a/lib/widgets/custom_navigation_menu_item.dart +++ b/lib/widgets/custom_navigation_menu_item.dart @@ -26,7 +26,7 @@ class MenuItem extends StatelessWidget { CustomImageView(imagePath: icon), SizedBox( width: - 8.0), // Добавляем небольшой отступ между иконкой и текстом + 8.0,), // Добавляем небольшой отступ между иконкой и текстом Text(text), ], ), diff --git a/lib/widgets/custom_notification_screen.dart b/lib/widgets/custom_notification_screen.dart index bb77844..960293c 100644 --- a/lib/widgets/custom_notification_screen.dart +++ b/lib/widgets/custom_notification_screen.dart @@ -21,7 +21,7 @@ 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/test/add_info_test.dart b/test/add_info_test.dart index a4d576d..86379dd 100644 --- a/test/add_info_test.dart +++ b/test/add_info_test.dart @@ -39,7 +39,7 @@ void main() { favoriteFoods: "favoriteFoods", unfavoriteFoods: "unfavoriteFoods", additionalInfo: - "additionalInfo")))); // Ensure that MyProfileModel is non-nullable + "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/allergies_test.dart b/test/allergies_test.dart index d020b5f..d0a7832 100644 --- a/test/allergies_test.dart +++ b/test/allergies_test.dart @@ -39,7 +39,7 @@ void main() { favoriteFoods: "favoriteFoods", unfavoriteFoods: "unfavoriteFoods", additionalInfo: - "additionalInfo")))); // Ensure that MyProfileModel is non-nullable + "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/blood_pressure_test.dart b/test/blood_pressure_test.dart index 1469343..a8c70db 100644 --- a/test/blood_pressure_test.dart +++ b/test/blood_pressure_test.dart @@ -39,7 +39,7 @@ void main() { favoriteFoods: "favoriteFoods", unfavoriteFoods: "unfavoriteFoods", additionalInfo: - "additionalInfo")))); // Ensure that MyProfileModel is non-nullable + "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/body_circumferences_test.dart b/test/body_circumferences_test.dart index e727e21..339c3b8 100644 --- a/test/body_circumferences_test.dart +++ b/test/body_circumferences_test.dart @@ -39,7 +39,7 @@ void main() { favoriteFoods: "favoriteFoods", unfavoriteFoods: "unfavoriteFoods", additionalInfo: - "additionalInfo")))); // Ensure that MyProfileModel is non-nullable + "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/city_of_living_test.dart b/test/city_of_living_test.dart index d198eb2..1a6c18b 100644 --- a/test/city_of_living_test.dart +++ b/test/city_of_living_test.dart @@ -39,7 +39,7 @@ void main() { favoriteFoods: "favoriteFoods", unfavoriteFoods: "unfavoriteFoods", additionalInfo: - "additionalInfo")))); // Ensure that MyProfileModel is non-nullable + "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/credentials_test.dart b/test/credentials_test.dart index 851a7df..a82cd41 100644 --- a/test/credentials_test.dart +++ b/test/credentials_test.dart @@ -39,7 +39,7 @@ void main() { favoriteFoods: "favoriteFoods", unfavoriteFoods: "unfavoriteFoods", additionalInfo: - "additionalInfo")))); // Ensure that MyProfileModel is non-nullable + "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/date_of_birth_test.dart b/test/date_of_birth_test.dart index 4d79b57..8ce0a1f 100644 --- a/test/date_of_birth_test.dart +++ b/test/date_of_birth_test.dart @@ -39,7 +39,7 @@ void main() { favoriteFoods: "favoriteFoods", unfavoriteFoods: "unfavoriteFoods", additionalInfo: - "additionalInfo")))); // Ensure that MyProfileModel is non-nullable + "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/diary_test.dart b/test/diary_test.dart index c7570d3..56d1c58 100644 --- a/test/diary_test.dart +++ b/test/diary_test.dart @@ -28,7 +28,7 @@ void main() { moderationExpanded: false, recommendedChartValues: [10, 10, 10, 10], consumedChartValues: [1, 2, 3, 4], - moodExpanded: false); + moodExpanded: false,); await tester.pumpWidget( MaterialApp( diff --git a/test/favorite_foods_test.dart b/test/favorite_foods_test.dart index 2fbd838..6364726 100644 --- a/test/favorite_foods_test.dart +++ b/test/favorite_foods_test.dart @@ -39,7 +39,7 @@ void main() { favoriteFoods: "favoriteFoods", unfavoriteFoods: "unfavoriteFoods", additionalInfo: - "additionalInfo")))); // Ensure that MyProfileModel is non-nullable + "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/favorite_sports_test.dart b/test/favorite_sports_test.dart index ed7ff4c..1c7311e 100644 --- a/test/favorite_sports_test.dart +++ b/test/favorite_sports_test.dart @@ -39,7 +39,7 @@ void main() { favoriteFoods: "favoriteSports", unfavoriteFoods: "unfavoriteSports", additionalInfo: - "additionalInfo")))); // Ensure that MyProfileModel is non-nullable + "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/gender_test.dart b/test/gender_test.dart index e05ba6f..94ab621 100644 --- a/test/gender_test.dart +++ b/test/gender_test.dart @@ -39,7 +39,7 @@ void main() { favoriteFoods: "favoriteSports", unfavoriteFoods: "unfavoriteSports", additionalInfo: - "additionalInfo")))); // Ensure that MyProfileModel is non-nullable + "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/height_test.dart b/test/height_test.dart index 9338fa7..cd512ed 100644 --- a/test/height_test.dart +++ b/test/height_test.dart @@ -39,7 +39,7 @@ void main() { favoriteFoods: "favoriteSports", unfavoriteFoods: "unfavoriteSports", additionalInfo: - "additionalInfo")))); // Ensure that MyProfileModel is non-nullable + "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/language_select_test.dart b/test/language_select_test.dart index 447592f..15582cf 100644 --- a/test/language_select_test.dart +++ b/test/language_select_test.dart @@ -10,7 +10,7 @@ void main() { testWidgets('renders screen in initial state', (WidgetTester tester) async { final myProfileBloc = LanguageSelectBloc(LanguageSelectState( languageSelectModelObj: - LanguageSelectModel())); // Ensure that MyProfileModel is non-nullable + LanguageSelectModel(),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/medicine_intake_test.dart b/test/medicine_intake_test.dart index fd92e71..eae83c1 100644 --- a/test/medicine_intake_test.dart +++ b/test/medicine_intake_test.dart @@ -39,7 +39,7 @@ void main() { favoriteFoods: "favoriteFoods", unfavoriteFoods: "unfavoriteFoods", additionalInfo: - "additionalInfo")))); // Ensure that MyProfileModel is non-nullable + "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/name_test.dart b/test/name_test.dart index 408a01c..1e271cb 100644 --- a/test/name_test.dart +++ b/test/name_test.dart @@ -39,7 +39,7 @@ void main() { favoriteFoods: "favoriteFoods", unfavoriteFoods: "unfavoriteFoods", additionalInfo: - "additionalInfo")))); // Ensure that MyProfileModel is non-nullable + "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/profile_test.dart b/test/profile_test.dart index 20f3f34..cf0ebc4 100644 --- a/test/profile_test.dart +++ b/test/profile_test.dart @@ -11,7 +11,7 @@ void main() { (WidgetTester tester) async { final myProfileBloc = MyProfileBloc(MyProfileState( myProfileModelObj: - MyProfileModel())); // Ensure that MyProfileModel is non-nullable + MyProfileModel(),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/settings_test.dart b/test/settings_test.dart index b866ba4..c605878 100644 --- a/test/settings_test.dart +++ b/test/settings_test.dart @@ -11,7 +11,7 @@ void main() { (WidgetTester tester) async { final myProfileBloc = MyProfileBloc(MyProfileState( myProfileModelObj: - MyProfileModel())); // Ensure that MyProfileModel is non-nullable + MyProfileModel(),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( diff --git a/test/weight_test.dart b/test/weight_test.dart index adf8f8f..e5f9fe0 100644 --- a/test/weight_test.dart +++ b/test/weight_test.dart @@ -39,7 +39,7 @@ void main() { favoriteFoods: "favoriteFoods", unfavoriteFoods: "unfavoriteFoods", additionalInfo: - "additionalInfo")))); // Ensure that MyProfileModel is non-nullable + "additionalInfo",),),),); // Ensure that MyProfileModel is non-nullable await tester.pumpWidget( MaterialApp( -- 2.49.1 From f8bfe36f4724899773b5bfac4a2662f033643120 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Thu, 27 Jun 2024 10:44:33 +0300 Subject: [PATCH 006/110] feat(chat): fix native analyze --- analysis_options.yaml | 3 +- ios/Runner/Info.plist | 5 ++ .../initialization_cubit.dart | 19 +++--- .../chat/presentation/pages/chat_screen.dart | 10 +++- lib/main.dart | 59 ++++++++++--------- pubspec.yaml | 1 + 6 files changed, 60 insertions(+), 37 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index ee44716..31a0a37 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -33,6 +33,7 @@ linter: # - newline-before-return # - no-boolean-literal-compare # - no-empty-block -# - prefer-trailing-comma # - prefer-conditional-expressions # - no-equal-then-else +rules: + - prefer-trailing-comma \ No newline at end of file diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index fb18841..0d81ba4 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -52,5 +52,10 @@ UIApplicationSupportsIndirectInputEvents + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index cd9828e..57544ae 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -5,8 +5,6 @@ import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; import 'package:pusher_client/pusher_client.dart'; class InitializationCubit extends Cubit { - late final webSocketChannel; - final ChatRepository chatRepository; InitializationCubit({required this.chatRepository}) : super(const InitializationState.loading()); @@ -29,20 +27,27 @@ class InitializationCubit extends Cubit { ), ); - PusherClient pusher = PusherClient( + PusherClient pusherClient = PusherClient( wsUrl.key, options, autoConnect: true, enableLogging: true, ); - await pusher.connect(); - - // Channel channel = pusher.subscribe('private-direct-chat.'); - // channel.registerListener(classId, method); + await pusherClient.connect(); emit(const InitializationState.success()); + + Channel channel = pusherClient.subscribe('private-direct-chat.' + '7909ea56-7822-4d5f-8892-134bc937127f'); + + channel.bind("pusher_internal:subscription_succeeded", (PusherEvent? event) { + channel.trigger("pusher_internal:subscription_succeeded", {}); + }); + + channel.registerListener('pusher:subscribe', (data) => print(data.toString())); + } catch (e) { + print(e); emit(InitializationState.error(errorMessage: e.toString())); } } diff --git a/lib/features/chat/presentation/pages/chat_screen.dart b/lib/features/chat/presentation/pages/chat_screen.dart index 4c4bcfe..4f7867e 100644 --- a/lib/features/chat/presentation/pages/chat_screen.dart +++ b/lib/features/chat/presentation/pages/chat_screen.dart @@ -1,3 +1,4 @@ +import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.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'; @@ -6,7 +7,7 @@ import 'package:flutter/cupertino.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:flutter/material.dart'; -class ChatScreen extends StatelessWidget { +class ChatScreen extends StatefulWidget { final String chatId; const ChatScreen({ @@ -14,9 +15,14 @@ class ChatScreen extends StatelessWidget { super.key, }); + @override + State createState() => _ChatScreenState(); +} + +class _ChatScreenState extends State { Widget build(BuildContext context) { return BlocProvider( - create: (BuildContext context) => sl()..initChat(chatId), + create: (BuildContext context) => sl()..initChat(widget.chatId), child: BlocBuilder( builder: (context, state) { if (state is ChatRoomStateLoading) { diff --git a/lib/main.dart b/lib/main.dart index e1f081e..2919130 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,5 +1,6 @@ import 'package:eatvio_app/app_router.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.dart'; +import 'package:eatvio_app/core/initialization_cubit/initialization_state.dart'; 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/locator_service.dart'; @@ -42,7 +43,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MultiBlocProvider( providers: [ - BlocProvider(create: (context) => sl()..runInitialization()), + BlocProvider(create: (context) => InitializationCubit(chatRepository: sl())..runInitialization()), BlocProvider(create: (context) => ThemeBloc(ThemeState(themeType: PrefUtils().getThemeData()))), BlocProvider(create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent())), BlocProvider(create: (context) => FeedBloc(FeedState(myProfileModelObj: FeedModel()))..add(FeedInitialEvent())), @@ -51,33 +52,37 @@ class MyApp extends StatelessWidget { create: (context) => ChatSelectBloc(ChatSelectState(chatSelectModelObj: ChatSelectModel()))..add(ChatSelectInitialEvent()), ), ], - child: BlocBuilder( - builder: (context, state) { - return KeyboardDismisser( - gestures: [ - GestureType.onTap, - GestureType.onPanUpdateDownDirection, - ], - child: MaterialApp.router( - theme: theme, - title: 'Eatvio', - routerConfig: AppRouter.appRouter, - debugShowCheckedModeBanner: false, - localizationsDelegates: [ - AppLocalizationDelegate(), - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - supportedLocales: [ - Locale( - 'ru', - '', - ), - ], - ), - ); + child: BlocListener( + listener: (BuildContext context, InitializationState state) { }, + child: BlocBuilder( + builder: (context, state) { + return KeyboardDismisser( + gestures: [ + GestureType.onTap, + GestureType.onPanUpdateDownDirection, + ], + child: MaterialApp.router( + theme: theme, + title: 'Eatvio', + routerConfig: AppRouter.appRouter, + debugShowCheckedModeBanner: false, + localizationsDelegates: [ + AppLocalizationDelegate(), + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: [ + Locale( + 'ru', + '', + ), + ], + ), + ); + }, + ), ), ); } diff --git a/pubspec.yaml b/pubspec.yaml index a3986db..353e7ef 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,7 @@ name: eatvio_app description: A new Flutter project. version: 0.0.0+1 +publish_to: 'none' environment: sdk: ">=3.3.4 <4.0.0" -- 2.49.1 From 6b56d4583264578af344973e0f5ed96819145a2c Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Thu, 27 Jun 2024 10:49:00 +0300 Subject: [PATCH 007/110] feat(chat): remove rules --- analysis_options.yaml | 7 +------ lib/features/chat/presentation/pages/chat_screen.dart | 1 - 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index 31a0a37..3d36fce 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -27,13 +27,8 @@ dart_code_metrics: # maximum-nesting-level: 5 # metrics-exclude: # - test/** -linter: - rules: - require_trailing_commas: true # - newline-before-return # - no-boolean-literal-compare # - no-empty-block # - prefer-conditional-expressions -# - no-equal-then-else -rules: - - prefer-trailing-comma \ No newline at end of file +# - no-equal-then-else \ No newline at end of file diff --git a/lib/features/chat/presentation/pages/chat_screen.dart b/lib/features/chat/presentation/pages/chat_screen.dart index 4f7867e..31f431a 100644 --- a/lib/features/chat/presentation/pages/chat_screen.dart +++ b/lib/features/chat/presentation/pages/chat_screen.dart @@ -1,4 +1,3 @@ -import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.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'; -- 2.49.1 From b1508c3553c4299df841a18bc0f1c5a5b8b84776 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 27 Jun 2024 13:17:53 +0300 Subject: [PATCH 008/110] feat(app): Initial layouts for subscribers, feed display fix, feed photo upload front end --- .../bloc/blog_post_create_bloc.dart | 26 +- .../bloc/blog_post_create_event.dart | 7 + .../bloc/blog_post_create_state.dart | 30 ++- .../blog_post_create_screen.dart | 109 ++++++++- .../feed/feed_screen/bloc/feed_bloc.dart | 4 +- .../feed/feed_screen/feed_screen.dart | 118 +++++---- .../bloc/my_profile_bloc.dart | 231 ++++++++++-------- .../bloc/subscribers_bloc.dart | 74 ++++++ .../bloc/subscribers_event.dart | 16 ++ .../bloc/subscribers_state.dart | 49 ++++ .../models/subscribers_model.dart | 16 ++ .../subscribers_screen.dart | 213 ++++++++++++++++ 12 files changed, 709 insertions(+), 184 deletions(-) create mode 100644 lib/presentation/users/subscribers_screen/bloc/subscribers_bloc.dart create mode 100644 lib/presentation/users/subscribers_screen/bloc/subscribers_event.dart create mode 100644 lib/presentation/users/subscribers_screen/bloc/subscribers_state.dart create mode 100644 lib/presentation/users/subscribers_screen/models/subscribers_model.dart create mode 100644 lib/presentation/users/subscribers_screen/subscribers_screen.dart 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 3e6c540..d2f448b 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 @@ -6,6 +6,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; +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'; @@ -19,6 +20,7 @@ class BlogPostCreateBloc BlogPostCreateBloc(BlogPostCreateState initialState) : super(initialState) { on(_onInitialize); on(_createBlogPost); + on(_uploadImages); } _onInitialize( @@ -32,23 +34,31 @@ class BlogPostCreateBloc } if (state is BlogPostCreateLoadedState) { var currentState = state as BlogPostCreateLoadedState; - emit(currentState.copyWith( + emit( + currentState.copyWith( blog_postModelObj: currentState.blog_postModelObj, title: currentState.title, description: currentState.description, youtube_url: currentState.youtube_url, - token: currentState.token,),); + token: currentState.token, + ), + ); } else { - emit(BlogPostCreateLoadedState( + emit( + BlogPostCreateLoadedState( token: token, title: TextEditingController(), description: TextEditingController(), - youtube_url: TextEditingController(),),); + youtube_url: TextEditingController(), + ), + ); } } FutureOr _createBlogPost( - CreateBlogPost event, Emitter emit,) async { + CreateBlogPost event, + Emitter emit, + ) async { if (state is BlogPostCreateLoadedState) { var currentState = state as BlogPostCreateLoadedState; @@ -62,7 +72,8 @@ class BlogPostCreateBloc AppRouter.navigatorKey.currentContext?.goNamed('feedScreen'); } else { print( - 'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}',); + 'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}', + ); } } } @@ -94,4 +105,7 @@ class BlogPostCreateBloc return response; } + + FutureOr _uploadImages( + UploadImages event, Emitter emit) {} } diff --git a/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_event.dart b/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_event.dart index 7631fac..778cd85 100644 --- a/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_event.dart +++ b/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_event.dart @@ -19,3 +19,10 @@ class CreateBlogPost extends BlogPostCreateEvent { @override List get props => []; } + +class UploadImages extends BlogPostCreateEvent { + UploadImages(this.image); + final XFile image; + @override + List get props => [image]; +} 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 6012dd4..6014e3d 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 @@ -22,33 +22,39 @@ class BlogPostCreateState extends Equatable { } class BlogPostCreateLoadedState extends BlogPostCreateState { - BlogPostCreateLoadedState( - {this.token, - this.blog_postModelObj, - this.title, - this.description, - this.youtube_url,}); + BlogPostCreateLoadedState({ + this.token, + this.blog_postModelObj, + this.title, + this.description, + this.youtube_url, + this.isLoading = false, + }); BlogPostCreateModel? blog_postModelObj; TextEditingController? title; TextEditingController? description; TextEditingController? youtube_url; String? token; + bool isLoading; @override List get props => [blog_postModelObj, title, description, youtube_url]; - BlogPostCreateLoadedState copyWith( - {BlogPostCreateModel? blog_postModelObj, - TextEditingController? title, - TextEditingController? description, - TextEditingController? youtube_url, - String? token,}) { + BlogPostCreateLoadedState copyWith({ + BlogPostCreateModel? blog_postModelObj, + TextEditingController? title, + TextEditingController? description, + TextEditingController? youtube_url, + String? token, + bool isLoading = false, + }) { return BlogPostCreateLoadedState( blog_postModelObj: blog_postModelObj ?? this.blog_postModelObj, title: title ?? this.title, description: description ?? this.description, youtube_url: youtube_url ?? this.youtube_url, token: token ?? this.token, + isLoading: this.isLoading, ); } } diff --git a/lib/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart b/lib/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart index 444800a..f02a512 100644 --- a/lib/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart +++ b/lib/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart @@ -2,6 +2,7 @@ import 'bloc/blog_post_create_bloc.dart'; import 'models/blog_post_create_model.dart'; import 'package:eatvio_app/core/app_export.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'; @@ -11,9 +12,12 @@ 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()))) - ..add(BlogPostCreateInitialEvent()), - child: BlogPostCreateScreen(),); + create: (context) => BlogPostCreateBloc(BlogPostCreateState( + blog_postModelObj: + BlogPostCreateModel(blog_postID: blog_postID.toString()))) + ..add(BlogPostCreateInitialEvent()), + child: BlogPostCreateScreen(), + ); } Widget build(BuildContext context) { @@ -71,13 +75,15 @@ 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.youtube_url, validator: _validateYouTubeLink, @@ -90,9 +96,12 @@ class BlogPostCreateScreen extends StatelessWidget { maxLines: 6, ), SizedBox(height: 16.0), + _buildAddPhoto(context, state), + SizedBox(height: 16.0), // Add widget for image upload here CustomOutlinedButton( - onPressed: () => _submitForm(context, state.title!.text, state.description!.text, state.youtube_url!.text), + onPressed: () => _submitForm(context, state.title!.text, + state.description!.text, state.youtube_url!.text), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, text: 'Создать', ), @@ -108,16 +117,20 @@ 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 @@ -125,6 +138,81 @@ _submitForm(BuildContext context, String title, String description, String youtu } } +_buildAddPhoto(BuildContext context, BlogPostCreateLoadedState state) { + bool isLoading = state.isLoading; + return GestureDetector( + onTap: addImage(context, isLoading), + child: Stack( + children: [ + if (!isLoading) + Container( + margin: EdgeInsets.symmetric(horizontal: 10.h), + padding: EdgeInsets.symmetric( + horizontal: 40.h, + vertical: 80.v, + ), + decoration: AppDecoration.fillGray.copyWith( + borderRadius: BorderRadiusStyle.roundedBorder5, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + children: [ + // Показывайте прелоадер, если загрузка активна + + Padding( + padding: EdgeInsets.only( + left: 7.h, + top: 5.v, + ), + child: Text( + "Добавить фото", + selectionColor: appTheme.blueA400, + ), + ), + Spacer(), + Icon( + Icons.photo_library, + color: appTheme.blueGray300, + ), + ], + ), + ), + if (isLoading) + Container( + margin: EdgeInsets.symmetric(horizontal: 10.h), + padding: EdgeInsets.symmetric( + horizontal: 40.h, + vertical: 80.v, + ), + decoration: AppDecoration.fillGray.copyWith( + borderRadius: BorderRadiusStyle.roundedBorder5, + ), + child: Center( + child: CircularProgressIndicator( + color: appTheme + .blueGray300), // Замените на свой прелоадер при необходимости + ), + ), + ], + ), + ); +} + +addImage(BuildContext context, bool isLoading) { + if (!isLoading) { + return () async { + final picker = ImagePicker(); + List? images = await picker.pickMultiImage(); + if (images.isNotEmpty) { + for (var image in images) { + context.read().add(UploadImages(image)); + } + } + }; + } +} + String? _validateTitle(value) { if (value!.isEmpty) { return 'Пожалуйста, введите заголовок'; @@ -149,6 +237,7 @@ 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/presentation/feed/feed_screen/bloc/feed_bloc.dart b/lib/presentation/feed/feed_screen/bloc/feed_bloc.dart index 0055e61..1eda1fe 100644 --- a/lib/presentation/feed/feed_screen/bloc/feed_bloc.dart +++ b/lib/presentation/feed/feed_screen/bloc/feed_bloc.dart @@ -50,12 +50,12 @@ class FeedBloc extends Bloc { emit((currentState).copyWith( posts: data, myProfileModelObj: currentState.myProfileModelObj, - ),); + )); } else { print('Got unloaded'); emit(FeedLoadedState( posts: data, - ),); + )); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку diff --git a/lib/presentation/feed/feed_screen/feed_screen.dart b/lib/presentation/feed/feed_screen/feed_screen.dart index 52105c6..f6cf07a 100644 --- a/lib/presentation/feed/feed_screen/feed_screen.dart +++ b/lib/presentation/feed/feed_screen/feed_screen.dart @@ -13,7 +13,10 @@ import 'package:intl/intl.dart'; class FeedScreen extends StatelessWidget { static Widget builder(BuildContext context) { - return BlocProvider(create: (context) => FeedBloc(FeedState(myProfileModelObj: FeedModel()))..add(FeedInitialEvent()), child: FeedScreen()); + return BlocProvider( + create: (context) => FeedBloc(FeedState(myProfileModelObj: FeedModel())) + ..add(FeedInitialEvent()), + child: FeedScreen()); } Widget build(BuildContext context) { @@ -103,7 +106,8 @@ class FeedScreen extends StatelessWidget { flex: 1, child: CustomOutlinedButton( text: "+", - onPressed: () => GoRouter.of(context).goNamed('blogPostCreateScreen'), + onPressed: () => + GoRouter.of(context).goNamed('blogPostCreateScreen'), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, ), ), @@ -132,23 +136,25 @@ class FeedScreen extends StatelessWidget { _buildFeedEntry(post, 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: 2, - blurRadius: 5, - 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: 2, + blurRadius: 5, + offset: Offset(0, 3), + ), + ], + ), + child: Column( + children: [ ListTile( leading: CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (post["author"]['profile_photo_path'] ?? ''), + imageUrl: dotenv.env['STORAGE_URL']! + + (post['profile_photo_path'] ?? ''), imageBuilder: (context, imageProvider) => CircleAvatar( backgroundImage: imageProvider, radius: 25, @@ -161,16 +167,17 @@ class FeedScreen extends StatelessWidget { ), ), title: Text( - post?['author']['name'] ?? '', + post?['author_name'] ?? 'Authorae', style: CustomTextStyles.titleMediumSemiBold, ), subtitle: Text( - DateFormat('dd.MM.yyyy').format(DateTime.parse(post?['post']['updated_at'])), + DateFormat('dd.MM.yyyy') + .format(DateTime.parse(post?['updated_at'])), style: theme.textTheme.bodyMedium, ), onTap: () => GoRouter.of(context).goNamed( 'blogPostScreen', - extra: post?['post']['id'].toString(), + extra: post?['id'].toString(), ), trailing: PopupMenuButton( onSelected: (value) => print("tap"), @@ -197,7 +204,7 @@ class FeedScreen extends StatelessWidget { Align( alignment: Alignment.center, child: Text( - post?['post']['title'], + post?['title'], style: CustomTextStyles.titleMediumBlack, ), ), @@ -206,16 +213,17 @@ class FeedScreen extends StatelessWidget { ), SizedBox(height: 8.0), Text( - post?['post']['description'], + post?['description'], style: CustomTextStyles.bodyMediumBluegray800, ), SizedBox(height: 16.0), CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (post?['post']['image'] ?? ''), + imageUrl: dotenv.env['STORAGE_URL']! + (post?['image'] ?? ''), imageBuilder: (context, imageProvider) => Stack( children: [ ClipRRect( - borderRadius: const BorderRadius.all(Radius.circular(8.0)), + borderRadius: + const BorderRadius.all(Radius.circular(8.0)), child: Image( image: imageProvider, ), @@ -225,39 +233,47 @@ class FeedScreen extends StatelessWidget { placeholder: (context, url) => CircularProgressIndicator(), ), SizedBox(height: 16.0), - Row(children: [ - Padding( - padding: EdgeInsets.only(left: 4), - child: Row(children: [ - Padding( - padding: EdgeInsets.only(right: 4), - child: Icon(Icons.comment_outlined), - ), - Text( - "Комментировать", - ), - ],), - ), - Spacer(), - Row(children: [ + Row( + children: [ Padding( - padding: const EdgeInsets.only(right: 4), - child: Icon(Icons.favorite_outline), + padding: EdgeInsets.only(left: 4), + child: Row( + children: [ + Padding( + padding: EdgeInsets.only(right: 4), + child: Icon(Icons.comment_outlined), + ), + Text( + "Комментировать", + ), + ], + ), ), - Text( - "Нравится", + Spacer(), + Row( + children: [ + Padding( + padding: const EdgeInsets.only(right: 4), + child: Icon(Icons.favorite_outline), + ), + Text( + "Нравится", + ), + ], ), - ],), - Spacer(), - Padding( - padding: EdgeInsets.only(right: 4), - child: Icon(Icons.share_outlined), - ), - ],), + Spacer(), + Padding( + padding: EdgeInsets.only(right: 4), + child: Icon(Icons.share_outlined), + ), + ], + ), ], ), ), - ],),); + ], + ), + ); } Function onTapBack(BuildContext context) { 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 cfecf5a..806768c 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 @@ -48,10 +48,10 @@ class MyProfileBloc extends Bloc { data.containsKey('userDetails') && data.containsKey('chartPoints') && data.containsKey('circumferences')) { - final avatarBox = await Hive.openBox('avatar'); - final avatar = data['user']['profile_photo_path']; - print(avatar); - avatarBox.put('avatar', avatar); + final avatarBox = await Hive.openBox('avatar'); + final avatar = data['user']['profile_photo_path']; + print(avatar); + avatarBox.put('avatar', avatar); if (state is MyProfileLoadedState) { var currentState = state as MyProfileLoadedState; var plans = [] @@ -61,46 +61,48 @@ class MyProfileBloc extends Bloc { ..addAll(data["paidPlan"]) ..addAll(data["requestedPlan"]) ..addAll(data["initedPlan"]); - emit((currentState).copyWith( - chartPoints: currentState.chartPoints, - chartDates: currentState.chartDates, - circumferences: currentState.circumferences, - user: data['user'], - userDetails: data['userDetails'], - plans: plans, - token: token, - chestCircumferenceController: TextEditingController(), - waistCircumferenceController: TextEditingController(), - hipCircumferenceController: TextEditingController(), - weightController: TextEditingController(), - 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, - allergiesFormController: currentState.allergiesFormController, - pillsFormController: currentState.pillsFormController, - favoriteFormController: currentState.favoriteFormController, - unfavoriteFormController: currentState.unfavoriteFormController, - additionalFormController: currentState.additionalFormController, - sportsFormController: currentState.sportsFormController, - dateFormController: currentState.dateFormController, - hypoFormController: currentState.hypoFormController, - hyperFormController: currentState.hyperFormController, - selectedCity: currentState.selectedCity, - selectedCountry: currentState.selectedCountry, - selectedActivity: currentState.selectedActivity, - myProfileModelObj: currentState.myProfileModelObj, - ),); + emit( + (currentState).copyWith( + chartPoints: currentState.chartPoints, + chartDates: currentState.chartDates, + circumferences: currentState.circumferences, + user: data['user'], + userDetails: data['userDetails'], + plans: plans, + token: token, + chestCircumferenceController: TextEditingController(), + waistCircumferenceController: TextEditingController(), + hipCircumferenceController: TextEditingController(), + weightController: TextEditingController(), + 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, + allergiesFormController: currentState.allergiesFormController, + pillsFormController: currentState.pillsFormController, + favoriteFormController: currentState.favoriteFormController, + unfavoriteFormController: currentState.unfavoriteFormController, + additionalFormController: currentState.additionalFormController, + sportsFormController: currentState.sportsFormController, + dateFormController: currentState.dateFormController, + hypoFormController: currentState.hypoFormController, + hyperFormController: currentState.hyperFormController, + selectedCity: currentState.selectedCity, + selectedCountry: currentState.selectedCountry, + selectedActivity: currentState.selectedActivity, + myProfileModelObj: currentState.myProfileModelObj, + ), + ); } else { var plans = [] ..addAll(data["finishedPlans"]) @@ -166,67 +168,87 @@ class MyProfileBloc extends Bloc { } } - emit(MyProfileLoadedState( - chartPoints: chartPoints, - chartDates: dates, - circumferences: circumferences, - user: data['user'], - userDetails: data['userDetails'], - plans: plans, - token: token, - chestCircumferenceController: TextEditingController(), - waistCircumferenceController: TextEditingController(), - hipCircumferenceController: TextEditingController(), - hypoFormController: data['userDetails']['has_hypo'].toString(), - hyperFormController: data['userDetails']['has_hyper'].toString(), - chestCircumferenceFormController: TextEditingController( - text: data['userDetails']['chest_circumference']?.toString(),), - waistCircumferenceFormController: TextEditingController( - text: data['userDetails']['waist_circumference']?.toString(),), - hipCircumferenceFormController: TextEditingController( - text: data['userDetails']['hip_circumference']?.toString(),), - weightController: TextEditingController( - text: data['userDetails']['weight']?.toString(),), - weightFormController: TextEditingController( - text: data['userDetails']['weight']?.toString(),), - 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']), - heightFormController: TextEditingController( - text: data['userDetails']['height']?.toString(),), - upPressureFormController: TextEditingController( - text: data['userDetails']['blood_pressure_up']?.toString(),), - downPressureFormController: TextEditingController( - text: data['userDetails']['blood_pressure_down']?.toString(),), - allergiesFormController: TextEditingController( - text: data['userDetails']['about_alergy'],), - pillsFormController: TextEditingController( - text: data['userDetails']['about_taking_pils'],), - sportsFormController: TextEditingController( - text: data['userDetails']['about_sport_hobbies'],), - favoriteFormController: TextEditingController( - text: data['userDetails']['favorite_foods'],), - unfavoriteFormController: TextEditingController( - text: data['userDetails']['unfavorite_foods'],), - additionalFormController: TextEditingController( - text: data['userDetails']['additional_info'],), - dateFormController: - TextEditingController(text: data['userDetails']['birthdate']), - selectedCity: data['userDetails']['city'], - selectedCountry: data['userDetails']['country'], - selectedActivity: determineActivityLevel( - data['userDetails']['activity_coefficient'],), - ),); + emit( + MyProfileLoadedState( + chartPoints: chartPoints, + chartDates: dates, + circumferences: circumferences, + user: data['user'], + userDetails: data['userDetails'], + plans: plans, + token: token, + chestCircumferenceController: TextEditingController(), + waistCircumferenceController: TextEditingController(), + hipCircumferenceController: TextEditingController(), + hypoFormController: data['userDetails']['has_hypo'].toString(), + hyperFormController: + data['userDetails']['has_hyper'].toString(), + chestCircumferenceFormController: TextEditingController( + text: data['userDetails']['chest_circumference']?.toString(), + ), + waistCircumferenceFormController: TextEditingController( + text: data['userDetails']['waist_circumference']?.toString(), + ), + hipCircumferenceFormController: TextEditingController( + text: data['userDetails']['hip_circumference']?.toString(), + ), + weightController: TextEditingController( + text: data['userDetails']['weight']?.toString(), + ), + weightFormController: TextEditingController( + text: data['userDetails']['weight']?.toString(), + ), + 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']), + heightFormController: TextEditingController( + text: data['userDetails']['height']?.toString(), + ), + upPressureFormController: TextEditingController( + text: data['userDetails']['blood_pressure_up']?.toString(), + ), + downPressureFormController: TextEditingController( + text: data['userDetails']['blood_pressure_down']?.toString(), + ), + allergiesFormController: TextEditingController( + text: data['userDetails']['about_alergy'], + ), + pillsFormController: TextEditingController( + text: data['userDetails']['about_taking_pils'], + ), + sportsFormController: TextEditingController( + text: data['userDetails']['about_sport_hobbies'], + ), + favoriteFormController: TextEditingController( + text: data['userDetails']['favorite_foods'], + ), + unfavoriteFormController: TextEditingController( + text: data['userDetails']['unfavorite_foods'], + ), + additionalFormController: TextEditingController( + text: data['userDetails']['additional_info'], + ), + dateFormController: TextEditingController( + text: data['userDetails']['birthdate']), + selectedCity: data['userDetails']['city'], + selectedCountry: data['userDetails']['country'], + selectedActivity: determineActivityLevel( + data['userDetails']['activity_coefficient'], + ), + ), + ); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку emit( - MyProfileErrorState('Некоторые необходимые данные отсутствуют.'),); + MyProfileErrorState('Некоторые необходимые данные отсутствуют.'), + ); } } else { // Статус ответа не равен 200, обрабатываем ошибку @@ -253,7 +275,9 @@ class MyProfileBloc extends Bloc { } // колхоз, но свитчкейсы в дарте странно ведут себя при сравнении double Future _uploadAvatar( - UploadAvatar event, Emitter emit,) async { + UploadAvatar event, + Emitter emit, + ) async { if (state is MyProfileLoadedState) { var currentState = state as MyProfileLoadedState; @@ -279,7 +303,8 @@ class MyProfileBloc extends Bloc { return imageUrl; } else { throw Exception( - 'Failed to upload image. Status code: ${streamedResponse.statusCode} ${streamedResponse}}',); + 'Failed to upload image. Status code: ${streamedResponse.statusCode} ${streamedResponse}}', + ); } } } diff --git a/lib/presentation/users/subscribers_screen/bloc/subscribers_bloc.dart b/lib/presentation/users/subscribers_screen/bloc/subscribers_bloc.dart new file mode 100644 index 0000000..1bb1bcf --- /dev/null +++ b/lib/presentation/users/subscribers_screen/bloc/subscribers_bloc.dart @@ -0,0 +1,74 @@ +//import 'package:eatvio_app/presentation/auth/auth_screen/auth_screen.dart'; +import 'dart:async'; + +import 'package:eatvio_app/app_router.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'; + +part 'subscribers_event.dart'; +part 'subscribers_state.dart'; + +/// A bloc that manages the state of a Subscribers according to the event that is dispatched to it. +class SubscribersBloc extends Bloc { + SubscribersBloc(SubscribersState initialState) : super(initialState) { + on(_onInitialize); + } + + Future _onInitialize( + SubscribersInitialEvent event, + Emitter emit, + ) async { + try { + final box = await Hive.openBox('token'); + final token = box.get('token'); + if (token == null) { + AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); + } + final response = await http.get( + Uri.parse(dotenv.env['SERVER_ROOT']! + '/profile/subscribers'), + headers: { + 'Authorization': 'Bearer $token', + }, + ); + print('Got response'); + print(response.statusCode); + print(response.body); + if (response.statusCode == 200) { + print('Got 200'); + final data = jsonDecode(response.body); + if (data is List) { + print('Got List'); + if (state is SubscribersLoadedState) { + print('Got loaded'); + var currentState = state as SubscribersLoadedState; + emit((currentState).copyWith( + subscribers: data, + myProfileModelObj: currentState.myProfileModelObj, + )); + } else { + print('Got unloaded'); + emit(SubscribersLoadedState( + subscribers: data, + )); + } + } else { + // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку + emit(SubscribersErrorState('Неверный формат ответа API.')); + } + } else { + // Статус ответа не равен 200, обрабатываем ошибку + emit(SubscribersErrorState('Ошибка сервера: ${response.statusCode}')); + } + } catch (e) { + // Ошибка при декодировании JSON или другая ошибка выполнения + emit(SubscribersErrorState('Ошибка при получении данных ленты: $e')); + } + } +} diff --git a/lib/presentation/users/subscribers_screen/bloc/subscribers_event.dart b/lib/presentation/users/subscribers_screen/bloc/subscribers_event.dart new file mode 100644 index 0000000..3034e63 --- /dev/null +++ b/lib/presentation/users/subscribers_screen/bloc/subscribers_event.dart @@ -0,0 +1,16 @@ +// ignore_for_file: must_be_immutable + +part of 'subscribers_bloc.dart'; + +/// Abstract class for all events that can be dispatched from the +///Subscribers widget. +/// +/// Events must be immutable and implement the [Equatable] interface. +@immutable +abstract class SubscribersEvent extends Equatable {} + +/// Event that is dispatched when the Subscribers widget is first created. +class SubscribersInitialEvent extends SubscribersEvent { + @override + List get props => []; +} diff --git a/lib/presentation/users/subscribers_screen/bloc/subscribers_state.dart b/lib/presentation/users/subscribers_screen/bloc/subscribers_state.dart new file mode 100644 index 0000000..151e062 --- /dev/null +++ b/lib/presentation/users/subscribers_screen/bloc/subscribers_state.dart @@ -0,0 +1,49 @@ +// ignore_for_file: must_be_immutable + +part of 'subscribers_bloc.dart'; + +class SubscribersState extends Equatable { + const SubscribersState({this.myProfileModelObj}); + + final SubscribersModel? myProfileModelObj; + + @override + List get props => [myProfileModelObj]; +} + +class SubscribersInitialState extends SubscribersState { + 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); + + SubscribersModel? myProfileModelObj; + dynamic subscribers; + @override + List get props => [ + myProfileModelObj, + subscribers, + ]; + SubscribersLoadedState copyWith({ + SubscribersModel? myProfileModelObj, + dynamic subscribers, + }) { + return SubscribersLoadedState( + myProfileModelObj: myProfileModelObj ?? this.myProfileModelObj, + subscribers: subscribers ?? this.subscribers, + ); + } +} + +class SubscribersErrorState extends SubscribersState { + final String errorMessage; + + const SubscribersErrorState(this.errorMessage); + + @override + List get props => [errorMessage]; +} diff --git a/lib/presentation/users/subscribers_screen/models/subscribers_model.dart b/lib/presentation/users/subscribers_screen/models/subscribers_model.dart new file mode 100644 index 0000000..f7d0cda --- /dev/null +++ b/lib/presentation/users/subscribers_screen/models/subscribers_model.dart @@ -0,0 +1,16 @@ +// ignore_for_file: must_be_immutable + +import 'package:equatable/equatable.dart'; + +/// This class defines the variables used in the [k0_page], +/// and is typically used to hold data that is passed between different parts of the application. +class SubscribersModel extends Equatable { + SubscribersModel(); + + SubscribersModel copyWith() { + return SubscribersModel(); + } + + @override + List get props => []; +} diff --git a/lib/presentation/users/subscribers_screen/subscribers_screen.dart b/lib/presentation/users/subscribers_screen/subscribers_screen.dart new file mode 100644 index 0000000..f2ac7e1 --- /dev/null +++ b/lib/presentation/users/subscribers_screen/subscribers_screen.dart @@ -0,0 +1,213 @@ +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()), + child: SubscribersScreen()); + } + + Widget build(BuildContext context) { + return BlocBuilder( + builder: (context, state) { + if (state is SubscribersInitialState) { + // Это начальное состояние, данные ещё не загружены. + return CircularProgressIndicator( + color: Colors.white, + backgroundColor: Colors.white, + ); + } else if (state is SubscribersLoadedState) { + // Данные загружены, можно строить экран. + return _buildSubscribersScreen(context, state); + } else { + // Другие состояния, если они есть. + return Container(); // Пустой контейнер для необработанных состояний. + } + }, + ); + } + + _buildSubscribersScreen(BuildContext context, SubscribersLoadedState state) { + return Scaffold( + backgroundColor: Colors.grey[200], + resizeToAvoidBottomInset: true, + body: SingleChildScrollView( + child: Container( + width: double.maxFinite, + decoration: BoxDecoration(color: Colors.grey[200]), + child: Padding( + padding: EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox(height: 10), + 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(), + ), + title: Padding( + padding: EdgeInsets.only(left: 20.h), + child: Row( + children: [ + AppbarSubtitle( + text: "Мои подписчики", + 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)), + ) + ], + ), + ), + ), + ), + _buildSearch(context), + SizedBox(height: 16), + _buildSubscribersList(context, state), + ], + ), + ), + ), + ), + ); + } + + _buildSearch(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: 2, + blurRadius: 5, + offset: Offset(0, 3), + ), + ], + ), + child: Padding( + padding: const EdgeInsets.all(12.0), + child: Column( + children: [ + CustomSearchView( + hintText: "Поиск", + ), + SizedBox(height: 10), + Row( + children: [ + Flexible( + flex: 5, + child: CustomOutlinedButton( + text: "Найти", + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + ), + ), + SizedBox(width: 8), // Add some spacing between the buttons + Flexible( + flex: 1, + child: CustomOutlinedButton( + text: "+", + onPressed: () => + GoRouter.of(context).goNamed('blogPostCreateScreen'), + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + ), + ), + ], + ) + ], + ), + ), + ); + } + + _buildSubscribersList(BuildContext context, SubscribersLoadedState state) { + List subscriberWidgets = []; + + if (state.subscribers != null) { + for (var subscriber in state.subscribers!) { + subscriberWidgets.add(_buildSubscriberEntry(subscriber, context)); + } + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: subscriberWidgets, + ); + } + + _buildSubscriberEntry(BuildContext context, subscriber) { + 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), + ), + ], + ), + child: ListTile( + leading: CachedNetworkImage( + imageUrl: dotenv.env['STORAGE_URL']! + subscriber['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( + subscriber?['title'] ?? '', + style: CustomTextStyles.titleMediumSemiBold, + ), + subtitle: Text(subscriber?['description'] ?? ''), + trailing: GestureDetector(child: Icon(Icons.edit)), + )); + } +} -- 2.49.1 From 70296bc48500aa1501f4259d375a8c3743439037 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Thu, 27 Jun 2024 13:24:44 +0300 Subject: [PATCH 009/110] feat(chat): fix token storage --- .../initialization_cubit.dart | 14 ++------------ lib/core/token_storage.dart | 15 ++++++--------- pubspec.yaml | 4 +--- 3 files changed, 9 insertions(+), 24 deletions(-) diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index 57544ae..a3db291 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -12,7 +12,6 @@ class InitializationCubit extends Cubit { runInitialization() async { try { await TokenStorage.haveTokenInStorage(); - final wsUrl = await chatRepository.getWebsocket(); PusherOptions options = PusherOptions( @@ -22,12 +21,12 @@ class InitializationCubit extends Cubit { auth: PusherAuth( 'wss://' + wsUrl.host + '/app/' + wsUrl.key, headers: { - 'Authorization': 'Bearer ${TokenStorage.getTokenFromStorage()}', + 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, ), ); - PusherClient pusherClient = PusherClient( + PusherClient pusherClient = await PusherClient( wsUrl.key, options, autoConnect: true, @@ -37,15 +36,6 @@ class InitializationCubit extends Cubit { await pusherClient.connect(); emit(const InitializationState.success()); - - Channel channel = pusherClient.subscribe('private-direct-chat.' + '7909ea56-7822-4d5f-8892-134bc937127f'); - - channel.bind("pusher_internal:subscription_succeeded", (PusherEvent? event) { - channel.trigger("pusher_internal:subscription_succeeded", {}); - }); - - channel.registerListener('pusher:subscribe', (data) => print(data.toString())); - } catch (e) { print(e); emit(InitializationState.error(errorMessage: e.toString())); diff --git a/lib/core/token_storage.dart b/lib/core/token_storage.dart index 82d2935..1179241 100644 --- a/lib/core/token_storage.dart +++ b/lib/core/token_storage.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/locator_service.dart'; import 'package:hive_flutter/hive_flutter.dart'; abstract class TokenStorage { - static addTokenToDioHeader(String token) { + static _addTokenToDioHeader(String token) { sl().options.headers['Authorization'] = 'Bearer $token'; } @@ -13,20 +13,17 @@ abstract class TokenStorage { if (token == null) { return false; } else { - addTokenToDioHeader(token); + _addTokenToDioHeader(token); return true; } } - static getTokenFromStorage() async => await Hive.openBox('token') - ..get('token'); + static Future getTokenFromStorage() async => (await Hive.openBox('token')).get('token'); static saveTokenInStorage(String token) async { - await Hive.openBox('token') - ..put('token', token); - addTokenToDioHeader(token); + (await Hive.openBox('token')).put('token', token); + _addTokenToDioHeader(token); } - static removeTokenInStorage(String token) async => await Hive.openBox('token') - ..delete('token'); + static removeTokenInStorage() async => (await Hive.openBox('token')).delete('token'); } diff --git a/pubspec.yaml b/pubspec.yaml index 353e7ef..8633537 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -60,9 +60,7 @@ dependencies: # http request dio: ^5.4.3+1 # websocket - pusher_client: - git: - url: https://github.com/bihim/pusher_client + pusher_client: ^2.0.0 # photo gallery viewer + dismissible page photo_view: ^0.15.0 dismissible_page: ^1.0.2 -- 2.49.1 From 58a7ca933dd7a6ab18faa3e61e6f6ccfcbe00b00 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 27 Jun 2024 16:50:23 +0300 Subject: [PATCH 010/110] feat(feed): Dio, retrofit and freezed model stump --- lib/core/token_storage.dart | 17 +- .../bloc/blog_post_create_bloc.dart | 48 ++-- .../bloc/blog_post_create_state.dart | 14 +- .../blog_post_create_screen.dart | 20 +- .../blog_post_create_credentials_model.dart | 16 ++ ...post_create_credentials_model.freezed.dart | 235 ++++++++++++++++++ .../blog_post_create_credentials_model.g.dart | 25 ++ .../repositories/blog_repository.dart | 20 ++ .../services/blog_service.dart | 14 ++ .../services/blog_service.g.dart | 78 ++++++ .../bloc/blog_post_edit_bloc.dart | 32 ++- .../bloc/blog_post_edit_state.dart | 21 +- .../blog_post_edit_screen.dart | 17 +- 13 files changed, 481 insertions(+), 76 deletions(-) create mode 100644 lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.dart create mode 100644 lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.freezed.dart create mode 100644 lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.g.dart create mode 100644 lib/presentation/feed/blog_post_create_screen/repositories/blog_repository.dart create mode 100644 lib/presentation/feed/blog_post_create_screen/services/blog_service.dart create mode 100644 lib/presentation/feed/blog_post_create_screen/services/blog_service.g.dart diff --git a/lib/core/token_storage.dart b/lib/core/token_storage.dart index 82d2935..01ac606 100644 --- a/lib/core/token_storage.dart +++ b/lib/core/token_storage.dart @@ -3,7 +3,7 @@ import 'package:eatvio_app/locator_service.dart'; import 'package:hive_flutter/hive_flutter.dart'; abstract class TokenStorage { - static addTokenToDioHeader(String token) { + static _addTokenToDioHeader(String token) { sl().options.headers['Authorization'] = 'Bearer $token'; } @@ -13,20 +13,19 @@ abstract class TokenStorage { if (token == null) { return false; } else { - addTokenToDioHeader(token); + _addTokenToDioHeader(token); return true; } } - static getTokenFromStorage() async => await Hive.openBox('token') - ..get('token'); + static Future getTokenFromStorage() async => + (await Hive.openBox('token')).get('token'); static saveTokenInStorage(String token) async { - await Hive.openBox('token') - ..put('token', token); - addTokenToDioHeader(token); + (await Hive.openBox('token')).put('token', token); + _addTokenToDioHeader(token); } - static removeTokenInStorage(String token) async => await Hive.openBox('token') - ..delete('token'); + static removeTokenInStorage() async => + (await Hive.openBox('token')).delete('token'); } 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 d2f448b..7ddbaca 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,11 +1,11 @@ import 'dart:async'; +import 'package:dio/dio.dart'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/locator_service.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:hive/hive.dart'; -import 'package:http/http.dart' as http; import 'package:image_picker/image_picker.dart'; import 'dart:convert'; import '/core/app_export.dart'; @@ -39,7 +39,7 @@ class BlogPostCreateBloc blog_postModelObj: currentState.blog_postModelObj, title: currentState.title, description: currentState.description, - youtube_url: currentState.youtube_url, + youtubeURL: currentState.youtubeURL, token: currentState.token, ), ); @@ -49,7 +49,7 @@ class BlogPostCreateBloc token: token, title: TextEditingController(), description: TextEditingController(), - youtube_url: TextEditingController(), + youtubeURL: TextEditingController(), ), ); } @@ -64,8 +64,9 @@ class BlogPostCreateBloc var response = await sendBlogPost( currentState.title?.text, - currentState.youtube_url?.text, + currentState.youtubeURL?.text, currentState.description?.text, + currentState.image, ); if (response.statusCode == 200) { @@ -78,34 +79,35 @@ class BlogPostCreateBloc } } - FutureOr sendBlogPost( - String? title, - String? youtube_url, - String? description, - ) async { - String url = '${dotenv.env['SERVER_ROOT']!}/feed/create'; - final box = await Hive.openBox('token'); - final token = box.get('token'); + sendBlogPost(String? title, String? youtubeURL, String? description, + XFile? image) async { + String url = '/blog_post/create'; + final Map credentials = { 'title': title, 'description': description, - 'youtube_url': youtube_url, + 'youtube_url': youtubeURL, 'status': 'active', + 'image': image, }; - 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 sl().post( + url, + data: json.encode(credentials), ); return response; } FutureOr _uploadImages( - UploadImages event, Emitter emit) {} + UploadImages event, Emitter emit) { + if (state is BlogPostCreateLoadedState) { + var currentState = state as BlogPostCreateLoadedState; + emit( + currentState.copyWith( + image: event.image, + ), + ); + } + } } 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 6014e3d..4da3f5a 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 @@ -27,33 +27,37 @@ class BlogPostCreateLoadedState extends BlogPostCreateState { this.blog_postModelObj, this.title, this.description, - this.youtube_url, + this.youtubeURL, + this.image, this.isLoading = false, }); BlogPostCreateModel? blog_postModelObj; TextEditingController? title; TextEditingController? description; - TextEditingController? youtube_url; + TextEditingController? youtubeURL; String? token; bool isLoading; + XFile? image; @override List get props => - [blog_postModelObj, title, description, youtube_url]; + [blog_postModelObj, title, description, youtubeURL]; BlogPostCreateLoadedState copyWith({ BlogPostCreateModel? blog_postModelObj, TextEditingController? title, TextEditingController? description, - TextEditingController? youtube_url, + TextEditingController? youtubeURL, String? token, + XFile? image, bool isLoading = false, }) { return BlogPostCreateLoadedState( blog_postModelObj: blog_postModelObj ?? this.blog_postModelObj, title: title ?? this.title, description: description ?? this.description, - youtube_url: youtube_url ?? this.youtube_url, + youtubeURL: youtubeURL ?? this.youtubeURL, token: token ?? this.token, + image: image ?? this.image, isLoading: this.isLoading, ); } diff --git a/lib/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart b/lib/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart index f02a512..225a771 100644 --- a/lib/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart +++ b/lib/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart @@ -5,6 +5,7 @@ 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'; class BlogPostCreateScreen extends StatelessWidget { const BlogPostCreateScreen({Key? key}) : super(key: key); @@ -43,6 +44,7 @@ class BlogPostCreateScreen extends StatelessWidget { } _buildBlogPostCreate(BuildContext context, BlogPostCreateLoadedState state) { + print(state.image); return Scaffold( resizeToAvoidBottomInset: false, body: Container( @@ -85,7 +87,7 @@ class BlogPostCreateScreen extends StatelessWidget { Text("Ссылка на YouTube", style: theme.textTheme.bodyLarge), CustomTextFormField( - controller: state.youtube_url, + controller: state.youtubeURL, validator: _validateYouTubeLink, ), SizedBox(height: 8.0), @@ -101,7 +103,7 @@ class BlogPostCreateScreen extends StatelessWidget { // Add widget for image upload here CustomOutlinedButton( onPressed: () => _submitForm(context, state.title!.text, - state.description!.text, state.youtube_url!.text), + state.description!.text, state.youtubeURL!.text), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, text: 'Создать', ), @@ -144,7 +146,7 @@ _buildAddPhoto(BuildContext context, BlogPostCreateLoadedState state) { onTap: addImage(context, isLoading), child: Stack( children: [ - if (!isLoading) + if (state.image == null) Container( margin: EdgeInsets.symmetric(horizontal: 10.h), padding: EdgeInsets.symmetric( @@ -158,8 +160,6 @@ _buildAddPhoto(BuildContext context, BlogPostCreateLoadedState state) { mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: [ - // Показывайте прелоадер, если загрузка активна - Padding( padding: EdgeInsets.only( left: 7.h, @@ -178,7 +178,7 @@ _buildAddPhoto(BuildContext context, BlogPostCreateLoadedState state) { ], ), ), - if (isLoading) + if (state.image != null) Container( margin: EdgeInsets.symmetric(horizontal: 10.h), padding: EdgeInsets.symmetric( @@ -188,12 +188,8 @@ _buildAddPhoto(BuildContext context, BlogPostCreateLoadedState state) { decoration: AppDecoration.fillGray.copyWith( borderRadius: BorderRadiusStyle.roundedBorder5, ), - child: Center( - child: CircularProgressIndicator( - color: appTheme - .blueGray300), // Замените на свой прелоадер при необходимости - ), - ), + child: Image(image: FileImage(File(state.image!.path))), + ) ], ), ); diff --git a/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.dart b/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.dart new file mode 100644 index 0000000..1464eb0 --- /dev/null +++ b/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.dart @@ -0,0 +1,16 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +part 'blog_post_create_credentials_model.freezed.dart'; +part 'blog_post_create_credentials_model.g.dart'; + +@freezed +class BlogPostCreateCredentialsModel with _$BlogPostCreateCredentialsModel { + const factory BlogPostCreateCredentialsModel({ + required String title, + required String description, + @JsonKey(name: 'youtube_url') required String youtubeUrl, + @Default('active') String status, + }) = _BlogPostCreateCredentialsModel; + + factory BlogPostCreateCredentialsModel.fromJson(Map json) => + _$BlogPostCreateCredentialsModelFromJson(json); +} 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 new file mode 100644 index 0000000..87eb9e1 --- /dev/null +++ b/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.freezed.dart @@ -0,0 +1,235 @@ +// 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 'blog_post_create_credentials_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'); + +BlogPostCreateCredentialsModel _$BlogPostCreateCredentialsModelFromJson( + Map json) { + return _BlogPostCreateCredentialsModel.fromJson(json); +} + +/// @nodoc +mixin _$BlogPostCreateCredentialsModel { + String get title => throw _privateConstructorUsedError; + String get description => throw _privateConstructorUsedError; + @JsonKey(name: 'youtube_url') + String get youtubeUrl => throw _privateConstructorUsedError; + String get status => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $BlogPostCreateCredentialsModelCopyWith + get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $BlogPostCreateCredentialsModelCopyWith<$Res> { + 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}); +} + +/// @nodoc +class _$BlogPostCreateCredentialsModelCopyWithImpl<$Res, + $Val extends BlogPostCreateCredentialsModel> + implements $BlogPostCreateCredentialsModelCopyWith<$Res> { + _$BlogPostCreateCredentialsModelCopyWithImpl(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? title = null, + Object? description = null, + Object? youtubeUrl = null, + Object? status = null, + }) { + return _then(_value.copyWith( + title: null == title + ? _value.title + : title // ignore: cast_nullable_to_non_nullable + as String, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + youtubeUrl: null == youtubeUrl + ? _value.youtubeUrl + : youtubeUrl // ignore: cast_nullable_to_non_nullable + as String, + status: null == status + ? _value.status + : status // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +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}); +} + +/// @nodoc +class __$$BlogPostCreateCredentialsModelImplCopyWithImpl<$Res> + extends _$BlogPostCreateCredentialsModelCopyWithImpl<$Res, + _$BlogPostCreateCredentialsModelImpl> + implements _$$BlogPostCreateCredentialsModelImplCopyWith<$Res> { + __$$BlogPostCreateCredentialsModelImplCopyWithImpl( + _$BlogPostCreateCredentialsModelImpl _value, + $Res Function(_$BlogPostCreateCredentialsModelImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? title = null, + Object? description = null, + Object? youtubeUrl = null, + Object? status = null, + }) { + return _then(_$BlogPostCreateCredentialsModelImpl( + title: null == title + ? _value.title + : title // ignore: cast_nullable_to_non_nullable + as String, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + youtubeUrl: null == youtubeUrl + ? _value.youtubeUrl + : youtubeUrl // ignore: cast_nullable_to_non_nullable + as String, + status: null == status + ? _value.status + : status // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$BlogPostCreateCredentialsModelImpl + implements _BlogPostCreateCredentialsModel { + const _$BlogPostCreateCredentialsModelImpl( + {required this.title, + required this.description, + @JsonKey(name: 'youtube_url') required this.youtubeUrl, + this.status = 'active'}); + + factory _$BlogPostCreateCredentialsModelImpl.fromJson( + Map json) => + _$$BlogPostCreateCredentialsModelImplFromJson(json); + + @override + final String title; + @override + final String description; + @override + @JsonKey(name: 'youtube_url') + final String youtubeUrl; + @override + @JsonKey() + final String status; + + @override + String toString() { + return 'BlogPostCreateCredentialsModel(title: $title, description: $description, youtubeUrl: $youtubeUrl, status: $status)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (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.status, status) || other.status == status)); + } + + @JsonKey(ignore: true) + @override + 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); + + @override + Map toJson() { + return _$$BlogPostCreateCredentialsModelImplToJson( + this, + ); + } +} + +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; + + @override + String get title; + @override + String get description; + @override + @JsonKey(name: 'youtube_url') + String get youtubeUrl; + @override + String get status; + @override + @JsonKey(ignore: true) + _$$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 new file mode 100644 index 0000000..bf339e9 --- /dev/null +++ b/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.g.dart @@ -0,0 +1,25 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'blog_post_create_credentials_model.dart'; + +// ************************************************************************** +// 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', + ); + +Map _$$BlogPostCreateCredentialsModelImplToJson( + _$BlogPostCreateCredentialsModelImpl instance) => + { + 'title': instance.title, + 'description': instance.description, + 'youtube_url': instance.youtubeUrl, + 'status': instance.status, + }; diff --git a/lib/presentation/feed/blog_post_create_screen/repositories/blog_repository.dart b/lib/presentation/feed/blog_post_create_screen/repositories/blog_repository.dart new file mode 100644 index 0000000..74f79cd --- /dev/null +++ b/lib/presentation/feed/blog_post_create_screen/repositories/blog_repository.dart @@ -0,0 +1,20 @@ +import 'package:eatvio_app/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.dart'; +import 'package:eatvio_app/presentation/feed/blog_post_create_screen/services/blog_service.dart'; + +class BlogRepository { + final BlogService blogService; + + BlogRepository({ + required this.blogService, + }); + + Future createBlogPost( + BlogPostCreateCredentialsModel model) async { + try { + return (await blogService.createBlogPost(model)); + } catch (e) { + print(e); + throw (e); + } + } +} diff --git a/lib/presentation/feed/blog_post_create_screen/services/blog_service.dart b/lib/presentation/feed/blog_post_create_screen/services/blog_service.dart new file mode 100644 index 0000000..e559383 --- /dev/null +++ b/lib/presentation/feed/blog_post_create_screen/services/blog_service.dart @@ -0,0 +1,14 @@ +import 'package:eatvio_app/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.dart'; +import 'package:dio/dio.dart'; +import 'package:retrofit/retrofit.dart'; + +part 'blog_service.g.dart'; + +@RestApi() +abstract class BlogService { + factory BlogService(Dio dio, {String baseUrl}) = _BlogService; + + @POST('/blog_post/create') + Future createBlogPost( + BlogPostCreateCredentialsModel model); +} diff --git a/lib/presentation/feed/blog_post_create_screen/services/blog_service.g.dart b/lib/presentation/feed/blog_post_create_screen/services/blog_service.g.dart new file mode 100644 index 0000000..eef2fc9 --- /dev/null +++ b/lib/presentation/feed/blog_post_create_screen/services/blog_service.g.dart @@ -0,0 +1,78 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'blog_service.dart'; + +// ************************************************************************** +// RetrofitGenerator +// ************************************************************************** + +// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers + +class _BlogService implements BlogService { + _BlogService( + this._dio, { + this.baseUrl, + }); + + final Dio _dio; + + String? baseUrl; + + @override + Future createBlogPost( + BlogPostCreateCredentialsModel model) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio.fetch>( + _setStreamType(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/blog_post/create', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final value = BlogPostCreateCredentialsModel.fromJson(_result.data!); + 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/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 6b45f84..07dc31c 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 @@ -44,22 +44,29 @@ class BlogPostEditBloc extends Bloc { if (data is Map) { if (state is BlogPostEditLoadedState) { var currentState = state as BlogPostEditLoadedState; - emit(currentState.copyWith( + emit( + currentState.copyWith( blog_postModelObj: currentState.blog_postModelObj, blog_post: currentState.blog_post, title: currentState.title, description: currentState.description, - youtube_url: currentState.youtube_url,),); + youtubeURL: currentState.youtubeURL, + ), + ); } else { - emit(BlogPostEditLoadedState( + emit( + BlogPostEditLoadedState( blog_post: data, title: TextEditingController(text: data['title']), description: TextEditingController(text: data['description']), - youtube_url: TextEditingController(text: data['youtube_url']),),); + youtubeURL: TextEditingController(text: data['youtubeURL']), + ), + ); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку - emit(BlogPostEditErrorState('Некоторые необходимые данные отсутствуют.')); + emit(BlogPostEditErrorState( + 'Некоторые необходимые данные отсутствуют.')); } } else { // Статус ответа не равен 200, обрабатываем ошибку @@ -71,21 +78,24 @@ 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; var response = await sendBlogPost( currentState.blog_post, currentState.title?.text, - currentState.youtube_url?.text, + currentState.youtubeURL?.text, currentState.description?.text, ); 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}'); } } } @@ -93,7 +103,7 @@ class BlogPostEditBloc extends Bloc { FutureOr sendBlogPost( Map? blog_post, String? title, - String? youtube_url, + String? youtubeURL, String? description, ) async { int id = blog_post?['id']; @@ -103,7 +113,7 @@ class BlogPostEditBloc extends Bloc { 'id': id, 'title': title, 'description': description, - 'youtube_url': youtube_url, + 'youtubeURL': youtubeURL, }; var response = await http.post( 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 4381948..cc2d5f3 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 @@ -22,34 +22,35 @@ class BlogPostEditState extends Equatable { } class BlogPostEditLoadedState extends BlogPostEditState { - BlogPostEditLoadedState( - {this.blog_postModelObj, - this.blog_post, - this.title, - this.description, - this.youtube_url,}); + BlogPostEditLoadedState({ + this.blog_postModelObj, + this.blog_post, + this.title, + this.description, + this.youtubeURL, + }); BlogPostEditModel? blog_postModelObj; Map? blog_post; TextEditingController? title; TextEditingController? description; - TextEditingController? youtube_url; + TextEditingController? youtubeURL; @override List get props => - [blog_postModelObj, blog_post, title, description, youtube_url]; + [blog_postModelObj, blog_post, title, description, youtubeURL]; BlogPostEditLoadedState copyWith({ BlogPostEditModel? blog_postModelObj, Map? blog_post, TextEditingController? title, TextEditingController? description, - TextEditingController? youtube_url, + TextEditingController? youtubeURL, }) { return BlogPostEditLoadedState( blog_postModelObj: blog_postModelObj ?? this.blog_postModelObj, blog_post: blog_post ?? this.blog_post, title: title ?? this.title, description: description ?? this.description, - youtube_url: youtube_url ?? this.youtube_url, + youtubeURL: youtubeURL ?? this.youtubeURL, ); } } 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 6af1c51..7012a55 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 @@ -10,9 +10,12 @@ class BlogPostEditScreen extends StatelessWidget { static Widget builder(BuildContext context, blog_postID) { return BlocProvider( - create: (context) => - BlogPostEditBloc(BlogPostEditState(blog_postModelObj: BlogPostEditModel(blog_postID: blog_postID.toString())))..add(BlogPostEditInitialEvent()), - child: BlogPostEditScreen(),); + create: (context) => BlogPostEditBloc(BlogPostEditState( + blog_postModelObj: + BlogPostEditModel(blog_postID: blog_postID.toString()))) + ..add(BlogPostEditInitialEvent()), + child: BlogPostEditScreen(), + ); } Widget build(BuildContext context) { @@ -74,7 +77,8 @@ class BlogPostEditScreen extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (state.blog_post?['image'] ?? ''), + imageUrl: dotenv.env['STORAGE_URL']! + + (state.blog_post?['image'] ?? ''), imageBuilder: (context, imageProvider) => CircleAvatar( backgroundImage: imageProvider, radius: 25, @@ -98,13 +102,14 @@ class BlogPostEditScreen extends StatelessWidget { ), SizedBox(height: 16.0), TextFormField( - controller: state.youtube_url, + controller: state.youtubeURL, decoration: InputDecoration(labelText: 'Ссылка'), ), SizedBox(height: 16.0), // Здесь нужно добавить виджет для загрузки картинки ElevatedButton( - onPressed: () => context.read().add(EditBlogPost()), + onPressed: () => + context.read().add(EditBlogPost()), child: Text('Сохранить'), ), ], -- 2.49.1 From 060fb512a0e60485f6b547425defb155b515869b Mon Sep 17 00:00:00 2001 From: alex Date: Fri, 28 Jun 2024 12:55:57 +0300 Subject: [PATCH 011/110] refactor(feed): refactor feed screen --- android/eatvio_app_android.iml | 2 +- lib/app_router.dart | 2 +- .../feed/models/feed_blog_post_model.dart | 20 + .../models/feed_blog_post_model.freezed.dart | 310 +++++++++ .../feed/models/feed_blog_post_model.g.dart | 33 + .../bloc/feed_cubit/feed_cubit.dart | 19 + .../bloc/feed_cubit/feed_state.dart | 19 + .../bloc/feed_cubit/feed_state.freezed.dart | 620 ++++++++++++++++++ .../feed/presentation/pages}/feed_screen.dart | 90 ++- .../feed/repositories/feed_repository.dart | 16 + lib/features/feed/services/feed_service.dart | 13 + .../feed/services/feed_service.g.dart | 80 +++ lib/locator_service.dart | 6 + lib/main.dart | 5 +- .../feed/feed_screen/bloc/feed_bloc.dart | 73 --- .../feed/feed_screen/bloc/feed_event.dart | 23 - .../feed/feed_screen/bloc/feed_state.dart | 49 -- 17 files changed, 1183 insertions(+), 197 deletions(-) create mode 100644 lib/features/feed/models/feed_blog_post_model.dart create mode 100644 lib/features/feed/models/feed_blog_post_model.freezed.dart create mode 100644 lib/features/feed/models/feed_blog_post_model.g.dart create mode 100644 lib/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart create mode 100644 lib/features/feed/presentation/bloc/feed_cubit/feed_state.dart create mode 100644 lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart rename lib/{presentation/feed/feed_screen => features/feed/presentation/pages}/feed_screen.dart (79%) create mode 100644 lib/features/feed/repositories/feed_repository.dart create mode 100644 lib/features/feed/services/feed_service.dart create mode 100644 lib/features/feed/services/feed_service.g.dart delete mode 100644 lib/presentation/feed/feed_screen/bloc/feed_bloc.dart delete mode 100644 lib/presentation/feed/feed_screen/bloc/feed_event.dart delete mode 100644 lib/presentation/feed/feed_screen/bloc/feed_state.dart diff --git a/android/eatvio_app_android.iml b/android/eatvio_app_android.iml index 1899969..3e44773 100644 --- a/android/eatvio_app_android.iml +++ b/android/eatvio_app_android.iml @@ -26,4 +26,4 @@ - + \ No newline at end of file diff --git a/lib/app_router.dart b/lib/app_router.dart index f0aafe9..c40516b 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -8,7 +8,7 @@ import 'package:eatvio_app/presentation/diets/diet_select_screen/diet_select_scr import 'package:eatvio_app/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart'; import 'package:eatvio_app/presentation/feed/blog_post_edit_screen/blog_post_edit_screen.dart'; import 'package:eatvio_app/presentation/feed/blog_post_screen/blog_post_screen.dart'; -import 'package:eatvio_app/presentation/feed/feed_screen/feed_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'; diff --git a/lib/features/feed/models/feed_blog_post_model.dart b/lib/features/feed/models/feed_blog_post_model.dart new file mode 100644 index 0000000..b77fb3f --- /dev/null +++ b/lib/features/feed/models/feed_blog_post_model.dart @@ -0,0 +1,20 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'feed_blog_post_model.freezed.dart'; +part 'feed_blog_post_model.g.dart'; + +@freezed +class FeedBlogPostModel with _$FeedBlogPostModel { + const factory FeedBlogPostModel({ + required int id, + required String state, + required String image, + required String description, + @JsonKey(name: "youtube_url") required String youtubeUrl, + @JsonKey(name: "created_at") required DateTime createdAt, + @JsonKey(name: "updated_at") required DateTime updatedAt, + required String title, + }) = _FeedBlogPostModel; + + factory FeedBlogPostModel.fromJson(Map json) => _$FeedBlogPostModelFromJson(json); +} diff --git a/lib/features/feed/models/feed_blog_post_model.freezed.dart b/lib/features/feed/models/feed_blog_post_model.freezed.dart new file mode 100644 index 0000000..4d753a1 --- /dev/null +++ b/lib/features/feed/models/feed_blog_post_model.freezed.dart @@ -0,0 +1,310 @@ +// 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_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'); + +FeedBlogPostModel _$FeedBlogPostModelFromJson(Map json) { + return _FeedBlogPostModel.fromJson(json); +} + +/// @nodoc +mixin _$FeedBlogPostModel { + int get id => throw _privateConstructorUsedError; + String get state => throw _privateConstructorUsedError; + String get image => throw _privateConstructorUsedError; + String get description => throw _privateConstructorUsedError; + @JsonKey(name: "youtube_url") + String get youtubeUrl => throw _privateConstructorUsedError; + @JsonKey(name: "created_at") + DateTime get createdAt => throw _privateConstructorUsedError; + @JsonKey(name: "updated_at") + DateTime get updatedAt => throw _privateConstructorUsedError; + String get title => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $FeedBlogPostModelCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $FeedBlogPostModelCopyWith<$Res> { + factory $FeedBlogPostModelCopyWith( + FeedBlogPostModel value, $Res Function(FeedBlogPostModel) then) = + _$FeedBlogPostModelCopyWithImpl<$Res, FeedBlogPostModel>; + @useResult + $Res call( + {int id, + String state, + String image, + String description, + @JsonKey(name: "youtube_url") String youtubeUrl, + @JsonKey(name: "created_at") DateTime createdAt, + @JsonKey(name: "updated_at") DateTime updatedAt, + String title}); +} + +/// @nodoc +class _$FeedBlogPostModelCopyWithImpl<$Res, $Val extends FeedBlogPostModel> + implements $FeedBlogPostModelCopyWith<$Res> { + _$FeedBlogPostModelCopyWithImpl(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 = null, + Object? state = null, + Object? image = null, + Object? description = null, + Object? youtubeUrl = null, + Object? createdAt = null, + Object? updatedAt = null, + Object? title = null, + }) { + return _then(_value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + state: null == state + ? _value.state + : state // ignore: cast_nullable_to_non_nullable + as String, + image: null == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as String, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + youtubeUrl: null == youtubeUrl + ? _value.youtubeUrl + : youtubeUrl // ignore: cast_nullable_to_non_nullable + as String, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + updatedAt: null == updatedAt + ? _value.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as DateTime, + title: null == title + ? _value.title + : title // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$FeedBlogPostModelImplCopyWith<$Res> + implements $FeedBlogPostModelCopyWith<$Res> { + factory _$$FeedBlogPostModelImplCopyWith(_$FeedBlogPostModelImpl value, + $Res Function(_$FeedBlogPostModelImpl) then) = + __$$FeedBlogPostModelImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {int id, + String state, + String image, + String description, + @JsonKey(name: "youtube_url") String youtubeUrl, + @JsonKey(name: "created_at") DateTime createdAt, + @JsonKey(name: "updated_at") DateTime updatedAt, + String title}); +} + +/// @nodoc +class __$$FeedBlogPostModelImplCopyWithImpl<$Res> + extends _$FeedBlogPostModelCopyWithImpl<$Res, _$FeedBlogPostModelImpl> + implements _$$FeedBlogPostModelImplCopyWith<$Res> { + __$$FeedBlogPostModelImplCopyWithImpl(_$FeedBlogPostModelImpl _value, + $Res Function(_$FeedBlogPostModelImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? state = null, + Object? image = null, + Object? description = null, + Object? youtubeUrl = null, + Object? createdAt = null, + Object? updatedAt = null, + Object? title = null, + }) { + return _then(_$FeedBlogPostModelImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + state: null == state + ? _value.state + : state // ignore: cast_nullable_to_non_nullable + as String, + image: null == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as String, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + youtubeUrl: null == youtubeUrl + ? _value.youtubeUrl + : youtubeUrl // ignore: cast_nullable_to_non_nullable + as String, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + updatedAt: null == updatedAt + ? _value.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as DateTime, + title: null == title + ? _value.title + : title // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$FeedBlogPostModelImpl implements _FeedBlogPostModel { + const _$FeedBlogPostModelImpl( + {required this.id, + required this.state, + required this.image, + required this.description, + @JsonKey(name: "youtube_url") required this.youtubeUrl, + @JsonKey(name: "created_at") required this.createdAt, + @JsonKey(name: "updated_at") required this.updatedAt, + required this.title}); + + factory _$FeedBlogPostModelImpl.fromJson(Map json) => + _$$FeedBlogPostModelImplFromJson(json); + + @override + final int id; + @override + final String state; + @override + final String image; + @override + final String description; + @override + @JsonKey(name: "youtube_url") + final String youtubeUrl; + @override + @JsonKey(name: "created_at") + final DateTime createdAt; + @override + @JsonKey(name: "updated_at") + final DateTime updatedAt; + @override + final String title; + + @override + String toString() { + return 'FeedBlogPostModel(id: $id, state: $state, image: $image, description: $description, youtubeUrl: $youtubeUrl, createdAt: $createdAt, updatedAt: $updatedAt, title: $title)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$FeedBlogPostModelImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.state, state) || other.state == state) && + (identical(other.image, image) || other.image == image) && + (identical(other.description, description) || + other.description == description) && + (identical(other.youtubeUrl, youtubeUrl) || + other.youtubeUrl == youtubeUrl) && + (identical(other.createdAt, createdAt) || + other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt) && + (identical(other.title, title) || other.title == title)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, id, state, image, description, + youtubeUrl, createdAt, updatedAt, title); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => + __$$FeedBlogPostModelImplCopyWithImpl<_$FeedBlogPostModelImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$FeedBlogPostModelImplToJson( + this, + ); + } +} + +abstract class _FeedBlogPostModel implements FeedBlogPostModel { + const factory _FeedBlogPostModel( + {required final int id, + required final String state, + required final String image, + required final String description, + @JsonKey(name: "youtube_url") required final String youtubeUrl, + @JsonKey(name: "created_at") required final DateTime createdAt, + @JsonKey(name: "updated_at") required final DateTime updatedAt, + required final String title}) = _$FeedBlogPostModelImpl; + + factory _FeedBlogPostModel.fromJson(Map json) = + _$FeedBlogPostModelImpl.fromJson; + + @override + int get id; + @override + String get state; + @override + String get image; + @override + String get description; + @override + @JsonKey(name: "youtube_url") + String get youtubeUrl; + @override + @JsonKey(name: "created_at") + DateTime get createdAt; + @override + @JsonKey(name: "updated_at") + DateTime get updatedAt; + @override + String get title; + @override + @JsonKey(ignore: true) + _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/feed/models/feed_blog_post_model.g.dart b/lib/features/feed/models/feed_blog_post_model.g.dart new file mode 100644 index 0000000..93cc70f --- /dev/null +++ b/lib/features/feed/models/feed_blog_post_model.g.dart @@ -0,0 +1,33 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'feed_blog_post_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$FeedBlogPostModelImpl _$$FeedBlogPostModelImplFromJson( + Map json) => + _$FeedBlogPostModelImpl( + id: (json['id'] as num).toInt(), + state: json['state'] as String, + image: json['image'] as String, + description: json['description'] as String, + youtubeUrl: json['youtube_url'] as String, + createdAt: DateTime.parse(json['created_at'] as String), + updatedAt: DateTime.parse(json['updated_at'] as String), + title: json['title'] as String, + ); + +Map _$$FeedBlogPostModelImplToJson( + _$FeedBlogPostModelImpl instance) => + { + 'id': instance.id, + 'state': instance.state, + 'image': instance.image, + 'description': instance.description, + 'youtube_url': instance.youtubeUrl, + 'created_at': instance.createdAt.toIso8601String(), + 'updated_at': instance.updatedAt.toIso8601String(), + 'title': instance.title, + }; diff --git a/lib/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart b/lib/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart new file mode 100644 index 0000000..6a52223 --- /dev/null +++ b/lib/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart @@ -0,0 +1,19 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_state.dart'; +import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; + +class FeedCubit extends Cubit { + final FeedRepository feedRepository; + + FeedCubit({required this.feedRepository}) : super(const FeedState.loading()); + + loadFeedBlogPostList() async { + emit(const FeedStateLoading()); + try { + final feedBlogPostList = await feedRepository.getFeedBlogPostList(); + emit(FeedState.loaded(feedBlogPostList: feedBlogPostList)); + } catch (e) { + emit(FeedState.error(errorMessage: e.toString())); + } + } +} diff --git a/lib/features/feed/presentation/bloc/feed_cubit/feed_state.dart b/lib/features/feed/presentation/bloc/feed_cubit/feed_state.dart new file mode 100644 index 0000000..70e8c3b --- /dev/null +++ b/lib/features/feed/presentation/bloc/feed_cubit/feed_state.dart @@ -0,0 +1,19 @@ +import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'feed_state.freezed.dart'; + +@freezed +abstract class FeedState with _$FeedState { + const factory FeedState() = _FeedState; + + const factory FeedState.loading() = FeedStateLoading; + + const factory FeedState.loaded({ + required List feedBlogPostList, + }) = FeedStateLoaded; + + const factory FeedState.error({ + required String errorMessage, + }) = FeedStateError; +} diff --git a/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart b/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart new file mode 100644 index 0000000..ab3385f --- /dev/null +++ b/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart @@ -0,0 +1,620 @@ +// 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_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 _$FeedState { + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(List feedBlogPostList) loaded, + required TResult Function(String errorMessage) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(List feedBlogPostList)? loaded, + TResult? Function(String errorMessage)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(List feedBlogPostList)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map( + TResult Function(_FeedState value) $default, { + required TResult Function(FeedStateLoading value) loading, + required TResult Function(FeedStateLoaded value) loaded, + required TResult Function(FeedStateError value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_FeedState value)? $default, { + TResult? Function(FeedStateLoading value)? loading, + TResult? Function(FeedStateLoaded value)? loaded, + TResult? Function(FeedStateError value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap( + TResult Function(_FeedState value)? $default, { + TResult Function(FeedStateLoading value)? loading, + TResult Function(FeedStateLoaded value)? loaded, + TResult Function(FeedStateError value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $FeedStateCopyWith<$Res> { + factory $FeedStateCopyWith(FeedState value, $Res Function(FeedState) then) = + _$FeedStateCopyWithImpl<$Res, FeedState>; +} + +/// @nodoc +class _$FeedStateCopyWithImpl<$Res, $Val extends FeedState> + implements $FeedStateCopyWith<$Res> { + _$FeedStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; +} + +/// @nodoc +abstract class _$$FeedStateImplCopyWith<$Res> { + factory _$$FeedStateImplCopyWith( + _$FeedStateImpl value, $Res Function(_$FeedStateImpl) then) = + __$$FeedStateImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$FeedStateImplCopyWithImpl<$Res> + extends _$FeedStateCopyWithImpl<$Res, _$FeedStateImpl> + implements _$$FeedStateImplCopyWith<$Res> { + __$$FeedStateImplCopyWithImpl( + _$FeedStateImpl _value, $Res Function(_$FeedStateImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$FeedStateImpl implements _FeedState { + const _$FeedStateImpl(); + + @override + String toString() { + return 'FeedState()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$FeedStateImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(List feedBlogPostList) loaded, + required TResult Function(String errorMessage) error, + }) { + return $default(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(List feedBlogPostList)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return $default?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(List feedBlogPostList)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_FeedState value) $default, { + required TResult Function(FeedStateLoading value) loading, + required TResult Function(FeedStateLoaded value) loaded, + required TResult Function(FeedStateError value) error, + }) { + return $default(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_FeedState value)? $default, { + TResult? Function(FeedStateLoading value)? loading, + TResult? Function(FeedStateLoaded value)? loaded, + TResult? Function(FeedStateError value)? error, + }) { + return $default?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_FeedState value)? $default, { + TResult Function(FeedStateLoading value)? loading, + TResult Function(FeedStateLoaded value)? loaded, + TResult Function(FeedStateError value)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(this); + } + return orElse(); + } +} + +abstract class _FeedState implements FeedState { + const factory _FeedState() = _$FeedStateImpl; +} + +/// @nodoc +abstract class _$$FeedStateLoadingImplCopyWith<$Res> { + factory _$$FeedStateLoadingImplCopyWith(_$FeedStateLoadingImpl value, + $Res Function(_$FeedStateLoadingImpl) then) = + __$$FeedStateLoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$FeedStateLoadingImplCopyWithImpl<$Res> + extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadingImpl> + implements _$$FeedStateLoadingImplCopyWith<$Res> { + __$$FeedStateLoadingImplCopyWithImpl(_$FeedStateLoadingImpl _value, + $Res Function(_$FeedStateLoadingImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$FeedStateLoadingImpl implements FeedStateLoading { + const _$FeedStateLoadingImpl(); + + @override + String toString() { + return 'FeedState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$FeedStateLoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(List feedBlogPostList) loaded, + required TResult Function(String errorMessage) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(List feedBlogPostList)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(List feedBlogPostList)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_FeedState value) $default, { + required TResult Function(FeedStateLoading value) loading, + required TResult Function(FeedStateLoaded value) loaded, + required TResult Function(FeedStateError value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_FeedState value)? $default, { + TResult? Function(FeedStateLoading value)? loading, + TResult? Function(FeedStateLoaded value)? loaded, + TResult? Function(FeedStateError value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_FeedState value)? $default, { + TResult Function(FeedStateLoading value)? loading, + TResult Function(FeedStateLoaded value)? loaded, + TResult Function(FeedStateError value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class FeedStateLoading implements FeedState { + const factory FeedStateLoading() = _$FeedStateLoadingImpl; +} + +/// @nodoc +abstract class _$$FeedStateLoadedImplCopyWith<$Res> { + factory _$$FeedStateLoadedImplCopyWith(_$FeedStateLoadedImpl value, + $Res Function(_$FeedStateLoadedImpl) then) = + __$$FeedStateLoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({List feedBlogPostList}); +} + +/// @nodoc +class __$$FeedStateLoadedImplCopyWithImpl<$Res> + extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadedImpl> + implements _$$FeedStateLoadedImplCopyWith<$Res> { + __$$FeedStateLoadedImplCopyWithImpl( + _$FeedStateLoadedImpl _value, $Res Function(_$FeedStateLoadedImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? feedBlogPostList = null, + }) { + return _then(_$FeedStateLoadedImpl( + feedBlogPostList: null == feedBlogPostList + ? _value._feedBlogPostList + : feedBlogPostList // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class _$FeedStateLoadedImpl implements FeedStateLoaded { + const _$FeedStateLoadedImpl( + {required final List feedBlogPostList}) + : _feedBlogPostList = feedBlogPostList; + + final List _feedBlogPostList; + @override + List get feedBlogPostList { + if (_feedBlogPostList is EqualUnmodifiableListView) + return _feedBlogPostList; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_feedBlogPostList); + } + + @override + String toString() { + return 'FeedState.loaded(feedBlogPostList: $feedBlogPostList)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$FeedStateLoadedImpl && + const DeepCollectionEquality() + .equals(other._feedBlogPostList, _feedBlogPostList)); + } + + @override + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_feedBlogPostList)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => + __$$FeedStateLoadedImplCopyWithImpl<_$FeedStateLoadedImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(List feedBlogPostList) loaded, + required TResult Function(String errorMessage) error, + }) { + return loaded(feedBlogPostList); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(List feedBlogPostList)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return loaded?.call(feedBlogPostList); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(List feedBlogPostList)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(feedBlogPostList); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_FeedState value) $default, { + required TResult Function(FeedStateLoading value) loading, + required TResult Function(FeedStateLoaded value) loaded, + required TResult Function(FeedStateError value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_FeedState value)? $default, { + TResult? Function(FeedStateLoading value)? loading, + TResult? Function(FeedStateLoaded value)? loaded, + TResult? Function(FeedStateError value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_FeedState value)? $default, { + TResult Function(FeedStateLoading value)? loading, + TResult Function(FeedStateLoaded value)? loaded, + TResult Function(FeedStateError value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class FeedStateLoaded implements FeedState { + const factory FeedStateLoaded( + {required final List feedBlogPostList}) = + _$FeedStateLoadedImpl; + + List get feedBlogPostList; + @JsonKey(ignore: true) + _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$FeedStateErrorImplCopyWith<$Res> { + factory _$$FeedStateErrorImplCopyWith(_$FeedStateErrorImpl value, + $Res Function(_$FeedStateErrorImpl) then) = + __$$FeedStateErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String errorMessage}); +} + +/// @nodoc +class __$$FeedStateErrorImplCopyWithImpl<$Res> + extends _$FeedStateCopyWithImpl<$Res, _$FeedStateErrorImpl> + implements _$$FeedStateErrorImplCopyWith<$Res> { + __$$FeedStateErrorImplCopyWithImpl( + _$FeedStateErrorImpl _value, $Res Function(_$FeedStateErrorImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? errorMessage = null, + }) { + return _then(_$FeedStateErrorImpl( + errorMessage: null == errorMessage + ? _value.errorMessage + : errorMessage // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$FeedStateErrorImpl implements FeedStateError { + const _$FeedStateErrorImpl({required this.errorMessage}); + + @override + final String errorMessage; + + @override + String toString() { + return 'FeedState.error(errorMessage: $errorMessage)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$FeedStateErrorImpl && + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); + } + + @override + int get hashCode => Object.hash(runtimeType, errorMessage); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => + __$$FeedStateErrorImplCopyWithImpl<_$FeedStateErrorImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(List feedBlogPostList) loaded, + required TResult Function(String errorMessage) error, + }) { + return error(errorMessage); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(List feedBlogPostList)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return error?.call(errorMessage); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(List feedBlogPostList)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(errorMessage); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_FeedState value) $default, { + required TResult Function(FeedStateLoading value) loading, + required TResult Function(FeedStateLoaded value) loaded, + required TResult Function(FeedStateError value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_FeedState value)? $default, { + TResult? Function(FeedStateLoading value)? loading, + TResult? Function(FeedStateLoaded value)? loaded, + TResult? Function(FeedStateError value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_FeedState value)? $default, { + TResult Function(FeedStateLoading value)? loading, + TResult Function(FeedStateLoaded value)? loaded, + TResult Function(FeedStateError value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class FeedStateError implements FeedState { + const factory FeedStateError({required final String errorMessage}) = + _$FeedStateErrorImpl; + + String get errorMessage; + @JsonKey(ignore: true) + _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/feed/feed_screen/feed_screen.dart b/lib/features/feed/presentation/pages/feed_screen.dart similarity index 79% rename from lib/presentation/feed/feed_screen/feed_screen.dart rename to lib/features/feed/presentation/pages/feed_screen.dart index f6cf07a..dca0eef 100644 --- a/lib/presentation/feed/feed_screen/feed_screen.dart +++ b/lib/features/feed/presentation/pages/feed_screen.dart @@ -1,7 +1,8 @@ +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 'bloc/feed_bloc.dart'; -import 'models/feed_model.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'; @@ -12,37 +13,30 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; class FeedScreen extends StatelessWidget { - static Widget builder(BuildContext context) { - return BlocProvider( - create: (context) => FeedBloc(FeedState(myProfileModelObj: FeedModel())) - ..add(FeedInitialEvent()), - child: FeedScreen()); - } - Widget build(BuildContext context) { - return BlocBuilder( - builder: (context, state) { - if (state is FeedInitialState) { - // Это начальное состояние, данные ещё не загружены. - return CircularProgressIndicator( - color: Colors.white, - backgroundColor: Colors.white, - ); - } else if (state is FeedLoadedState) { - // Данные загружены, можно строить экран. + return BlocBuilder( + builder: (BuildContext context, FeedState state) { + if (state is FeedStateLoaded) { return _buildFeedScreen(context, state); } else { - // Другие состояния, если они есть. - return Container(); // Пустой контейнер для необработанных состояний. + return Scaffold( + body: Center( + child: CupertinoActivityIndicator(), + ), + ); } }, ); } - _buildFeedScreen(BuildContext context, FeedLoadedState state) { + _buildFeedScreen(BuildContext context, FeedStateLoaded state) { mediaQueryData = MediaQuery.of(context); - return SafeArea( + return RefreshIndicator( + onRefresh: () => context.read().loadFeedBlogPostList(), child: Scaffold( + appBar: AppBar( + toolbarHeight: 0, + ), backgroundColor: Colors.grey[200], resizeToAvoidBottomInset: true, body: SingleChildScrollView( @@ -106,8 +100,7 @@ class FeedScreen extends StatelessWidget { flex: 1, child: CustomOutlinedButton( text: "+", - onPressed: () => - GoRouter.of(context).goNamed('blogPostCreateScreen'), + onPressed: () => GoRouter.of(context).goNamed('blogPostCreateScreen'), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, ), ), @@ -119,13 +112,11 @@ class FeedScreen extends StatelessWidget { ); } - _buildBlogPostList(BuildContext context, FeedLoadedState state) { + _buildBlogPostList(BuildContext context, FeedStateLoaded state) { List postWidgets = []; - if (state.posts != null) { - for (var post in state.posts!) { - postWidgets.add(_buildFeedEntry(post, context)); - } + for (var post in state.feedBlogPostList) { + postWidgets.add(_buildFeedEntry(post, context)); } return Column( @@ -134,7 +125,7 @@ class FeedScreen extends StatelessWidget { ); } - _buildFeedEntry(post, BuildContext context) { + _buildFeedEntry(FeedBlogPostModel post, BuildContext context) { return Container( margin: EdgeInsets.only(bottom: 10), decoration: BoxDecoration( @@ -153,31 +144,37 @@ class FeedScreen extends StatelessWidget { children: [ ListTile( leading: CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + - (post['profile_photo_path'] ?? ''), + imageUrl: dotenv.env['STORAGE_URL']! + ('' ?? ''), + + /// todo profile photo path imageBuilder: (context, imageProvider) => CircleAvatar( backgroundImage: imageProvider, - radius: 25, + radius: 24, + ), + placeholder: (context, url) => CircleAvatar( + child: Icon(Icons.person), + backgroundColor: Colors.white, + radius: 24, ), - placeholder: (context, url) => CircularProgressIndicator(), errorWidget: (context, url, error) => CircleAvatar( child: Icon(Icons.person), backgroundColor: Colors.white, - radius: 25, + radius: 24, ), ), title: Text( - post?['author_name'] ?? 'Authorae', + 'Authorae', + + /// todo author name style: CustomTextStyles.titleMediumSemiBold, ), subtitle: Text( - DateFormat('dd.MM.yyyy') - .format(DateTime.parse(post?['updated_at'])), + DateFormat('dd.MM.yyyy').format(post.updatedAt), style: theme.textTheme.bodyMedium, ), onTap: () => GoRouter.of(context).goNamed( 'blogPostScreen', - extra: post?['id'].toString(), + extra: post.id.toString(), ), trailing: PopupMenuButton( onSelected: (value) => print("tap"), @@ -204,7 +201,7 @@ class FeedScreen extends StatelessWidget { Align( alignment: Alignment.center, child: Text( - post?['title'], + post.title, style: CustomTextStyles.titleMediumBlack, ), ), @@ -213,17 +210,16 @@ class FeedScreen extends StatelessWidget { ), SizedBox(height: 8.0), Text( - post?['description'], + post.description, style: CustomTextStyles.bodyMediumBluegray800, ), SizedBox(height: 16.0), CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (post?['image'] ?? ''), + imageUrl: dotenv.env['STORAGE_URL']! + (post.image ?? ''), imageBuilder: (context, imageProvider) => Stack( children: [ ClipRRect( - borderRadius: - const BorderRadius.all(Radius.circular(8.0)), + borderRadius: const BorderRadius.all(Radius.circular(8.0)), child: Image( image: imageProvider, ), @@ -286,7 +282,7 @@ class FeedScreen extends StatelessWidget { GoRouter.of(context).pop(); } - _buildMenu(BuildContext context, FeedLoadedState state) { + _buildMenu(BuildContext context, FeedStateLoaded state) { return Container( padding: EdgeInsets.all(12), margin: EdgeInsets.only(bottom: 10), diff --git a/lib/features/feed/repositories/feed_repository.dart b/lib/features/feed/repositories/feed_repository.dart new file mode 100644 index 0000000..fb87104 --- /dev/null +++ b/lib/features/feed/repositories/feed_repository.dart @@ -0,0 +1,16 @@ +import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; +import 'package:eatvio_app/features/feed/services/feed_service.dart'; + +class FeedRepository { + final FeedService feedService; + + FeedRepository({required this.feedService}); + + Future> getFeedBlogPostList() async { + try { + return await feedService.getBlocPostList(); + } catch (e) { + rethrow; + } + } +} diff --git a/lib/features/feed/services/feed_service.dart b/lib/features/feed/services/feed_service.dart new file mode 100644 index 0000000..80deb91 --- /dev/null +++ b/lib/features/feed/services/feed_service.dart @@ -0,0 +1,13 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; +import 'package:retrofit/retrofit.dart'; + +part 'feed_service.g.dart'; + +@RestApi() +abstract class FeedService { + factory FeedService(Dio dio, {String baseUrl}) = _FeedService; + + @GET('/feed/index') + Future> getBlocPostList(); +} diff --git a/lib/features/feed/services/feed_service.g.dart b/lib/features/feed/services/feed_service.g.dart new file mode 100644 index 0000000..6184cfb --- /dev/null +++ b/lib/features/feed/services/feed_service.g.dart @@ -0,0 +1,80 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'feed_service.dart'; + +// ************************************************************************** +// RetrofitGenerator +// ************************************************************************** + +// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers + +class _FeedService implements FeedService { + _FeedService( + this._dio, { + this.baseUrl, + }); + + final Dio _dio; + + String? baseUrl; + + @override + Future> getBlocPostList() async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio + .fetch>(_setStreamType>(Options( + method: 'GET', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/feed/index', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + var value = _result.data! + .map((dynamic i) => + FeedBlogPostModel.fromJson(i as Map)) + .toList(); + 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/locator_service.dart b/lib/locator_service.dart index 8759775..9780f41 100644 --- a/lib/locator_service.dart +++ b/lib/locator_service.dart @@ -3,6 +3,9 @@ import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; 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:get_it/get_it.dart'; @@ -12,12 +15,15 @@ Future init() async { // BLoC sl.registerFactory(() => ChatRoomCubit(chatRepository: sl())); sl.registerFactory(() => InitializationCubit(chatRepository: sl())); + sl.registerFactory(() => FeedCubit(feedRepository: sl())); // Repository sl.registerLazySingleton(() => ChatRepository(chatService: sl())); + sl.registerLazySingleton(() => FeedRepository(feedService: sl())); // Services sl.registerLazySingleton(() => ChatService(sl())); + sl.registerLazySingleton(() => FeedService(sl())); // External sl.registerLazySingleton( diff --git a/lib/main.dart b/lib/main.dart index 2919130..2f81b9f 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -3,11 +3,10 @@ import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_state.dart'; 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'; 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'; -import 'package:eatvio_app/presentation/feed/feed_screen/bloc/feed_bloc.dart'; -import 'package:eatvio_app/presentation/feed/feed_screen/models/feed_model.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'; import 'package:flutter/material.dart'; @@ -45,8 +44,8 @@ class MyApp extends StatelessWidget { providers: [ BlocProvider(create: (context) => InitializationCubit(chatRepository: sl())..runInitialization()), BlocProvider(create: (context) => ThemeBloc(ThemeState(themeType: PrefUtils().getThemeData()))), + BlocProvider(create: (context) => sl()..loadFeedBlogPostList()), BlocProvider(create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent())), - BlocProvider(create: (context) => FeedBloc(FeedState(myProfileModelObj: FeedModel()))..add(FeedInitialEvent())), BlocProvider(create: (context) => DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel()))..add(DiaryEditInitialEvent())), BlocProvider( create: (context) => ChatSelectBloc(ChatSelectState(chatSelectModelObj: ChatSelectModel()))..add(ChatSelectInitialEvent()), diff --git a/lib/presentation/feed/feed_screen/bloc/feed_bloc.dart b/lib/presentation/feed/feed_screen/bloc/feed_bloc.dart deleted file mode 100644 index 1eda1fe..0000000 --- a/lib/presentation/feed/feed_screen/bloc/feed_bloc.dart +++ /dev/null @@ -1,73 +0,0 @@ -//import 'package:eatvio_app/presentation/auth/auth_screen/auth_screen.dart'; -import 'dart:async'; - -import 'package:eatvio_app/app_router.dart'; -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import '/core/app_export.dart'; -import 'package:eatvio_app/presentation/feed/feed_screen/models/feed_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'; - -part 'feed_event.dart'; -part 'feed_state.dart'; - -/// A bloc that manages the state of a Feed according to the event that is dispatched to it. -class FeedBloc extends Bloc { - FeedBloc(FeedState initialState) : super(initialState) { - on(_onInitialize); - } - - Future _onInitialize( - FeedInitialEvent event, - Emitter emit, - ) async { - try { - final box = await Hive.openBox('token'); - final token = box.get('token'); - if (token == null) { - AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); - } - final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/feed/index'), - headers: { - 'Authorization': 'Bearer $token', - }, - ); - print('Got response'); - if (response.statusCode == 200) { - print('Got 200'); - final data = jsonDecode(response.body); - if (data is List) { - print('Got List'); - if (state is FeedLoadedState) { - print('Got loaded'); - var currentState = state as FeedLoadedState; - emit((currentState).copyWith( - posts: data, - myProfileModelObj: currentState.myProfileModelObj, - )); - } else { - print('Got unloaded'); - emit(FeedLoadedState( - posts: data, - )); - } - } else { - // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку - emit(FeedErrorState('Неверный формат ответа API.')); - } - } else { - // Статус ответа не равен 200, обрабатываем ошибку - emit(FeedErrorState('Ошибка сервера: ${response.statusCode}')); - } - } catch (e) { - // Ошибка при декодировании JSON или другая ошибка выполнения - emit(FeedErrorState('Ошибка при получении данных ленты: $e')); - } - } -} diff --git a/lib/presentation/feed/feed_screen/bloc/feed_event.dart b/lib/presentation/feed/feed_screen/bloc/feed_event.dart deleted file mode 100644 index cbb510f..0000000 --- a/lib/presentation/feed/feed_screen/bloc/feed_event.dart +++ /dev/null @@ -1,23 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'feed_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///Feed widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class FeedEvent extends Equatable {} - -/// Event that is dispatched when the Feed widget is first created. -class FeedInitialEvent extends FeedEvent { - @override - List get props => []; -} - -class UploadAvatar extends FeedEvent { - UploadAvatar(this.image); - final XFile image; - @override - List get props => [image]; -} diff --git a/lib/presentation/feed/feed_screen/bloc/feed_state.dart b/lib/presentation/feed/feed_screen/bloc/feed_state.dart deleted file mode 100644 index dbc57ac..0000000 --- a/lib/presentation/feed/feed_screen/bloc/feed_state.dart +++ /dev/null @@ -1,49 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'feed_bloc.dart'; - -class FeedState extends Equatable { - const FeedState({this.myProfileModelObj}); - - final FeedModel? myProfileModelObj; - - @override - List get props => [myProfileModelObj]; -} - -class FeedInitialState extends FeedState { - FeedInitialState({required FeedModel myProfileModelObj}) - : super(myProfileModelObj: myProfileModelObj); -} - -/// Represents the state of Feed in the application. -class FeedLoadedState extends FeedState { - FeedLoadedState({this.myProfileModelObj, this.posts}) - : super(myProfileModelObj: null); - - FeedModel? myProfileModelObj; - List? posts; - @override - List get props => [ - myProfileModelObj, - posts, - ]; - FeedLoadedState copyWith({ - FeedModel? myProfileModelObj, - List? posts, - }) { - return FeedLoadedState( - myProfileModelObj: myProfileModelObj ?? this.myProfileModelObj, - posts: posts ?? this.posts, - ); - } -} - -class FeedErrorState extends FeedState { - final String errorMessage; - - const FeedErrorState(this.errorMessage); - - @override - List get props => [errorMessage]; -} -- 2.49.1 From 31514132097904f6ec3a38ef5798a266dd91aa6f Mon Sep 17 00:00:00 2001 From: alex Date: Fri, 28 Jun 2024 13:17:20 +0300 Subject: [PATCH 012/110] refactor(feed): fix analyze --- lib/features/feed/presentation/pages/feed_screen.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/features/feed/presentation/pages/feed_screen.dart b/lib/features/feed/presentation/pages/feed_screen.dart index dca0eef..b3ed4ec 100644 --- a/lib/features/feed/presentation/pages/feed_screen.dart +++ b/lib/features/feed/presentation/pages/feed_screen.dart @@ -144,7 +144,7 @@ class FeedScreen extends StatelessWidget { children: [ ListTile( leading: CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + ('' ?? ''), + imageUrl: dotenv.env['STORAGE_URL']! + (''), /// todo profile photo path imageBuilder: (context, imageProvider) => CircleAvatar( @@ -215,7 +215,7 @@ class FeedScreen extends StatelessWidget { ), SizedBox(height: 16.0), CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (post.image ?? ''), + imageUrl: dotenv.env['STORAGE_URL']! + (post.image), imageBuilder: (context, imageProvider) => Stack( children: [ ClipRRect( -- 2.49.1 From 02f4008394489ce2c85ee6e3b6c269b0a30b6cd7 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 28 Jun 2024 14:41:30 +0300 Subject: [PATCH 013/110] refactor(blog_post): Dio, retrfit and freezed implemented for blog post show screen --- lib/app_router.dart | 106 ++- .../blog_post/models/blog_post_model.dart | 23 + .../models/blog_post_model.freezed.dart | 351 ++++++++++ .../blog_post/models/blog_post_model.g.dart | 35 + .../presentation/bloc/blog_post_cubit.dart | 21 + .../presentation/bloc/blog_post_state.dart | 19 + .../bloc/blog_post_state.freezed.dart | 622 ++++++++++++++++++ .../presentation/pages}/blog_post_screen.dart | 255 ++++--- .../repositories/blog_post_repository.dart | 16 + .../blog_post/services/blog_post_service.dart | 13 + .../services/blog_post_service.g.dart | 77 +++ .../bloc/feed_cubit/feed_cubit.dart | 2 +- .../feed/presentation/pages/feed_screen.dart | 10 +- lib/locator_service.dart | 17 +- .../blog_post_screen/bloc/blog_post_bloc.dart | 184 ------ .../bloc/blog_post_event.dart | 44 -- .../bloc/blog_post_state.dart | 70 -- 17 files changed, 1397 insertions(+), 468 deletions(-) create mode 100644 lib/features/blog_post/models/blog_post_model.dart create mode 100644 lib/features/blog_post/models/blog_post_model.freezed.dart create mode 100644 lib/features/blog_post/models/blog_post_model.g.dart create mode 100644 lib/features/blog_post/presentation/bloc/blog_post_cubit.dart create mode 100644 lib/features/blog_post/presentation/bloc/blog_post_state.dart create mode 100644 lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart rename lib/{presentation/feed/blog_post_screen => features/blog_post/presentation/pages}/blog_post_screen.dart (62%) create mode 100644 lib/features/blog_post/repositories/blog_post_repository.dart create mode 100644 lib/features/blog_post/services/blog_post_service.dart create mode 100644 lib/features/blog_post/services/blog_post_service.g.dart delete mode 100644 lib/presentation/feed/blog_post_screen/bloc/blog_post_bloc.dart delete mode 100644 lib/presentation/feed/blog_post_screen/bloc/blog_post_event.dart delete mode 100644 lib/presentation/feed/blog_post_screen/bloc/blog_post_state.dart diff --git a/lib/app_router.dart b/lib/app_router.dart index c40516b..0b8c097 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -7,7 +7,7 @@ import 'package:eatvio_app/presentation/diets/diet_create_screen/diet_create_scr import 'package:eatvio_app/presentation/diets/diet_select_screen/diet_select_screen.dart'; import 'package:eatvio_app/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart'; import 'package:eatvio_app/presentation/feed/blog_post_edit_screen/blog_post_edit_screen.dart'; -import 'package:eatvio_app/presentation/feed/blog_post_screen/blog_post_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'; @@ -45,7 +45,8 @@ class AppRouter { path: '/auth-screen', name: 'authScreen', redirect: (context, state) async { - if (await TokenStorage.haveTokenInStorage()) return '/my-profile-screen'; + if (await TokenStorage.haveTokenInStorage()) + return '/my-profile-screen'; return null; }, builder: (context, state) => AuthScreen.builder(context), @@ -58,72 +59,120 @@ class AppRouter { GoRoute( path: 'credentials-screen', name: 'credentialsScreen', - builder: (context, state) => CredentialsScreen.builder(context, state.extra), + builder: (context, state) => + CredentialsScreen.builder(context, state.extra), routes: [ GoRoute( path: 'name-screen', name: 'nameScreen', - builder: (context, state) => NameScreen.builder(context, state.extra), + builder: (context, state) => + NameScreen.builder(context, state.extra), routes: [ GoRoute( path: 'gender-screen', name: 'genderScreen', - builder: (context, state) => GenderScreen.builder(context, state.extra), + 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), + 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), + builder: (context, state) => + CityOfLivingScreen.builder( + context, state.extra), routes: [ GoRoute( path: 'body-circumferences-screen', name: 'bodyCircumferencesScreen', - builder: (context, state) => BodyCircumferencesScreen.builder(context, state.extra), + builder: (context, state) => + BodyCircumferencesScreen.builder( + context, state.extra), routes: [ GoRoute( path: 'weight-screen', name: 'weightScreen', - builder: (context, state) => WeightScreen.builder(context, state.extra), + builder: (context, state) => + WeightScreen.builder( + context, state.extra), routes: [ GoRoute( path: 'height-screen', name: 'heightScreen', - builder: (context, state) => HeightScreen.builder(context, state.extra), + builder: (context, state) => + HeightScreen.builder( + context, state.extra), routes: [ GoRoute( path: 'blood-pressure-screen', name: 'bloodPressureScreen', - builder: (context, state) => BloodPressureScreen.builder(context, state.extra), + builder: (context, state) => + BloodPressureScreen.builder( + context, state.extra), routes: [ GoRoute( - path: 'favorite-sports-screen', - name: 'favoriteSportsScreen', - builder: (context, state) => FavoriteSportsScreen.builder(context, state.extra), + 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), + builder: (context, + state) => + AllergiesScreen + .builder( + context, + state + .extra), routes: [ GoRoute( - name: 'medicineIntakeScreen', - path: 'medicine-intake-screen', - builder: (context, state) => MedicineIntakeScreen.builder(context, state.extra), + 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), + 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: + 'additional-information-screen', + name: + 'additionalInformationScreen', + builder: (context, + state) => + AdditionalInformationScreen.builder( + context, + state + .extra), ), ], ), @@ -171,15 +220,14 @@ class AppRouter { GoRoute( path: 'blog-post-create-screen', name: 'blogPostCreateScreen', - builder: (context, state) => BlogPostCreateScreen.builder(context), + builder: (context, state) => + BlogPostCreateScreen.builder(context), ), GoRoute( path: 'blog-post-screen', name: 'blogPostScreen', - builder: (context, state) => BlogPostScreen.builder( - context, - state.extra.toString(), - ), + builder: (context, state) => + BlogPostScreen(blogPostID: state.extra as String), routes: [ GoRoute( path: 'blog-post-edit-screen', diff --git a/lib/features/blog_post/models/blog_post_model.dart b/lib/features/blog_post/models/blog_post_model.dart new file mode 100644 index 0000000..df39fe1 --- /dev/null +++ b/lib/features/blog_post/models/blog_post_model.dart @@ -0,0 +1,23 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'blog_post_model.freezed.dart'; +part 'blog_post_model.g.dart'; + +@freezed +class BlogPostModel with _$BlogPostModel { + const factory BlogPostModel({ + required int id, + required String state, + String? image, + required String description, + String? author_name, + String? author_avatar_path, + @JsonKey(name: "youtube_url") required String youtubeUrl, + @JsonKey(name: "created_at") required DateTime createdAt, + @JsonKey(name: "updated_at") required DateTime updatedAt, + required String title, + }) = _BlogPostModel; + + factory BlogPostModel.fromJson(Map json) => + _$BlogPostModelFromJson(json); +} diff --git a/lib/features/blog_post/models/blog_post_model.freezed.dart b/lib/features/blog_post/models/blog_post_model.freezed.dart new file mode 100644 index 0000000..7c0a750 --- /dev/null +++ b/lib/features/blog_post/models/blog_post_model.freezed.dart @@ -0,0 +1,351 @@ +// 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 'blog_post_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'); + +BlogPostModel _$BlogPostModelFromJson(Map json) { + return _BlogPostModel.fromJson(json); +} + +/// @nodoc +mixin _$BlogPostModel { + int get id => throw _privateConstructorUsedError; + String get state => throw _privateConstructorUsedError; + String? get image => throw _privateConstructorUsedError; + String get description => throw _privateConstructorUsedError; + String? get author_name => throw _privateConstructorUsedError; + String? get author_avatar_path => throw _privateConstructorUsedError; + @JsonKey(name: "youtube_url") + String get youtubeUrl => throw _privateConstructorUsedError; + @JsonKey(name: "created_at") + DateTime get createdAt => throw _privateConstructorUsedError; + @JsonKey(name: "updated_at") + DateTime get updatedAt => throw _privateConstructorUsedError; + String get title => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $BlogPostModelCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $BlogPostModelCopyWith<$Res> { + factory $BlogPostModelCopyWith( + BlogPostModel value, $Res Function(BlogPostModel) then) = + _$BlogPostModelCopyWithImpl<$Res, BlogPostModel>; + @useResult + $Res call( + {int id, + String state, + String? image, + String description, + String? author_name, + String? author_avatar_path, + @JsonKey(name: "youtube_url") String youtubeUrl, + @JsonKey(name: "created_at") DateTime createdAt, + @JsonKey(name: "updated_at") DateTime updatedAt, + String title}); +} + +/// @nodoc +class _$BlogPostModelCopyWithImpl<$Res, $Val extends BlogPostModel> + implements $BlogPostModelCopyWith<$Res> { + _$BlogPostModelCopyWithImpl(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 = null, + Object? state = null, + Object? image = freezed, + Object? description = null, + Object? author_name = freezed, + Object? author_avatar_path = freezed, + Object? youtubeUrl = null, + Object? createdAt = null, + Object? updatedAt = null, + Object? title = null, + }) { + return _then(_value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + state: null == state + ? _value.state + : state // ignore: cast_nullable_to_non_nullable + as String, + image: freezed == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as String?, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + author_name: freezed == author_name + ? _value.author_name + : author_name // ignore: cast_nullable_to_non_nullable + as String?, + author_avatar_path: freezed == author_avatar_path + ? _value.author_avatar_path + : author_avatar_path // ignore: cast_nullable_to_non_nullable + as String?, + youtubeUrl: null == youtubeUrl + ? _value.youtubeUrl + : youtubeUrl // ignore: cast_nullable_to_non_nullable + as String, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + updatedAt: null == updatedAt + ? _value.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as DateTime, + title: null == title + ? _value.title + : title // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$BlogPostModelImplCopyWith<$Res> + implements $BlogPostModelCopyWith<$Res> { + factory _$$BlogPostModelImplCopyWith( + _$BlogPostModelImpl value, $Res Function(_$BlogPostModelImpl) then) = + __$$BlogPostModelImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {int id, + String state, + String? image, + String description, + String? author_name, + String? author_avatar_path, + @JsonKey(name: "youtube_url") String youtubeUrl, + @JsonKey(name: "created_at") DateTime createdAt, + @JsonKey(name: "updated_at") DateTime updatedAt, + String title}); +} + +/// @nodoc +class __$$BlogPostModelImplCopyWithImpl<$Res> + extends _$BlogPostModelCopyWithImpl<$Res, _$BlogPostModelImpl> + implements _$$BlogPostModelImplCopyWith<$Res> { + __$$BlogPostModelImplCopyWithImpl( + _$BlogPostModelImpl _value, $Res Function(_$BlogPostModelImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? state = null, + Object? image = freezed, + Object? description = null, + Object? author_name = freezed, + Object? author_avatar_path = freezed, + Object? youtubeUrl = null, + Object? createdAt = null, + Object? updatedAt = null, + Object? title = null, + }) { + return _then(_$BlogPostModelImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + state: null == state + ? _value.state + : state // ignore: cast_nullable_to_non_nullable + as String, + image: freezed == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as String?, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + author_name: freezed == author_name + ? _value.author_name + : author_name // ignore: cast_nullable_to_non_nullable + as String?, + author_avatar_path: freezed == author_avatar_path + ? _value.author_avatar_path + : author_avatar_path // ignore: cast_nullable_to_non_nullable + as String?, + youtubeUrl: null == youtubeUrl + ? _value.youtubeUrl + : youtubeUrl // ignore: cast_nullable_to_non_nullable + as String, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + updatedAt: null == updatedAt + ? _value.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as DateTime, + title: null == title + ? _value.title + : title // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$BlogPostModelImpl implements _BlogPostModel { + const _$BlogPostModelImpl( + {required this.id, + required this.state, + this.image, + required this.description, + this.author_name, + this.author_avatar_path, + @JsonKey(name: "youtube_url") required this.youtubeUrl, + @JsonKey(name: "created_at") required this.createdAt, + @JsonKey(name: "updated_at") required this.updatedAt, + required this.title}); + + factory _$BlogPostModelImpl.fromJson(Map json) => + _$$BlogPostModelImplFromJson(json); + + @override + final int id; + @override + final String state; + @override + final String? image; + @override + final String description; + @override + final String? author_name; + @override + final String? author_avatar_path; + @override + @JsonKey(name: "youtube_url") + final String youtubeUrl; + @override + @JsonKey(name: "created_at") + final DateTime createdAt; + @override + @JsonKey(name: "updated_at") + final DateTime updatedAt; + @override + final String title; + + @override + String toString() { + return 'BlogPostModel(id: $id, state: $state, image: $image, description: $description, author_name: $author_name, author_avatar_path: $author_avatar_path, youtubeUrl: $youtubeUrl, createdAt: $createdAt, updatedAt: $updatedAt, title: $title)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$BlogPostModelImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.state, state) || other.state == state) && + (identical(other.image, image) || other.image == image) && + (identical(other.description, description) || + other.description == description) && + (identical(other.author_name, author_name) || + other.author_name == author_name) && + (identical(other.author_avatar_path, author_avatar_path) || + other.author_avatar_path == author_avatar_path) && + (identical(other.youtubeUrl, youtubeUrl) || + other.youtubeUrl == youtubeUrl) && + (identical(other.createdAt, createdAt) || + other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt) && + (identical(other.title, title) || other.title == title)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, id, state, image, description, + author_name, author_avatar_path, youtubeUrl, createdAt, updatedAt, title); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => + __$$BlogPostModelImplCopyWithImpl<_$BlogPostModelImpl>(this, _$identity); + + @override + Map toJson() { + return _$$BlogPostModelImplToJson( + this, + ); + } +} + +abstract class _BlogPostModel implements BlogPostModel { + const factory _BlogPostModel( + {required final int id, + required final String state, + final String? image, + required final String description, + final String? author_name, + final String? author_avatar_path, + @JsonKey(name: "youtube_url") required final String youtubeUrl, + @JsonKey(name: "created_at") required final DateTime createdAt, + @JsonKey(name: "updated_at") required final DateTime updatedAt, + required final String title}) = _$BlogPostModelImpl; + + factory _BlogPostModel.fromJson(Map json) = + _$BlogPostModelImpl.fromJson; + + @override + int get id; + @override + String get state; + @override + String? get image; + @override + String get description; + @override + String? get author_name; + @override + String? get author_avatar_path; + @override + @JsonKey(name: "youtube_url") + String get youtubeUrl; + @override + @JsonKey(name: "created_at") + DateTime get createdAt; + @override + @JsonKey(name: "updated_at") + DateTime get updatedAt; + @override + String get title; + @override + @JsonKey(ignore: true) + _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/blog_post/models/blog_post_model.g.dart b/lib/features/blog_post/models/blog_post_model.g.dart new file mode 100644 index 0000000..2e3233c --- /dev/null +++ b/lib/features/blog_post/models/blog_post_model.g.dart @@ -0,0 +1,35 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'blog_post_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$BlogPostModelImpl _$$BlogPostModelImplFromJson(Map json) => + _$BlogPostModelImpl( + id: (json['id'] as num).toInt(), + state: json['state'] as String, + image: json['image'] as String?, + description: json['description'] as String, + author_name: json['author_name'] as String?, + author_avatar_path: json['author_avatar_path'] as String?, + youtubeUrl: json['youtube_url'] as String, + createdAt: DateTime.parse(json['created_at'] as String), + updatedAt: DateTime.parse(json['updated_at'] as String), + title: json['title'] as String, + ); + +Map _$$BlogPostModelImplToJson(_$BlogPostModelImpl instance) => + { + 'id': instance.id, + 'state': instance.state, + 'image': instance.image, + 'description': instance.description, + 'author_name': instance.author_name, + 'author_avatar_path': instance.author_avatar_path, + 'youtube_url': instance.youtubeUrl, + 'created_at': instance.createdAt.toIso8601String(), + 'updated_at': instance.updatedAt.toIso8601String(), + 'title': instance.title, + }; diff --git a/lib/features/blog_post/presentation/bloc/blog_post_cubit.dart b/lib/features/blog_post/presentation/bloc/blog_post_cubit.dart new file mode 100644 index 0000000..90520c9 --- /dev/null +++ b/lib/features/blog_post/presentation/bloc/blog_post_cubit.dart @@ -0,0 +1,21 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/features/blog_post/presentation/bloc/blog_post_state.dart'; +import 'package:eatvio_app/features/blog_post/repositories/blog_post_repository.dart'; + +class BlogPostCubit extends Cubit { + final BlogPostRepository blogPostRepository; + + BlogPostCubit({required this.blogPostRepository}) + : super(const BlogPostState.loading()); + + loadBlogPost(String blogPostID) async { + emit(const BlogPostState.loading()); + try { + final blogPost = await blogPostRepository.getBlogPost(blogPostID); + emit(BlogPostState.loaded(blogPost: blogPost)); + } catch (e) { + emit(BlogPostState.error(errorMessage: e.toString())); + print(e); + } + } +} diff --git a/lib/features/blog_post/presentation/bloc/blog_post_state.dart b/lib/features/blog_post/presentation/bloc/blog_post_state.dart new file mode 100644 index 0000000..c8a4d0e --- /dev/null +++ b/lib/features/blog_post/presentation/bloc/blog_post_state.dart @@ -0,0 +1,19 @@ +import 'package:eatvio_app/features/blog_post/models/blog_post_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'blog_post_state.freezed.dart'; + +@freezed +abstract class BlogPostState with _$BlogPostState { + const factory BlogPostState() = _BlogPostState; + + const factory BlogPostState.loading() = BlogPostStateLoading; + + const factory BlogPostState.loaded({ + required BlogPostModel blogPost, + }) = BlogPostStateLoaded; + + const factory BlogPostState.error({ + required String errorMessage, + }) = BlogPostStateError; +} diff --git a/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart b/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart new file mode 100644 index 0000000..4f99a3c --- /dev/null +++ b/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart @@ -0,0 +1,622 @@ +// 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 'blog_post_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 _$BlogPostState { + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(BlogPostModel blogPost) loaded, + required TResult Function(String errorMessage) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(BlogPostModel blogPost)? loaded, + TResult? Function(String errorMessage)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(BlogPostModel blogPost)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map( + TResult Function(_BlogPostState value) $default, { + required TResult Function(BlogPostStateLoading value) loading, + required TResult Function(BlogPostStateLoaded value) loaded, + required TResult Function(BlogPostStateError value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_BlogPostState value)? $default, { + TResult? Function(BlogPostStateLoading value)? loading, + TResult? Function(BlogPostStateLoaded value)? loaded, + TResult? Function(BlogPostStateError value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap( + TResult Function(_BlogPostState value)? $default, { + TResult Function(BlogPostStateLoading value)? loading, + TResult Function(BlogPostStateLoaded value)? loaded, + TResult Function(BlogPostStateError value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $BlogPostStateCopyWith<$Res> { + factory $BlogPostStateCopyWith( + BlogPostState value, $Res Function(BlogPostState) then) = + _$BlogPostStateCopyWithImpl<$Res, BlogPostState>; +} + +/// @nodoc +class _$BlogPostStateCopyWithImpl<$Res, $Val extends BlogPostState> + implements $BlogPostStateCopyWith<$Res> { + _$BlogPostStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; +} + +/// @nodoc +abstract class _$$BlogPostStateImplCopyWith<$Res> { + factory _$$BlogPostStateImplCopyWith( + _$BlogPostStateImpl value, $Res Function(_$BlogPostStateImpl) then) = + __$$BlogPostStateImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$BlogPostStateImplCopyWithImpl<$Res> + extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateImpl> + implements _$$BlogPostStateImplCopyWith<$Res> { + __$$BlogPostStateImplCopyWithImpl( + _$BlogPostStateImpl _value, $Res Function(_$BlogPostStateImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$BlogPostStateImpl implements _BlogPostState { + const _$BlogPostStateImpl(); + + @override + String toString() { + return 'BlogPostState()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$BlogPostStateImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(BlogPostModel blogPost) loaded, + required TResult Function(String errorMessage) error, + }) { + return $default(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(BlogPostModel blogPost)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return $default?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(BlogPostModel blogPost)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_BlogPostState value) $default, { + required TResult Function(BlogPostStateLoading value) loading, + required TResult Function(BlogPostStateLoaded value) loaded, + required TResult Function(BlogPostStateError value) error, + }) { + return $default(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_BlogPostState value)? $default, { + TResult? Function(BlogPostStateLoading value)? loading, + TResult? Function(BlogPostStateLoaded value)? loaded, + TResult? Function(BlogPostStateError value)? error, + }) { + return $default?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_BlogPostState value)? $default, { + TResult Function(BlogPostStateLoading value)? loading, + TResult Function(BlogPostStateLoaded value)? loaded, + TResult Function(BlogPostStateError value)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(this); + } + return orElse(); + } +} + +abstract class _BlogPostState implements BlogPostState { + const factory _BlogPostState() = _$BlogPostStateImpl; +} + +/// @nodoc +abstract class _$$BlogPostStateLoadingImplCopyWith<$Res> { + factory _$$BlogPostStateLoadingImplCopyWith(_$BlogPostStateLoadingImpl value, + $Res Function(_$BlogPostStateLoadingImpl) then) = + __$$BlogPostStateLoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$BlogPostStateLoadingImplCopyWithImpl<$Res> + extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadingImpl> + implements _$$BlogPostStateLoadingImplCopyWith<$Res> { + __$$BlogPostStateLoadingImplCopyWithImpl(_$BlogPostStateLoadingImpl _value, + $Res Function(_$BlogPostStateLoadingImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$BlogPostStateLoadingImpl implements BlogPostStateLoading { + const _$BlogPostStateLoadingImpl(); + + @override + String toString() { + return 'BlogPostState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$BlogPostStateLoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(BlogPostModel blogPost) loaded, + required TResult Function(String errorMessage) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(BlogPostModel blogPost)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(BlogPostModel blogPost)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_BlogPostState value) $default, { + required TResult Function(BlogPostStateLoading value) loading, + required TResult Function(BlogPostStateLoaded value) loaded, + required TResult Function(BlogPostStateError value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_BlogPostState value)? $default, { + TResult? Function(BlogPostStateLoading value)? loading, + TResult? Function(BlogPostStateLoaded value)? loaded, + TResult? Function(BlogPostStateError value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_BlogPostState value)? $default, { + TResult Function(BlogPostStateLoading value)? loading, + TResult Function(BlogPostStateLoaded value)? loaded, + TResult Function(BlogPostStateError value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class BlogPostStateLoading implements BlogPostState { + const factory BlogPostStateLoading() = _$BlogPostStateLoadingImpl; +} + +/// @nodoc +abstract class _$$BlogPostStateLoadedImplCopyWith<$Res> { + factory _$$BlogPostStateLoadedImplCopyWith(_$BlogPostStateLoadedImpl value, + $Res Function(_$BlogPostStateLoadedImpl) then) = + __$$BlogPostStateLoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({BlogPostModel blogPost}); + + $BlogPostModelCopyWith<$Res> get blogPost; +} + +/// @nodoc +class __$$BlogPostStateLoadedImplCopyWithImpl<$Res> + extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadedImpl> + implements _$$BlogPostStateLoadedImplCopyWith<$Res> { + __$$BlogPostStateLoadedImplCopyWithImpl(_$BlogPostStateLoadedImpl _value, + $Res Function(_$BlogPostStateLoadedImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? blogPost = null, + }) { + return _then(_$BlogPostStateLoadedImpl( + blogPost: null == blogPost + ? _value.blogPost + : blogPost // ignore: cast_nullable_to_non_nullable + as BlogPostModel, + )); + } + + @override + @pragma('vm:prefer-inline') + $BlogPostModelCopyWith<$Res> get blogPost { + return $BlogPostModelCopyWith<$Res>(_value.blogPost, (value) { + return _then(_value.copyWith(blogPost: value)); + }); + } +} + +/// @nodoc + +class _$BlogPostStateLoadedImpl implements BlogPostStateLoaded { + const _$BlogPostStateLoadedImpl({required this.blogPost}); + + @override + final BlogPostModel blogPost; + + @override + String toString() { + return 'BlogPostState.loaded(blogPost: $blogPost)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$BlogPostStateLoadedImpl && + (identical(other.blogPost, blogPost) || + other.blogPost == blogPost)); + } + + @override + int get hashCode => Object.hash(runtimeType, blogPost); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$BlogPostStateLoadedImplCopyWith<_$BlogPostStateLoadedImpl> get copyWith => + __$$BlogPostStateLoadedImplCopyWithImpl<_$BlogPostStateLoadedImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(BlogPostModel blogPost) loaded, + required TResult Function(String errorMessage) error, + }) { + return loaded(blogPost); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(BlogPostModel blogPost)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return loaded?.call(blogPost); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(BlogPostModel blogPost)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(blogPost); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_BlogPostState value) $default, { + required TResult Function(BlogPostStateLoading value) loading, + required TResult Function(BlogPostStateLoaded value) loaded, + required TResult Function(BlogPostStateError value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_BlogPostState value)? $default, { + TResult? Function(BlogPostStateLoading value)? loading, + TResult? Function(BlogPostStateLoaded value)? loaded, + TResult? Function(BlogPostStateError value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_BlogPostState value)? $default, { + TResult Function(BlogPostStateLoading value)? loading, + TResult Function(BlogPostStateLoaded value)? loaded, + TResult Function(BlogPostStateError value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class BlogPostStateLoaded implements BlogPostState { + const factory BlogPostStateLoaded({required final BlogPostModel blogPost}) = + _$BlogPostStateLoadedImpl; + + BlogPostModel get blogPost; + @JsonKey(ignore: true) + _$$BlogPostStateLoadedImplCopyWith<_$BlogPostStateLoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$BlogPostStateErrorImplCopyWith<$Res> { + factory _$$BlogPostStateErrorImplCopyWith(_$BlogPostStateErrorImpl value, + $Res Function(_$BlogPostStateErrorImpl) then) = + __$$BlogPostStateErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String errorMessage}); +} + +/// @nodoc +class __$$BlogPostStateErrorImplCopyWithImpl<$Res> + extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateErrorImpl> + implements _$$BlogPostStateErrorImplCopyWith<$Res> { + __$$BlogPostStateErrorImplCopyWithImpl(_$BlogPostStateErrorImpl _value, + $Res Function(_$BlogPostStateErrorImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? errorMessage = null, + }) { + return _then(_$BlogPostStateErrorImpl( + errorMessage: null == errorMessage + ? _value.errorMessage + : errorMessage // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$BlogPostStateErrorImpl implements BlogPostStateError { + const _$BlogPostStateErrorImpl({required this.errorMessage}); + + @override + final String errorMessage; + + @override + String toString() { + return 'BlogPostState.error(errorMessage: $errorMessage)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$BlogPostStateErrorImpl && + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); + } + + @override + int get hashCode => Object.hash(runtimeType, errorMessage); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$BlogPostStateErrorImplCopyWith<_$BlogPostStateErrorImpl> get copyWith => + __$$BlogPostStateErrorImplCopyWithImpl<_$BlogPostStateErrorImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(BlogPostModel blogPost) loaded, + required TResult Function(String errorMessage) error, + }) { + return error(errorMessage); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(BlogPostModel blogPost)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return error?.call(errorMessage); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(BlogPostModel blogPost)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(errorMessage); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_BlogPostState value) $default, { + required TResult Function(BlogPostStateLoading value) loading, + required TResult Function(BlogPostStateLoaded value) loaded, + required TResult Function(BlogPostStateError value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_BlogPostState value)? $default, { + TResult? Function(BlogPostStateLoading value)? loading, + TResult? Function(BlogPostStateLoaded value)? loaded, + TResult? Function(BlogPostStateError value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_BlogPostState value)? $default, { + TResult Function(BlogPostStateLoading value)? loading, + TResult Function(BlogPostStateLoaded value)? loaded, + TResult Function(BlogPostStateError value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class BlogPostStateError implements BlogPostState { + const factory BlogPostStateError({required final String errorMessage}) = + _$BlogPostStateErrorImpl; + + String get errorMessage; + @JsonKey(ignore: true) + _$$BlogPostStateErrorImplCopyWith<_$BlogPostStateErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/feed/blog_post_screen/blog_post_screen.dart b/lib/features/blog_post/presentation/pages/blog_post_screen.dart similarity index 62% rename from lib/presentation/feed/blog_post_screen/blog_post_screen.dart rename to lib/features/blog_post/presentation/pages/blog_post_screen.dart index dd2252b..f9fc969 100644 --- a/lib/presentation/feed/blog_post_screen/blog_post_screen.dart +++ b/lib/features/blog_post/presentation/pages/blog_post_screen.dart @@ -1,8 +1,8 @@ +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 'bloc/blog_post_bloc.dart'; -import 'models/blog_post_model.dart'; -import 'widgets/comment_widget.dart'; +import 'package:flutter/cupertino.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; @@ -12,53 +12,29 @@ import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; class BlogPostScreen extends StatelessWidget { - const BlogPostScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context, String blog_postID) { - return BlocProvider( - create: (context) => BlogPostBloc( - BlogPostState( - blog_postModelObj: BlogPostModel( - blog_postID: blog_postID.toString(), - ), - ), - )..add( - BlogPostInitialEvent(), - ), - child: BlogPostScreen(), - ); - } + final String blogPostID; + const BlogPostScreen({super.key, required this.blogPostID}); Widget build(BuildContext context) { - return BlocBuilder( - builder: (context, state) { - if (state is BlogPostInitialState) { - return Scaffold( - body: Center( - child: CircularProgressIndicator(), - ), - ); - } else if (state is BlogPostLoadedState) { - // Данные загружены, можно строить экран. - return _buildBlogPost(context, state); - } else if (state is BlogPostErrorState) { - // Произошла ошибка при загрузке данных. - return Center( - child: Text(state.errorMessage), - ); - } else { - return Scaffold( - body: Center( - child: CircularProgressIndicator(), - ), - ); - // Другие состояния, если они есть. - } - }, + return BlocProvider( + create: (context) => sl()..loadBlogPost(blogPostID), + child: BlocBuilder( + builder: (context, state) { + if (state is BlogPostStateLoaded) { + return _buildBlogPost(context, state); + } else { + return Scaffold( + body: Center( + child: CupertinoActivityIndicator(), + ), + ); + } + }, + ), ); } - _buildBlogPost(BuildContext context, BlogPostLoadedState state) { + _buildBlogPost(BuildContext context, BlogPostStateLoaded state) { return SafeArea( child: Scaffold( resizeToAvoidBottomInset: false, @@ -82,8 +58,8 @@ class BlogPostScreen extends StatelessWidget { ); } - _buildHeaderRow(BuildContext context, BlogPostLoadedState state) { - final String name = state.author?['name']; + _buildHeaderRow(BuildContext context, BlogPostStateLoaded state) { + final String name = state.blogPost.title; return Container( margin: EdgeInsets.symmetric(horizontal: 16.h, vertical: 16.h), padding: EdgeInsets.symmetric( @@ -121,7 +97,8 @@ class BlogPostScreen extends StatelessWidget { ), ), CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (state.author?['profile_photo_path'] ?? ''), + imageUrl: dotenv.env['STORAGE_URL']! + + (state.blogPost.author_avatar_path ?? ''), imageBuilder: (context, imageProvider) => CircleAvatar( backgroundImage: imageProvider, radius: 25, @@ -141,7 +118,7 @@ class BlogPostScreen extends StatelessWidget { ); } - _buildBlogPostData(BuildContext context, BlogPostLoadedState state) { + _buildBlogPostData(BuildContext context, BlogPostStateLoaded state) { return Container( margin: EdgeInsets.only( left: 16.h, @@ -161,79 +138,90 @@ class BlogPostScreen extends StatelessWidget { ), ], ), - child: Column(mainAxisSize: MainAxisSize.min, children: [ - Row( - children: [ - Text( - state.blog_post?['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.blog_post?['description'], - style: CustomTextStyles.bodyMediumBluegray800, - ), - SizedBox(height: 16.0), - Align( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Text( + state.blogPost.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.blogPost.description, + style: CustomTextStyles.bodyMediumBluegray800, + ), + SizedBox(height: 16.0), + Align( alignment: Alignment.topLeft, child: Text( - DateFormat('dd.MM.yyyy').format(DateTime.parse(state.blog_post?['updated_at'])), + DateFormat('dd.MM.yyyy').format(state.blogPost.updatedAt), style: theme.textTheme.bodyMedium, - ),), - 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), + 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, + ), + ], ), - ],),), - ],), - ],), + ), + ], + ), + ], + ), ); } - _buildImage(BlogPostLoadedState state) { + _buildImage(BlogPostStateLoaded state) { return CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (state.blog_post?['image'] ?? ''), + imageUrl: dotenv.env['STORAGE_URL']! + (state.blogPost.image ?? ""), imageBuilder: (context, imageProvider) => Stack( children: [ ClipRRect( @@ -290,7 +278,7 @@ class BlogPostScreen extends StatelessWidget { ), SizedBox(width: 4.0), Text( - '${state.comments?.length}', + '42', style: TextStyle(color: Colors.white), ), ], @@ -306,18 +294,18 @@ class BlogPostScreen extends StatelessWidget { ); } - void tapMenu(String value, BuildContext context, BlogPostLoadedState state) { + void tapMenu(String value, BuildContext context, BlogPostStateLoaded state) { if (value == 'edit') { GoRouter.of(context).goNamed( 'blogPostEditScreen', - extra: state.blog_post?['id'].toString(), + extra: state.blogPost.id.toString(), ); } else if (value == 'delete') { - context.read().add(DeleteEntry(state.blog_post?['id'])); + // context.read().add(DeleteEntry(state.blog_post?['id'])); } } - _buildTextField(BuildContext context, BlogPostLoadedState state) { + _buildTextField(BuildContext context, BlogPostStateLoaded state) { return Container( margin: EdgeInsets.only( left: 16.h, @@ -343,7 +331,7 @@ class BlogPostScreen extends StatelessWidget { Column( children: [ CustomTextFormField( - controller: state.commentController, + // controller: state.commentController, maxLines: 4, ), SizedBox(height: 15.h), @@ -354,7 +342,9 @@ class BlogPostScreen extends StatelessWidget { decoration: BoxDecoration( color: Colors.transparent, ), - onPressed: () => context.read().add(CreateComment(state.commentController!.text)), + /* onPressed: () => context + .read() + .add(CreateComment(state.commentController!.text)),*/ // Установите прозрачный фон ), ], @@ -364,9 +354,9 @@ class BlogPostScreen extends StatelessWidget { ); } - _buildCommentSection(BuildContext context, BlogPostLoadedState state) { - if (state.comments != null && state.comments!.isNotEmpty) { - return Column( + _buildCommentSection(BuildContext context, BlogPostStateLoaded state) { + /* if (state.comments != null && state.comments!.isNotEmpty) { + return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ for (int i = 0; i < state.comments!.length; i++) @@ -380,15 +370,14 @@ class BlogPostScreen extends StatelessWidget { ], ); } else { - // Return a message or placeholder widget when there are no comments - return Center( - child: Text('No comments available'), - ); - } - } - - /// Navigates to the previous screen. - onTapArrowleftone(BuildContext context) { - GoRouter.of(context).pop(); + // Return a message or placeholder widget when there are no comments*/ + return Center( + child: Text('No comments available'), + ); } } + +/// Navigates to the previous screen. +onTapArrowleftone(BuildContext context) { + GoRouter.of(context).pop(); +} diff --git a/lib/features/blog_post/repositories/blog_post_repository.dart b/lib/features/blog_post/repositories/blog_post_repository.dart new file mode 100644 index 0000000..b0c5a7a --- /dev/null +++ b/lib/features/blog_post/repositories/blog_post_repository.dart @@ -0,0 +1,16 @@ +import 'package:eatvio_app/features/blog_post/models/blog_post_model.dart'; +import 'package:eatvio_app/features/blog_post/services/blog_post_service.dart'; + +class BlogPostRepository { + final BlogPostService blogPostService; + + BlogPostRepository({required this.blogPostService}); + + Future getBlogPost(String blogPostID) async { + try { + return await blogPostService.getBlogPost(blogPostID); + } catch (e) { + rethrow; + } + } +} diff --git a/lib/features/blog_post/services/blog_post_service.dart b/lib/features/blog_post/services/blog_post_service.dart new file mode 100644 index 0000000..a406a7f --- /dev/null +++ b/lib/features/blog_post/services/blog_post_service.dart @@ -0,0 +1,13 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/blog_post/models/blog_post_model.dart'; +import 'package:retrofit/retrofit.dart'; + +part 'blog_post_service.g.dart'; + +@RestApi() +abstract class BlogPostService { + factory BlogPostService(Dio dio, {String baseUrl}) = _BlogPostService; + + @GET('/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 new file mode 100644 index 0000000..7af4607 --- /dev/null +++ b/lib/features/blog_post/services/blog_post_service.g.dart @@ -0,0 +1,77 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'blog_post_service.dart'; + +// ************************************************************************** +// RetrofitGenerator +// ************************************************************************** + +// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers + +class _BlogPostService implements BlogPostService { + _BlogPostService( + this._dio, { + this.baseUrl, + }); + + final Dio _dio; + + String? baseUrl; + + @override + Future getBlogPost(String id) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio + .fetch>(_setStreamType(Options( + method: 'GET', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/feed/show/${id}', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final value = BlogPostModel.fromJson(_result.data!); + 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/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart b/lib/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart index 6a52223..02ee767 100644 --- a/lib/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart +++ b/lib/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart @@ -8,7 +8,7 @@ class FeedCubit extends Cubit { FeedCubit({required this.feedRepository}) : super(const FeedState.loading()); loadFeedBlogPostList() async { - emit(const FeedStateLoading()); + emit(const FeedState.loading()); try { final feedBlogPostList = await feedRepository.getFeedBlogPostList(); emit(FeedState.loaded(feedBlogPostList: feedBlogPostList)); diff --git a/lib/features/feed/presentation/pages/feed_screen.dart b/lib/features/feed/presentation/pages/feed_screen.dart index dca0eef..d42e776 100644 --- a/lib/features/feed/presentation/pages/feed_screen.dart +++ b/lib/features/feed/presentation/pages/feed_screen.dart @@ -100,7 +100,8 @@ class FeedScreen extends StatelessWidget { flex: 1, child: CustomOutlinedButton( text: "+", - onPressed: () => GoRouter.of(context).goNamed('blogPostCreateScreen'), + onPressed: () => + GoRouter.of(context).goNamed('blogPostCreateScreen'), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, ), ), @@ -144,7 +145,7 @@ class FeedScreen extends StatelessWidget { children: [ ListTile( leading: CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + ('' ?? ''), + imageUrl: dotenv.env['STORAGE_URL']! + (''), /// todo profile photo path imageBuilder: (context, imageProvider) => CircleAvatar( @@ -215,11 +216,12 @@ class FeedScreen extends StatelessWidget { ), SizedBox(height: 16.0), CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + (post.image ?? ''), + imageUrl: dotenv.env['STORAGE_URL']! + (post.image), imageBuilder: (context, imageProvider) => Stack( children: [ ClipRRect( - borderRadius: const BorderRadius.all(Radius.circular(8.0)), + borderRadius: + const BorderRadius.all(Radius.circular(8.0)), child: Image( image: imageProvider, ), diff --git a/lib/locator_service.dart b/lib/locator_service.dart index 9780f41..2f4ee2f 100644 --- a/lib/locator_service.dart +++ b/lib/locator_service.dart @@ -1,5 +1,8 @@ import 'package:dio/dio.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'; +import 'package:eatvio_app/features/blog_post/services/blog_post_service.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; import 'package:eatvio_app/features/chat/services/chat_service.dart'; @@ -14,16 +17,24 @@ final sl = GetIt.instance; Future init() async { // BLoC sl.registerFactory(() => ChatRoomCubit(chatRepository: sl())); - sl.registerFactory(() => InitializationCubit(chatRepository: sl())); + sl.registerFactory( + () => InitializationCubit(chatRepository: sl())); sl.registerFactory(() => FeedCubit(feedRepository: sl())); + sl.registerFactory( + () => BlogPostCubit(blogPostRepository: sl())); // Repository - sl.registerLazySingleton(() => ChatRepository(chatService: sl())); - sl.registerLazySingleton(() => FeedRepository(feedService: sl())); + sl.registerLazySingleton( + () => ChatRepository(chatService: sl())); + sl.registerLazySingleton( + () => FeedRepository(feedService: sl())); + sl.registerLazySingleton( + () => BlogPostRepository(blogPostService: sl())); // Services sl.registerLazySingleton(() => ChatService(sl())); sl.registerLazySingleton(() => FeedService(sl())); + sl.registerLazySingleton(() => BlogPostService(sl())); // External sl.registerLazySingleton( diff --git a/lib/presentation/feed/blog_post_screen/bloc/blog_post_bloc.dart b/lib/presentation/feed/blog_post_screen/bloc/blog_post_bloc.dart deleted file mode 100644 index b93c18c..0000000 --- a/lib/presentation/feed/blog_post_screen/bloc/blog_post_bloc.dart +++ /dev/null @@ -1,184 +0,0 @@ -import 'dart:async'; - -import 'package:eatvio_app/app_router.dart'; -import 'package:eatvio_app/presentation/feed/blog_post_screen/models/comment_model.dart'; -import 'package:equatable/equatable.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_dotenv/flutter_dotenv.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/feed/blog_post_screen/models/blog_post_model.dart'; -import 'package:go_router/go_router.dart'; -part 'blog_post_event.dart'; -part 'blog_post_state.dart'; - -/// A bloc that manages the state of a BlogPost according to the event that is dispatched to it. -class BlogPostBloc extends Bloc { - BlogPostBloc(BlogPostState initialState) : super(initialState) { - on(_onInitialize); - on(_deleteEntry); - on(_createComment); - } - - _onInitialize( - BlogPostInitialEvent event, - Emitter emit, - ) async { - try { - final box = await Hive.openBox('token'); - final token = box.get('token'); - if (token == null) { - AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); - } - final String? blog_postID = state.blog_postModelObj?.blog_postID; - final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/feed/show/$blog_postID'), - headers: { - 'Authorization': 'Bearer $token', - }, - ); - if (response.statusCode == 200) { - final data = jsonDecode(response.body); - if (data is Map) { - if (state is BlogPostLoadedState) { - var currentState = state as BlogPostLoadedState; - emit(currentState.copyWith( - blog_postModelObj: currentState.blog_postModelObj, - blog_post: currentState.blog_post, - author: currentState.author, - comments: currentState.comments, - token: currentState.token,),); - } else { - emit(BlogPostLoadedState( - blog_post: data, - token: token, - commentController: TextEditingController(), - author: await _fetchAuthor(data['id']), - comments: fillCommentList(await _fetchComments(data['id'])),),); - } - } else { - // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку - emit(BlogPostErrorState('Некоторые необходимые данные отсутствуют.')); - } - } else { - // Статус ответа не равен 200, обрабатываем ошибку - emit(BlogPostErrorState('Ошибка сервера: ${response.statusCode}')); - } - } catch (e) { - // Ошибка при декодировании JSON или другая ошибка выполнения - emit(BlogPostErrorState('Ошибка при получении данных о чатах: $e')); - } - } - - FutureOr _createComment( - CreateComment event, Emitter emit,) async { - if (state is BlogPostLoadedState) { - var currentState = state as BlogPostLoadedState; - // Отправляем данные по HTTP маршруту и ждем ответ - var response = await _sendCommentData( - currentState.token, event.body, currentState.blog_post?['id'],); - if (response.statusCode == 200) { - var updatedComments = fillCommentList( - await _fetchComments(currentState.blog_post?['id']),); - var updatedState = currentState.copyWith( - comments: updatedComments, - commentController: - TextEditingController(), // Clear the comment input field - ); - emit(updatedState); // Emit the updated state to trigger a screen update - } - } - } - - FutureOr _deleteEntry( - DeleteEntry event, Emitter emit,) async { - final box = await Hive.openBox('token'); - final token = box.get('token'); - if (token == null) { - AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); - } - final int id = event.id; - final response = await http.post( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/feed/delete/$id'), - headers: { - 'Authorization': 'Bearer $token', - }, - ); - if (response.statusCode == 200) { - AppRouter.navigatorKey.currentContext?.goNamed('feedScreen'); - } else { - // Статус ответа не равен 200, обрабатываем ошибку - emit(BlogPostErrorState('Ошибка: ${response.statusCode}')); - } - } - - _fetchAuthor(int id) async { - final box = await Hive.openBox('token'); - final token = box.get('token'); - - if (token == null) { - AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); - } - - final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/feed/getAuthor/$id'), - headers: { - 'Authorization': 'Bearer $token', - }, - ); - final data = jsonDecode(response.body); - return data; - } - - Future _fetchComments(int id) async { - final box = await Hive.openBox('token'); - final token = box.get('token'); - if (token == null) { - AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); - } - final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/feed/getComments/$id'), - headers: { - 'Authorization': 'Bearer $token', - }, - ); - final data = jsonDecode(response.body); - return data; - } - - List fillCommentList(List comments) { - List list = []; - for (int i = 0; i < comments.length; i++) { - 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'],),); - } - return list; - } - - Future _sendCommentData( - String? token, String body, int id,) async { - String url = dotenv.env['SERVER_ROOT']! + '/feed/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,); - - return response; - } -} diff --git a/lib/presentation/feed/blog_post_screen/bloc/blog_post_event.dart b/lib/presentation/feed/blog_post_screen/bloc/blog_post_event.dart deleted file mode 100644 index e143511..0000000 --- a/lib/presentation/feed/blog_post_screen/bloc/blog_post_event.dart +++ /dev/null @@ -1,44 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'blog_post_bloc.dart'; - -/// Abstract class for all events that can be dispatched from the -///BlogPost widget. -/// -/// Events must be immutable and implement the [Equatable] interface. -@immutable -abstract class BlogPostEvent extends Equatable {} - -/// Event that is dispatched when the BlogPost widget is first created. -class BlogPostInitialEvent extends BlogPostEvent { - @override - List get props => []; -} - -class DeleteEntry extends BlogPostEvent { - DeleteEntry(this.id); - final int id; - @override - List get props => [id]; -} - -class FetchAuthor extends BlogPostEvent { - FetchAuthor(this.id); - final int id; - @override - List get props => [id]; -} - -class FetchComments extends BlogPostEvent { - FetchComments(this.id); - final int id; - @override - List get props => [id]; -} - -class CreateComment extends BlogPostEvent { - CreateComment(this.body); - final String body; - @override - List get props => [body]; -} diff --git a/lib/presentation/feed/blog_post_screen/bloc/blog_post_state.dart b/lib/presentation/feed/blog_post_screen/bloc/blog_post_state.dart deleted file mode 100644 index 982eac9..0000000 --- a/lib/presentation/feed/blog_post_screen/bloc/blog_post_state.dart +++ /dev/null @@ -1,70 +0,0 @@ -// ignore_for_file: must_be_immutable - -part of 'blog_post_bloc.dart'; - -/// Represents the state of BlogPost in the application. -/// - -class BlogPostState extends Equatable { - BlogPostState({ - this.blog_postModelObj, - }); - - BlogPostModel? blog_postModelObj; - - @override - List get props => [blog_postModelObj]; - BlogPostState copyWith({BlogPostModel? blog_postModelObj}) { - return BlogPostState( - blog_postModelObj: blog_postModelObj ?? this.blog_postModelObj, - ); - } -} - -class BlogPostLoadedState extends BlogPostState { - BlogPostLoadedState( - {this.blog_postModelObj, - this.blog_post, - this.author, - this.comments, - this.token, - this.commentController,}); - - BlogPostModel? blog_postModelObj; - Map? blog_post; - Map? author; - List? comments; - TextEditingController? commentController; - String? token; - @override - List get props => [blog_postModelObj, blog_post, author, comments]; - BlogPostLoadedState copyWith( - {BlogPostModel? blog_postModelObj, - Map? blog_post, - Map? author, - TextEditingController? commentController, - String? token, - List? comments,}) { - return BlogPostLoadedState( - blog_postModelObj: blog_postModelObj ?? this.blog_postModelObj, - blog_post: blog_post ?? this.blog_post, - author: author ?? this.author, - comments: comments ?? this.comments, - token: token ?? this.token, - commentController: commentController ?? this.commentController,); - } -} - -class BlogPostErrorState extends BlogPostState { - final String errorMessage; - - BlogPostErrorState(this.errorMessage); - - @override - List get props => [errorMessage]; -} - -class BlogPostInitialState extends BlogPostState { - BlogPostInitialState({required BlogPostModel blog_postModelObj}) - : super(blog_postModelObj: blog_postModelObj); -} -- 2.49.1 From c9c8883e01961bea573ef571bcf5f12717c27a68 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Mon, 1 Jul 2024 16:08:43 +0300 Subject: [PATCH 014/110] feat(chat): pusher --- .gitea/workflows/test.yml | 4 +- .../initialization_cubit.dart | 65 ++++++++++------- .../chat/models/websocket_info_model.dart | 3 + .../models/websocket_info_model.freezed.dart | 71 ++++++++++++++++--- .../chat/models/websocket_info_model.g.dart | 4 ++ pubspec.yaml | 6 +- 6 files changed, 114 insertions(+), 39 deletions(-) diff --git a/.gitea/workflows/test.yml b/.gitea/workflows/test.yml index ffd3281..a21834f 100644 --- a/.gitea/workflows/test.yml +++ b/.gitea/workflows/test.yml @@ -84,8 +84,8 @@ jobs: - name: Native Analyze run: flutter analyze - - name: Run Code Metrics - run: flutter pub run dart_code_metrics:metrics lib --disable-sunset-warning --fatal-warnings --fatal-performance + #- name: Run Code Metrics + # run: flutter pub run dart_code_metrics:metrics lib --disable-sunset-warning --fatal-warnings --fatal-performance - name: Test run: | diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index a3db291..2dabef5 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -2,7 +2,6 @@ import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_state.dart'; import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; -import 'package:pusher_client/pusher_client.dart'; class InitializationCubit extends Cubit { final ChatRepository chatRepository; @@ -12,29 +11,47 @@ class InitializationCubit extends Cubit { runInitialization() async { try { await TokenStorage.haveTokenInStorage(); - final wsUrl = await chatRepository.getWebsocket(); - - PusherOptions options = PusherOptions( - host: 'socket.mobile-stage.eatvio.ru', - wsPort: 443, - encrypted: true, - auth: PusherAuth( - 'wss://' + wsUrl.host + '/app/' + wsUrl.key, - headers: { - 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', - }, - ), - ); - - PusherClient pusherClient = await PusherClient( - wsUrl.key, - options, - autoConnect: true, - enableLogging: true, - ); - - await pusherClient.connect(); - + // 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(); + // final myPrivateChannel = client.privateChannel( + // 'private-message-events.${wsUrl.userId}', + // authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( + // authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), + // headers: { + // 'Authorization' : 'Bearer ${await TokenStorage.getTokenFromStorage()}', + // }, + // ), + // ); + // myPrivateChannel.subscribe(); + // myPrivateChannel.bindToAll().listen((event) { + // print(event.name); + // }); emit(const InitializationState.success()); } catch (e) { print(e); diff --git a/lib/features/chat/models/websocket_info_model.dart b/lib/features/chat/models/websocket_info_model.dart index 281c71e..274b421 100644 --- a/lib/features/chat/models/websocket_info_model.dart +++ b/lib/features/chat/models/websocket_info_model.dart @@ -10,6 +10,9 @@ class WebsocketInfoModel with _$WebsocketInfoModel { required String key, required String host, required String port, + required String cluster, + @JsonKey(name: 'user_id') + required int userId, }) = _WebsocketInfoModel; factory WebsocketInfoModel.fromJson(Map json) => _$WebsocketInfoModelFromJson(json); diff --git a/lib/features/chat/models/websocket_info_model.freezed.dart b/lib/features/chat/models/websocket_info_model.freezed.dart index 9a26fee..cd383a2 100644 --- a/lib/features/chat/models/websocket_info_model.freezed.dart +++ b/lib/features/chat/models/websocket_info_model.freezed.dart @@ -23,6 +23,9 @@ mixin _$WebsocketInfoModel { String get key => throw _privateConstructorUsedError; String get host => throw _privateConstructorUsedError; String get port => throw _privateConstructorUsedError; + String get cluster => throw _privateConstructorUsedError; + @JsonKey(name: 'user_id') + int get userId => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -36,7 +39,12 @@ abstract class $WebsocketInfoModelCopyWith<$Res> { WebsocketInfoModel value, $Res Function(WebsocketInfoModel) then) = _$WebsocketInfoModelCopyWithImpl<$Res, WebsocketInfoModel>; @useResult - $Res call({String key, String host, String port}); + $Res call( + {String key, + String host, + String port, + String cluster, + @JsonKey(name: 'user_id') int userId}); } /// @nodoc @@ -55,6 +63,8 @@ class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel> Object? key = null, Object? host = null, Object? port = null, + Object? cluster = null, + Object? userId = null, }) { return _then(_value.copyWith( key: null == key @@ -69,6 +79,14 @@ class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel> ? _value.port : port // ignore: cast_nullable_to_non_nullable as String, + cluster: null == cluster + ? _value.cluster + : cluster // ignore: cast_nullable_to_non_nullable + as String, + userId: null == userId + ? _value.userId + : userId // ignore: cast_nullable_to_non_nullable + as int, ) as $Val); } } @@ -81,7 +99,12 @@ abstract class _$$WebsocketInfoModelImplCopyWith<$Res> __$$WebsocketInfoModelImplCopyWithImpl<$Res>; @override @useResult - $Res call({String key, String host, String port}); + $Res call( + {String key, + String host, + String port, + String cluster, + @JsonKey(name: 'user_id') int userId}); } /// @nodoc @@ -98,6 +121,8 @@ class __$$WebsocketInfoModelImplCopyWithImpl<$Res> Object? key = null, Object? host = null, Object? port = null, + Object? cluster = null, + Object? userId = null, }) { return _then(_$WebsocketInfoModelImpl( key: null == key @@ -112,6 +137,14 @@ class __$$WebsocketInfoModelImplCopyWithImpl<$Res> ? _value.port : port // ignore: cast_nullable_to_non_nullable as String, + cluster: null == cluster + ? _value.cluster + : cluster // ignore: cast_nullable_to_non_nullable + as String, + userId: null == userId + ? _value.userId + : userId // ignore: cast_nullable_to_non_nullable + as int, )); } } @@ -120,7 +153,11 @@ class __$$WebsocketInfoModelImplCopyWithImpl<$Res> @JsonSerializable() class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { const _$WebsocketInfoModelImpl( - {required this.key, required this.host, required this.port}); + {required this.key, + required this.host, + required this.port, + required this.cluster, + @JsonKey(name: 'user_id') required this.userId}); factory _$WebsocketInfoModelImpl.fromJson(Map json) => _$$WebsocketInfoModelImplFromJson(json); @@ -131,10 +168,15 @@ class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { final String host; @override final String port; + @override + final String cluster; + @override + @JsonKey(name: 'user_id') + final int userId; @override String toString() { - return 'WebsocketInfoModel(key: $key, host: $host, port: $port)'; + return 'WebsocketInfoModel(key: $key, host: $host, port: $port, cluster: $cluster, userId: $userId)'; } @override @@ -144,12 +186,15 @@ class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { other is _$WebsocketInfoModelImpl && (identical(other.key, key) || other.key == key) && (identical(other.host, host) || other.host == host) && - (identical(other.port, port) || other.port == port)); + (identical(other.port, port) || other.port == port) && + (identical(other.cluster, cluster) || other.cluster == cluster) && + (identical(other.userId, userId) || other.userId == userId)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, key, host, port); + int get hashCode => + Object.hash(runtimeType, key, host, port, cluster, userId); @JsonKey(ignore: true) @override @@ -168,9 +213,12 @@ class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { abstract class _WebsocketInfoModel implements WebsocketInfoModel { const factory _WebsocketInfoModel( - {required final String key, - required final String host, - required final String port}) = _$WebsocketInfoModelImpl; + {required final String key, + required final String host, + required final String port, + required final String cluster, + @JsonKey(name: 'user_id') required final int userId}) = + _$WebsocketInfoModelImpl; factory _WebsocketInfoModel.fromJson(Map json) = _$WebsocketInfoModelImpl.fromJson; @@ -182,6 +230,11 @@ abstract class _WebsocketInfoModel implements WebsocketInfoModel { @override String get port; @override + String get cluster; + @override + @JsonKey(name: 'user_id') + int get userId; + @override @JsonKey(ignore: true) _$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith => throw _privateConstructorUsedError; diff --git a/lib/features/chat/models/websocket_info_model.g.dart b/lib/features/chat/models/websocket_info_model.g.dart index e5b5c32..b2bb124 100644 --- a/lib/features/chat/models/websocket_info_model.g.dart +++ b/lib/features/chat/models/websocket_info_model.g.dart @@ -12,6 +12,8 @@ _$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson( key: json['key'] as String, host: json['host'] as String, port: json['port'] as String, + cluster: json['cluster'] as String, + userId: (json['user_id'] as num).toInt(), ); Map _$$WebsocketInfoModelImplToJson( @@ -20,4 +22,6 @@ Map _$$WebsocketInfoModelImplToJson( 'key': instance.key, 'host': instance.host, 'port': instance.port, + 'cluster': instance.cluster, + 'user_id': instance.userId, }; diff --git a/pubspec.yaml b/pubspec.yaml index 8633537..d3572e0 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -59,8 +59,8 @@ dependencies: get_it: ^7.7.0 # http request dio: ^5.4.3+1 - # websocket - pusher_client: ^2.0.0 + # pusher + dart_pusher_channels: ^1.2.2+1 # photo gallery viewer + dismissible page photo_view: ^0.15.0 dismissible_page: ^1.0.2 @@ -68,8 +68,6 @@ dependencies: url_launcher: ^6.3.0 dev_dependencies: - dart_code_metrics: ^5.7.6 - dart_code_metrics_presets: ^1.8.0 build_runner: ^2.4.11 freezed: ^2.5.2 json_serializable: ^6.8.0 -- 2.49.1 From a022d87adb1e2b9719f6e794b4c6f06462f09238 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Mon, 1 Jul 2024 16:57:43 +0300 Subject: [PATCH 015/110] refactor(blog_post): Refactoring blog post create and conflict resolve --- lib/app_router.dart | 2 +- .../initialization_cubit.dart | 31 ------------------- lib/core/token_storage.dart | 6 ++-- .../blog_post_create_credentials_model.dart | 4 +-- .../pages}/blog_post_create_screen.dart | 4 +-- .../repositories/blog_repository.dart | 4 +-- .../services/blog_service.dart | 2 +- .../services/blog_service.g.dart | 0 .../bloc/diary_edit_bloc.dart | 8 ++--- .../bloc/diary_edit_state.dart | 8 ++--- .../diary_edit_screen/diary_edit_screen.dart | 6 ++-- ...post_create_credentials_model.freezed.dart | 2 +- .../blog_post_create_credentials_model.g.dart | 2 +- 13 files changed, 23 insertions(+), 56 deletions(-) rename lib/{presentation/feed/blog_post_create_screen => features/blog_post_create}/models/blog_post_create_credentials_model.dart (70%) rename lib/{presentation/feed/blog_post_create_screen => features/blog_post_create/presentation/pages}/blog_post_create_screen.dart (97%) rename lib/{presentation/feed/blog_post_create_screen => features/blog_post_create}/repositories/blog_repository.dart (62%) rename lib/{presentation/feed/blog_post_create_screen => features/blog_post_create}/services/blog_service.dart (74%) rename lib/{presentation/feed/blog_post_create_screen => features/blog_post_create}/services/blog_service.g.dart (100%) diff --git a/lib/app_router.dart b/lib/app_router.dart index 0b8c097..dada825 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -5,7 +5,7 @@ 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/presentation/feed/blog_post_create_screen/blog_post_create_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'; diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index 57544ae..8938568 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -15,37 +15,6 @@ class InitializationCubit extends Cubit { final wsUrl = await chatRepository.getWebsocket(); - PusherOptions options = PusherOptions( - host: 'socket.mobile-stage.eatvio.ru', - wsPort: 443, - encrypted: true, - auth: PusherAuth( - 'wss://' + wsUrl.host + '/app/' + wsUrl.key, - headers: { - 'Authorization': 'Bearer ${TokenStorage.getTokenFromStorage()}', - }, - ), - ); - - PusherClient pusherClient = PusherClient( - wsUrl.key, - options, - autoConnect: true, - enableLogging: true, - ); - - await pusherClient.connect(); - - emit(const InitializationState.success()); - - Channel channel = pusherClient.subscribe('private-direct-chat.' + '7909ea56-7822-4d5f-8892-134bc937127f'); - - channel.bind("pusher_internal:subscription_succeeded", (PusherEvent? event) { - channel.trigger("pusher_internal:subscription_succeeded", {}); - }); - - channel.registerListener('pusher:subscribe', (data) => print(data.toString())); - } catch (e) { print(e); emit(InitializationState.error(errorMessage: e.toString())); diff --git a/lib/core/token_storage.dart b/lib/core/token_storage.dart index 01ac606..1179241 100644 --- a/lib/core/token_storage.dart +++ b/lib/core/token_storage.dart @@ -18,14 +18,12 @@ abstract class TokenStorage { } } - static Future getTokenFromStorage() async => - (await Hive.openBox('token')).get('token'); + static Future getTokenFromStorage() async => (await Hive.openBox('token')).get('token'); static saveTokenInStorage(String token) async { (await Hive.openBox('token')).put('token', token); _addTokenToDioHeader(token); } - static removeTokenInStorage() async => - (await Hive.openBox('token')).delete('token'); + static removeTokenInStorage() async => (await Hive.openBox('token')).delete('token'); } diff --git a/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.dart b/lib/features/blog_post_create/models/blog_post_create_credentials_model.dart similarity index 70% rename from lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.dart rename to lib/features/blog_post_create/models/blog_post_create_credentials_model.dart index 1464eb0..71c84d3 100644 --- a/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.dart +++ b/lib/features/blog_post_create/models/blog_post_create_credentials_model.dart @@ -1,6 +1,6 @@ import 'package:freezed_annotation/freezed_annotation.dart'; -part 'blog_post_create_credentials_model.freezed.dart'; -part 'blog_post_create_credentials_model.g.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'; @freezed class BlogPostCreateCredentialsModel with _$BlogPostCreateCredentialsModel { diff --git a/lib/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart b/lib/features/blog_post_create/presentation/pages/blog_post_create_screen.dart similarity index 97% rename from lib/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart rename to lib/features/blog_post_create/presentation/pages/blog_post_create_screen.dart index 225a771..4bedcf5 100644 --- a/lib/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart +++ b/lib/features/blog_post_create/presentation/pages/blog_post_create_screen.dart @@ -1,5 +1,5 @@ -import 'bloc/blog_post_create_bloc.dart'; -import 'models/blog_post_create_model.dart'; +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 'package:eatvio_app/core/app_export.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; diff --git a/lib/presentation/feed/blog_post_create_screen/repositories/blog_repository.dart b/lib/features/blog_post_create/repositories/blog_repository.dart similarity index 62% rename from lib/presentation/feed/blog_post_create_screen/repositories/blog_repository.dart rename to lib/features/blog_post_create/repositories/blog_repository.dart index 74f79cd..e11bce9 100644 --- a/lib/presentation/feed/blog_post_create_screen/repositories/blog_repository.dart +++ b/lib/features/blog_post_create/repositories/blog_repository.dart @@ -1,5 +1,5 @@ -import 'package:eatvio_app/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.dart'; -import 'package:eatvio_app/presentation/feed/blog_post_create_screen/services/blog_service.dart'; +import 'package:eatvio_app/features/blog_post_create/models/blog_post_create_credentials_model.dart'; +import 'package:eatvio_app/features/blog_post_create/services/blog_service.dart'; class BlogRepository { final BlogService blogService; diff --git a/lib/presentation/feed/blog_post_create_screen/services/blog_service.dart b/lib/features/blog_post_create/services/blog_service.dart similarity index 74% rename from lib/presentation/feed/blog_post_create_screen/services/blog_service.dart rename to lib/features/blog_post_create/services/blog_service.dart index e559383..1291c9a 100644 --- a/lib/presentation/feed/blog_post_create_screen/services/blog_service.dart +++ b/lib/features/blog_post_create/services/blog_service.dart @@ -1,4 +1,4 @@ -import 'package:eatvio_app/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.dart'; +import 'package:eatvio_app/features/blog_post_create/models/blog_post_create_credentials_model.dart'; import 'package:dio/dio.dart'; import 'package:retrofit/retrofit.dart'; diff --git a/lib/presentation/feed/blog_post_create_screen/services/blog_service.g.dart b/lib/features/blog_post_create/services/blog_service.g.dart similarity index 100% rename from lib/presentation/feed/blog_post_create_screen/services/blog_service.g.dart rename to lib/features/blog_post_create/services/blog_service.g.dart 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 591cad6..d279105 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 @@ -190,12 +190,12 @@ class DiaryEditBloc extends Bloc { final recommendedChartValues = jsonDecode(responseChart.body)['dailyNutritionRecommendation'] .values - .map((value) => value as int) + .map((value) => value as double) .toList(); final consumedChartValues = jsonDecode(responseChart.body)['dailyNutritionIntake'] .values - .map((value) => value as int) + .map((value) => value as double) .toList(); return [recommendedChartValues, consumedChartValues]; } else { @@ -275,10 +275,10 @@ class DiaryEditBloc extends Bloc { moderationExpanded: false, token: token, recommendedChartValues: recommendedChartValues.values - .map((value) => value as int) + .map((value) => value as double) .toList(), consumedChartValues: consumedChartValues.values - .map((value) => value as int) + .map((value) => value as double) .toList(), meals: diary['meals'], portions: diary['meals'][0]['portions'], diff --git a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart index fc8e197..6486b03 100644 --- a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart +++ b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart @@ -57,8 +57,8 @@ class DiaryEditLoadedState extends DiaryEditState { List? portions; List? photos; List? autocompleteList; - List recommendedChartValues; - List consumedChartValues; + List recommendedChartValues; + List consumedChartValues; SelectionPopupModel? currentMeal; SelectionPopupModel? portionController; TimeOfDay? wakeupController; @@ -117,8 +117,8 @@ class DiaryEditLoadedState extends DiaryEditState { SelectionPopupModel? portionController, String? diaryDate, String? token, - List? recommendedChartValues, - List? consumedChartValues, + List? recommendedChartValues, + List? consumedChartValues, List? meals, List? portions, List? photos, 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 77aa77f..5f94a18 100644 --- a/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart +++ b/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart @@ -720,8 +720,8 @@ class DiaryEditScreen extends StatelessWidget { } _buildNutritionChart(BuildContext context, DiaryEditLoadedState state) { - final List recommendedValues = state.recommendedChartValues; // Рекомендуемые значения: калории, жиры, белки, углеводы - final List consumedValues = state.consumedChartValues; // + final List recommendedValues = state.recommendedChartValues; // Рекомендуемые значения: калории, жиры, белки, углеводы + final List consumedValues = state.consumedChartValues; // return Container( margin: EdgeInsets.symmetric(horizontal: 16.h), padding: EdgeInsets.symmetric( @@ -1196,7 +1196,7 @@ class DiaryEditScreen extends StatelessWidget { } } -bool checkConsumedValues(List recommendedValues, List consumedValues) { +bool checkConsumedValues(List recommendedValues, List consumedValues) { for (int i = 0; i < recommendedValues.length; i++) { if (consumedValues[i] > recommendedValues[i]) { // Если хотя бы одно потребленное значение превышает рекомендованное 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 87eb9e1..d403e45 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 @@ -3,7 +3,7 @@ // 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 'blog_post_create_credentials_model.dart'; +part of '../../../../features/blog_post_create/models/blog_post_create_credentials_model.dart'; // ************************************************************************** // FreezedGenerator 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 bf339e9..5dec030 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 @@ -1,6 +1,6 @@ // GENERATED CODE - DO NOT MODIFY BY HAND -part of 'blog_post_create_credentials_model.dart'; +part of '../../../../features/blog_post_create/models/blog_post_create_credentials_model.dart'; // ************************************************************************** // JsonSerializableGenerator -- 2.49.1 From 1b1275b2f4ae9958d579787c2a65a14b604eba21 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Mon, 1 Jul 2024 17:01:13 +0300 Subject: [PATCH 016/110] fix(git): Conflict resolve --- .../initialization_cubit.dart | 46 +++++++++++++++++-- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index 8938568..2dabef5 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -2,7 +2,6 @@ import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_state.dart'; import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; -import 'package:pusher_client/pusher_client.dart'; class InitializationCubit extends Cubit { final ChatRepository chatRepository; @@ -12,9 +11,48 @@ class InitializationCubit extends Cubit { runInitialization() async { try { await TokenStorage.haveTokenInStorage(); - - final wsUrl = await chatRepository.getWebsocket(); - + // 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(); + // final myPrivateChannel = client.privateChannel( + // 'private-message-events.${wsUrl.userId}', + // authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( + // authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), + // headers: { + // 'Authorization' : 'Bearer ${await TokenStorage.getTokenFromStorage()}', + // }, + // ), + // ); + // myPrivateChannel.subscribe(); + // myPrivateChannel.bindToAll().listen((event) { + // print(event.name); + // }); + emit(const InitializationState.success()); } catch (e) { print(e); emit(InitializationState.error(errorMessage: e.toString())); -- 2.49.1 From 9b97967d882fa83eb9b4bd0f6f78d09139a9a4d5 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 3 Jul 2024 11:33:10 +0300 Subject: [PATCH 017/110] refactor(diary): Diary cubit --- lib/features/diary/models/diary_model.dart | 23 + .../diary/presentation/bloc/diary_cubit.dart | 21 + .../diary/presentation/bloc/diary_state.dart | 19 + .../presentation/pages/diary_screen.dart | 1298 +++++++++++++++++ .../diary/repositories/diary_repository.dart | 16 + .../diary/services/diary_service.dart | 13 + 6 files changed, 1390 insertions(+) create mode 100644 lib/features/diary/models/diary_model.dart create mode 100644 lib/features/diary/presentation/bloc/diary_cubit.dart create mode 100644 lib/features/diary/presentation/bloc/diary_state.dart create mode 100644 lib/features/diary/presentation/pages/diary_screen.dart create mode 100644 lib/features/diary/repositories/diary_repository.dart create mode 100644 lib/features/diary/services/diary_service.dart diff --git a/lib/features/diary/models/diary_model.dart b/lib/features/diary/models/diary_model.dart new file mode 100644 index 0000000..dbf6cee --- /dev/null +++ b/lib/features/diary/models/diary_model.dart @@ -0,0 +1,23 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'diary_model.freezed.dart'; +part 'diary_model.g.dart'; + +@freezed +class DiaryModel with _$DiaryModel { + const factory DiaryModel({ + required int id, + required String state, + String? image, + required String description, + String? author_name, + String? author_avatar_path, + @JsonKey(name: "youtube_url") required String youtubeUrl, + @JsonKey(name: "created_at") required DateTime createdAt, + @JsonKey(name: "updated_at") required DateTime updatedAt, + required String title, + }) = _DiaryModel; + + factory DiaryModel.fromJson(Map json) => + _$DiaryModelFromJson(json); +} diff --git a/lib/features/diary/presentation/bloc/diary_cubit.dart b/lib/features/diary/presentation/bloc/diary_cubit.dart new file mode 100644 index 0000000..3a67666 --- /dev/null +++ b/lib/features/diary/presentation/bloc/diary_cubit.dart @@ -0,0 +1,21 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; +import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; + +class DiaryCubit extends Cubit { + final DiaryRepository blogPostRepository; + + DiaryCubit({required this.blogPostRepository}) + : super(const DiaryState.loading()); + + loadDiary(String blogPostID) async { + emit(const DiaryState.loading()); + try { + final blogPost = await blogPostRepository.getDiary(blogPostID); + emit(DiaryState.loaded(blogPost: blogPost)); + } catch (e) { + emit(DiaryState.error(errorMessage: e.toString())); + print(e); + } + } +} diff --git a/lib/features/diary/presentation/bloc/diary_state.dart b/lib/features/diary/presentation/bloc/diary_state.dart new file mode 100644 index 0000000..e37b05e --- /dev/null +++ b/lib/features/diary/presentation/bloc/diary_state.dart @@ -0,0 +1,19 @@ +import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'diary_state.freezed.dart'; + +@freezed +abstract class DiaryState with _$DiaryState { + const factory DiaryState() = _DiaryState; + + const factory DiaryState.loading() = DiaryStateLoading; + + const factory DiaryState.loaded({ + required DiaryModel blogPost, + }) = DiaryStateLoaded; + + const factory DiaryState.error({ + required String errorMessage, + }) = DiaryStateError; +} diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart new file mode 100644 index 0000000..d780616 --- /dev/null +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -0,0 +1,1298 @@ +// ignore_for_file: unused_local_variable + +import 'bloc/diary_edit_bloc.dart'; +import 'models/diary_edit_model.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'; + +// ignore: must_be_immutable +class DiaryEditScreen extends StatelessWidget { + DiaryEditScreen({Key? key}) : super(key: key); + + static Widget builder(BuildContext context) { + return BlocProvider( + create: (context) => + DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel())) + ..add(DiaryEditInitialEvent()), + child: DiaryEditScreen(), + ); + } + + Widget build(BuildContext context) { + return BlocBuilder( + builder: (context, state) { + if (state is DiaryEditInitialState) { + // Это начальное состояние, данные ещё не загружены. + return Container( + color: Colors.white, + ); + } else if (state is DiaryEditLoadedState) { + // Данные загружены, можно строить экран. + return _buildDiaryEditScreen(context, state); + } else if (state is DiaryEditErrorState) { + // Произошла ошибка при загрузке данных. + return Center(child: Text(state.errorMessage)); + } else { + // Другие состояния, если они есть. + return Container(); // Пустой контейнер для необработанных состояний. + } + }, + ); + } + + Widget _buildDiaryEditScreen( + BuildContext context, DiaryEditLoadedState state) { + return RefreshIndicator( + onRefresh: refreshPage(context), + child: Stack( + alignment: Alignment.bottomCenter, + children: [ + FormBuilder( + child: Scaffold( + appBar: AppBar( + toolbarHeight: 0, + automaticallyImplyLeading: false, + ), + backgroundColor: Color.fromARGB(255, 240, 242, 245), + resizeToAvoidBottomInset: true, + body: SizedBox( + width: double.maxFinite, + child: Column( + children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.only(bottom: 5.v), + child: Column( + children: [ + _buildHeaderRow(context, state), + SizedBox(height: 30.v), + _buildWakupRetire(context, state), + SizedBox(height: 30.v), + _buildMeal(context, state), + SizedBox(height: 20.v), + _buildMood(context, state), + SizedBox(height: 30.v), + _buildNutritionChart(context, state), + SizedBox(height: 30.v), + _buildComment(context, state), + ], + ), + ), + ), + ), + ], + ), + ), + ), + ), + _buildEndDay(context), + ], + ), + ); + } + + _buildEndDay(BuildContext context) { + return CustomOutlinedButton( + text: "Закончить день", + margin: EdgeInsets.only( + left: 16.h, + right: 16.h, + bottom: 16.v, + ), + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + decoration: BoxDecoration( + color: Colors.transparent, + ), + onPressed: onFinishDayPressed(context), + // Установите прозрачный фон + ); + } + + refreshPage(BuildContext context) { + return () async { + context.read().add(RefreshEvent()); + }; + } + + /// Section Widget + _buildHeaderRow(BuildContext context, DiaryEditLoadedState state) { + final day = state.diaryId; + return Container( + margin: EdgeInsets.symmetric(horizontal: 16.h, vertical: 16.h), + padding: EdgeInsets.symmetric( + horizontal: 24.h, + vertical: 12.v, + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.all(Radius.circular(12)), + boxShadow: [ + BoxShadow( + color: Colors.grey.withOpacity(0.5), + spreadRadius: 2, + blurRadius: 5, + offset: Offset(0, 3), + ), + ], + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Padding( + padding: EdgeInsets.only(top: 1.v), + child: Column( + children: [ + Align( + alignment: Alignment.centerRight, + child: Text( + "$day день", + style: CustomTextStyles.titleMediumBlack, + ), + ), + SizedBox(height: 2.v), + Text( + state.diaryDate.toString(), + style: CustomTextStyles.bodyMediumBluegray800, + ), + ], + ), + ), + ], + ), + ); + } + + /// Section Widget + _buildAddProduct(BuildContext context, DiaryEditLoadedState state) { + return CustomOutlinedButton( + text: "Добавить продукт", + margin: EdgeInsets.symmetric(horizontal: 10.h), + buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + onPressed: addProduct(context), + ); + } + + addProduct(BuildContext context) { + return () { + context.read().add(AddPortionEvent()); + }; + } + + /// Section Widget + _buildAddPhoto(BuildContext context, DiaryEditLoadedState state) { + bool isLoading = state.isLoading; + return GestureDetector( + onTap: addImage(context, isLoading), + child: Stack( + children: [ + if (!isLoading) + Container( + margin: EdgeInsets.symmetric(horizontal: 10.h), + padding: EdgeInsets.symmetric( + horizontal: 40.h, + vertical: 80.v, + ), + decoration: AppDecoration.fillGray.copyWith( + borderRadius: BorderRadiusStyle.roundedBorder5, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + children: [ + // Показывайте прелоадер, если загрузка активна + + Padding( + padding: EdgeInsets.only( + left: 7.h, + top: 5.v, + ), + child: Text( + "Добавить фото", + selectionColor: appTheme.blueA400, + ), + ), + Spacer(), + Icon( + Icons.photo_library, + color: appTheme.blueGray300, + ), + ], + ), + ), + if (isLoading) + Container( + margin: EdgeInsets.symmetric(horizontal: 10.h), + padding: EdgeInsets.symmetric( + horizontal: 40.h, + vertical: 80.v, + ), + decoration: AppDecoration.fillGray.copyWith( + borderRadius: BorderRadiusStyle.roundedBorder5, + ), + child: Center( + child: CircularProgressIndicator( + color: appTheme + .blueGray300), // Замените на свой прелоадер при необходимости + ), + ), + ], + ), + ); + } + + addImage(BuildContext context, bool isLoading) { + if (!isLoading) { + return () async { + final picker = ImagePicker(); + List? images = await picker.pickMultiImage(); + if (images.isNotEmpty) { + for (var image in images) { + context.read().add(UploadImages(image)); + } + } + }; + } + } + + _buildMeal(BuildContext context, DiaryEditLoadedState state) { + final digitsOnly = FilteringTextInputFormatter.digitsOnly; + List _options = + state.autocompleteList!.map((dynamic item) => item as String).toList(); + //print(_options); + FocusNode focusNodeName = FocusNode(); + return Container( + margin: EdgeInsets.symmetric(horizontal: 16.h), + padding: EdgeInsets.symmetric( + horizontal: 24.h, + vertical: 12.v, + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.all(Radius.circular(12)), + boxShadow: [ + BoxShadow( + color: Colors.grey.withOpacity(0.5), + spreadRadius: 2, + blurRadius: 5, + offset: Offset(0, 3), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: EdgeInsets.symmetric(horizontal: 10.h), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + "Время приема пищи", + style: CustomTextStyles.bodyMediumBlack900, + ), + Expanded( + // Adding Expanded widget + child: Padding( + padding: EdgeInsets.symmetric(horizontal: 10.h), + child: ConstrainedBox( + constraints: BoxConstraints( + maxWidth: MediaQuery.of(context).size.width - 260, + ), + child: GestureDetector( + onTap: () => _selectMealTime(context, state), + child: AbsorbPointer( + child: CustomTextFormField( + hintText: state.mealTimeController + ?.format(context) + .toString(), + autofocus: false, + ), + ), + ), + ), + ), + ), + ], + ), + ), + SizedBox(height: 20.v), + Padding( + padding: EdgeInsets.symmetric(horizontal: 10.h), + child: BlocSelector( + selector: (state) => state.diaryEditModelObj, + builder: (context, diaryEditModelObj) { + return CustomDropDown( + hintText: "Прием пищи", + items: diaryEditModelObj?.mealList, + contentPadding: EdgeInsets.symmetric( + horizontal: 10.h, + vertical: 9.v, + ), + defaultValue: diaryEditModelObj?.mealList[0], + onChanged: changeMeal(context, state), + ); + }, + ), + ), + SizedBox(height: 20.v), + Padding( + padding: EdgeInsets.symmetric(horizontal: 10.h), + child: RawAutocomplete( + optionsBuilder: buildOptions(_options), + fieldViewBuilder: ( + BuildContext context, + TextEditingController productEditingController, + FocusNode focusNodeName, + VoidCallback onFieldSubmitted, + ) { + if (state.isAdded) { + print("Clear"); + } + return CustomTextFormField( + hintText: "Введите название продукта", + controller: productEditingController, + focusNode: focusNodeName, + onChanged: getAutocomplete(context, focusNodeName), + ); + }, + 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: selectProduct(onSelected, option, state), + child: ListTile( + title: Text(option), + ), + ); + }, + ), + ), + ), + ); + }, + ), + ), + SizedBox(height: 20.v), + if (state.moderationExpanded) + Padding( + padding: EdgeInsets.symmetric(horizontal: 10.h), + child: GestureDetector( + onTap: () => openCaloriesDialog(context, state), + child: Text("Отправить на модерацию"), + ), + ), + SizedBox(height: 20.v), + Padding( + padding: EdgeInsets.symmetric(horizontal: 10.h), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + CustomTextFormField( + width: 150.h, + hintText: "Кол-во", + textInputAction: TextInputAction.done, + // focusNode: focusNodeQuantity, + controller: state.productQuantityController, + keyboardType: TextInputType.number, + inputFormatters: [digitsOnly], + ), + Padding( + padding: EdgeInsets.only(left: 30.h), + child: BlocSelector( + selector: (state) => state.diaryEditModelObj, + builder: (context, diaryEditModelObj) { + return CustomDropDown( + items: diaryEditModelObj?.portionList, + defaultValue: diaryEditModelObj?.portionList?[0], + onChanged: changePortion(context, state), + ); + }, + ), + ), + ], + ), + ), + ), + SizedBox(height: 30.v), + _buildAddProduct(context, state), + SizedBox(height: 30.v), + ...state.portions! + .map((portion) => _buildProduct(context, portion)) + .toList(), + SizedBox(height: 30.v), + /*...state.photos != null + ? state.photos!.isEmpty + ? [Text('Фото пока нет')] + : state.photos! + .map((photo) => _buildPhoto(context, photo)) + .toList() + : [Text('Фото нет')],*/ + _buildCarousel(context, state), + SizedBox(height: 20.v), + _buildAddPhoto(context, state), + SizedBox(height: 30.v), + Text( + "Ваша сытость после приёма пищи", + style: CustomTextStyles.bodyMediumBlack900, + ), + SizedBox(height: 15.v), + BlocBuilder( + builder: (context, state) { + if (state is DiaryEditLoadedState) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("😭"), + ScaleElement( + color: Colors.red, + isSelected: state.selectedSatiety == 0, + onTap: changeSatiety(context, 0), + ), + ScaleElement( + color: Colors.orange, + isSelected: state.selectedSatiety == 1, + onTap: changeSatiety(context, 1), + ), + ScaleElement( + color: Colors.yellow, + isSelected: state.selectedSatiety == 2, + onTap: changeSatiety(context, 2), + ), + ScaleElement( + color: Colors.lime, + isSelected: state.selectedSatiety == 3, + onTap: changeSatiety(context, 3), + ), + ScaleElement( + color: Colors.lightGreen, + isSelected: state.selectedSatiety == 4, + onTap: changeSatiety(context, 4), + ), + ScaleElement( + color: Colors.green, + isSelected: state.selectedSatiety == 5, + onTap: changeSatiety(context, 5), + ), + Text("😊"), + // Остальные элементы шкалы + ], + ); + } else { + return Container(); // Возвращаем пустой контейнер, если состояние не является DiaryEditLoadedState + } + }, + ), + ], + ), + ); + } + + openCaloriesDialog(BuildContext context, DiaryEditLoadedState state) { + showDialog( + context: context, + builder: (BuildContext dialogContext) { + return AlertDialog( + title: Text('Введите информацию о продукте'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + CustomTextFormField( + hintText: "Название", + controller: state.productNameController, + ), + SizedBox(height: 10.v), + CustomTextFormField( + hintText: "Энергетическая ценность на 100", + keyboardType: TextInputType.number, + controller: state.caloriesController, + ), + SizedBox(height: 10.v), + CustomTextFormField( + hintText: "Белки на 100г", + keyboardType: TextInputType.number, + controller: state.proteinsController, + ), + SizedBox(height: 10.v), + CustomTextFormField( + hintText: "Жиры на 100г", + keyboardType: TextInputType.number, + controller: state.fatsController, + ), + SizedBox(height: 10.v), + CustomTextFormField( + hintText: "Углеводы на 100г", + keyboardType: TextInputType.number, + controller: state.carbsController, + ), + ], + ), + actions: [ + TextButton( + onPressed: popDialog(context), + child: Text('Отмена'), + ), + TextButton( + onPressed: triggerModeration( + context, + state.productNameController!.text, + state.caloriesController!.text, + state.proteinsController!.text, + state.fatsController!.text, + state.carbsController!.text, + dialogContext, + ), + child: Text('Отправить'), + ), + ], + ); + }, + ); + } + + triggerModeration( + BuildContext context, + String name, + String energyOn100gr, + String proteinsOn100gr, + String fatsOn100gr, + String carbohydratesOn100gr, + BuildContext dialogContext, + ) { + return () { + // Call function to send moderation with the entered values + context.read().add( + SendModeration( + name: name, + energyOn100gr: energyOn100gr, + proteinsOn100gr: proteinsOn100gr, + fatsOn100gr: fatsOn100gr, + carbohydratesOn100gr: carbohydratesOn100gr, + ), + ); + Navigator.of(dialogContext).pop(); // Dismiss the dialog + }; + } + + popDialog(BuildContext dialogContext) { + return () { + Navigator.of(dialogContext) + .pop(); // Dismiss the dialog on Cancel button press + }; + } + + changeSatiety(BuildContext context, int satiety) { + return () { + context.read().add(ChangeSatiety(satiety)); + }; + } + + selectProduct(AutocompleteOnSelected onSelected, String option, + DiaryEditLoadedState state) { + state.productNameController?.text = option; + return () { + onSelected(option); + }; + } + + getAutocomplete(BuildContext context, FocusNode focusNode) { + return (value) { + /*print(state.autocompleteList + ?.map((dynamic item) => item as String) + .toList());*/ + if (value.length > 2) { + context.read().add(ProductInput(value)); + } + }; + } + + buildOptions(List _options) { + return (TextEditingValue textEditingValue) { + return _options.where((String option) { + return true; + }); + }; + } + + changeMeal(BuildContext context, DiaryEditLoadedState state) { + return (value) { + context + .read() + .add(ChangeMeal(meals: state.meals, value: value)); + }; + } + + changePortion(BuildContext context, DiaryEditLoadedState state) { + return (value) { + context.read().add(ChangePortion(value: value)); + }; + } + + _buildCarousel(BuildContext context, DiaryEditLoadedState state) { + if (state.photos!.isEmpty) { + return Text("Фото нет"); + } else { + return CarouselSlider( + options: CarouselOptions(height: 340.0), + items: state.photos!.map((photo) { + return _buildPhoto( + context, photo); // Assuming photos are stored as strings + }).toList(), + ); + } + } + + _buildProduct(BuildContext context, Map portion) { + return Container( + margin: EdgeInsets.symmetric(horizontal: 10.h), + padding: EdgeInsets.symmetric( + horizontal: 8.h, + vertical: 6.v, + ), + decoration: AppDecoration.fillGray.copyWith( + borderRadius: BorderRadiusStyle.roundedBorder5, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: EdgeInsets.only( + left: 7.h, + top: 5.v, + ), + child: Text( + portion['product_name'].length > 8 + ? portion['product_name'].substring(0, 8) + : portion['product_name'], + style: CustomTextStyles.titleMedium16, + ), + ), + Padding( + padding: EdgeInsets.only( + left: 20.h, + top: 3.v, + bottom: 3.v, + ), + child: Text( + portion['quantity'].toString() + + ' ' + + portion['portion'].toString().tr, + ), + ), + Spacer(), + GestureDetector( + onTap: removePortion(context, portion), + child: Padding( + padding: const EdgeInsets.only(right: 10), + child: Icon( + Icons.close, + color: appTheme.blueGray300, + ), + ), + ), + ], + ), + ); + } + + _buildPhoto(BuildContext context, Map photo) { + return Stack( + children: [ + Container( + margin: EdgeInsets.symmetric(horizontal: 10.h, vertical: 10.h), + decoration: AppDecoration.fillGray.copyWith( + borderRadius: BorderRadiusStyle.roundedBorder5, + ), + child: Image.network( + dotenv.env['STORAGE_URL']! + photo['path'], + ), + ), + Positioned( + top: 5, + right: 5, + child: GestureDetector( + onTap: removePhoto(context, photo), + child: Container( + padding: EdgeInsets.all(5), + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.transparent, + ), + child: Icon( + Icons.close, + color: appTheme.blueGray300, + ), + ), + ), + ), + ], + ); + } + + removePortion(BuildContext context, Map portion) { + return () { + context.read().add(RemovePortionEvent(portion['id'])); + }; + } + + removePhoto(BuildContext context, Map photo) { + return () { + context + .read() + .add(RemoveImageEvent(photo['id'].toString(), photo['path'])); + }; + } + + _buildNutritionChart(BuildContext context, DiaryEditLoadedState state) { + final List recommendedValues = state + .recommendedChartValues; // Рекомендуемые значения: калории, жиры, белки, углеводы + final List consumedValues = state.consumedChartValues; // + return Container( + margin: EdgeInsets.symmetric(horizontal: 16.h), + padding: EdgeInsets.symmetric( + horizontal: 10.h, + vertical: 16.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: Column( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SizedBox(height: 3.v), + Text( + "Ваш КБЖУ", + style: theme.textTheme.titleMedium, + ), + SizedBox(height: 8.v), + Text( + "От дневной суточной нормы", + style: CustomTextStyles.bodyMediumBluegray800, + ), + SizedBox(height: 19.v), + Align( + alignment: Alignment.centerRight, + child: Padding( + padding: EdgeInsets.only( + left: 30.h, + right: 12.h, + ), + child: AspectRatio( + aspectRatio: 1.5, + child: BarChart( + BarChartData( + alignment: BarChartAlignment.spaceAround, + barTouchData: BarTouchData(enabled: false), + titlesData: FlTitlesData( + show: true, + bottomTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + //getTitlesWidget: (value, meta) => newMethod(value), + ), + ), + ), + borderData: FlBorderData(show: false), + barGroups: [ + BarChartGroupData( + x: 0, + barRods: [ + BarChartRodData( + toY: consumedValues[0] / recommendedValues[0] * 100, + color: checkConsumedValues( + [recommendedValues[0]], [consumedValues[1]]) + ? Colors.red + : Colors.blue, + ), + ], + ), + BarChartGroupData( + x: 1, + barRods: [ + BarChartRodData( + toY: consumedValues[1] / recommendedValues[1] * 100, + color: checkConsumedValues( + [recommendedValues[1]], [consumedValues[1]]) + ? Colors.red + : Colors.blue, + ), + ], + ), + BarChartGroupData( + x: 2, + barRods: [ + BarChartRodData( + toY: consumedValues[2] / recommendedValues[2] * 100, + color: checkConsumedValues( + [recommendedValues[2]], [consumedValues[2]]) + ? Colors.red + : Colors.blue, + ), + ], + ), + BarChartGroupData( + x: 3, + barRods: [ + BarChartRodData( + toY: consumedValues[3] / recommendedValues[3] * 100, + color: checkConsumedValues( + [recommendedValues[3]], [consumedValues[3]]) + ? Colors.red + : Colors.blue, + ), + ], + ), + ], + ), + ), + ), + ), + ), + SizedBox(height: 8.v), + SizedBox(height: 2.v), + Padding( + padding: EdgeInsets.only( + left: 10.h, + right: 2.h, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "Калорий", + style: theme.textTheme.bodySmall, + ), + Padding( + padding: EdgeInsets.only( + left: 25.h, + bottom: 11.v, + ), + child: Text( + "Белков", + style: theme.textTheme.bodySmall, + ), + ), + Padding( + padding: EdgeInsets.only( + left: 19.h, + bottom: 11.v, + ), + child: Text( + "Жиров", + style: theme.textTheme.bodySmall, + ), + ), + Padding( + padding: EdgeInsets.only( + left: 14.h, + bottom: 11.v, + ), + child: Text( + "Углеводов", + style: theme.textTheme.bodySmall, + ), + ), + ], + ), + ), + SizedBox(height: 2.v), + Padding( + padding: EdgeInsets.only( + left: 10.h, + right: 2.h, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "${consumedValues[0].toInt()} из ${recommendedValues[0].toInt()}", + style: theme.textTheme.bodySmall, + ), + Padding( + padding: EdgeInsets.only( + left: 25.h, + bottom: 11.v, + ), + child: Text( + "${consumedValues[1].toInt()} из ${recommendedValues[1].toInt()}", + style: theme.textTheme.bodySmall, + ), + ), + Padding( + padding: EdgeInsets.only( + left: 19.h, + bottom: 11.v, + ), + child: Text( + "${consumedValues[2].toInt()} из ${recommendedValues[2].toInt()}", + style: theme.textTheme.bodySmall, + ), + ), + Padding( + padding: EdgeInsets.only( + left: 14.h, + bottom: 11.v, + ), + child: Text( + "${consumedValues[3].toInt()} из ${recommendedValues[3].toInt()}", + style: theme.textTheme.bodySmall, + ), + ), + ], + ), + ), + SizedBox(height: 19.v), + if (checkConsumedValues(recommendedValues, consumedValues)) + Text( + "*Превышенная суточная норма", + style: theme.textTheme.labelLarge, + ), + ], + ), + ); + } + + /// Section Widget + _buildComment(BuildContext context, DiaryEditLoadedState state) { + return Container( + margin: EdgeInsets.symmetric(horizontal: 16.h), + padding: EdgeInsets.symmetric( + horizontal: 24.h, + vertical: 12.v, + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.all(Radius.circular(12)), + boxShadow: [ + BoxShadow( + color: Colors.grey.withOpacity(0.5), + spreadRadius: 2, + blurRadius: 5, + offset: Offset(0, 3), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + "Дополнительная информация для консультанта", + style: theme.textTheme.titleMedium, + textAlign: TextAlign.center, + ), + SizedBox(height: 20.v), + Container( + width: 320.h, + child: CustomTextFormField( + autofocus: false, + hintText: "Введите информацию для консультанта", + maxLines: 7, + borderDecoration: InputBorder.none, + controller: state.commentController, + ), + ), + ], + ), + ); + } + + _buildWakupRetire(BuildContext context, DiaryEditLoadedState state) { + return Container( + margin: EdgeInsets.symmetric(horizontal: 16.h), + padding: EdgeInsets.symmetric( + horizontal: 24.h, + vertical: 12.v, + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.all(Radius.circular(12)), + boxShadow: [ + BoxShadow( + color: Colors.grey.withOpacity(0.5), + spreadRadius: 2, + blurRadius: 5, + offset: Offset(0, 3), + ), + ], + ), + child: Column( + children: [ + GestureDetector( + onTap: toggleWakeup(context), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + r"Подъем \ отход ко сну", + style: CustomTextStyles.bodyMediumBlack900, + ), + Icon(state.wakeupExpanded + ? Icons.arrow_drop_up + : Icons.arrow_drop_down), + ], + ), + ), + if (state.wakeupExpanded) + Padding( + padding: const EdgeInsets.only(left: 16.0), + child: Column( + children: [ + SizedBox(height: 20.v), + GestureDetector( + onTap: () => _selectWakeupTime(context, state), + child: AbsorbPointer( + child: CustomTextFormField( + hintText: + state.wakeupController?.format(context).toString(), + prefix: Icon(Icons.sunny), + autofocus: false, + ), + ), + ), + SizedBox(height: 20.v), + GestureDetector( + onTap: () => _selectRetireTime(context, state), + child: AbsorbPointer( + child: CustomTextFormField( + hintText: + state.retireController?.format(context).toString(), + prefix: Icon(Icons.bed), + autofocus: false, + ), + ), + ), + SizedBox(height: 20.v), + ], + ), + ), + ], + ), + ); + } + + toggleWakeup(BuildContext context) { + return () { + BlocProvider.of(context).add(ToggleWakeupExpandedEvent()); + }; + } + + /// Section Widget + + Function() onFinishDayPressed(BuildContext context) { + return () { + showDialog( + context: context, + builder: (BuildContext dialogContext) { + return AlertDialog( + title: Text("Подтвердите действие"), + content: Text("Вы уверены, что хотите завершить день?"), + actions: [ + TextButton( + child: Text("Отмена"), + onPressed: closeDialog(dialogContext), + ), + TextButton( + child: Text("Подтвердить"), + onPressed: sendFinishDayData(dialogContext, context), + ), + ], + ); + }, + ); + }; + } + + Function() sendFinishDayData( + BuildContext dialogContext, BuildContext context) { + return () { + closeDialog(dialogContext); + context.read().add(FinishDay()); + }; + } + + Function() closeDialog(BuildContext dialogContext) { + return () { + Navigator.of(dialogContext).pop(); + }; + } + + _buildMood(BuildContext context, DiaryEditLoadedState state) { + return Container( + margin: EdgeInsets.symmetric(horizontal: 16.h), + padding: EdgeInsets.symmetric( + horizontal: 24.h, + vertical: 12.v, + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.all(Radius.circular(12)), + boxShadow: [ + BoxShadow( + color: Colors.grey.withOpacity(0.5), + spreadRadius: 2, + blurRadius: 5, + offset: Offset(0, 3), + ), + ], + ), + child: Column( + children: [ + GestureDetector( + onTap: toggleMood(context), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + "Ваше настроение после приема пищи", + style: CustomTextStyles.bodyMediumBlack900, + ), + Icon(state.moodExpanded + ? Icons.arrow_drop_up + : Icons.arrow_drop_down), + ], + ), + ), + if (state.moodExpanded) + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("😭"), + ScaleElement( + color: Colors.red, + isSelected: state.selectedMood == 0, + onTap: changeMood(context, 0), + ), + ScaleElement( + color: Colors.orange, + isSelected: state.selectedMood == 1, + onTap: changeMood(context, 1), + ), + ScaleElement( + color: Colors.yellow, + isSelected: state.selectedMood == 2, + onTap: changeMood(context, 2), + ), + ScaleElement( + color: Colors.lime, + isSelected: state.selectedMood == 3, + onTap: changeMood(context, 3), + ), + ScaleElement( + color: Colors.lightGreen, + isSelected: state.selectedMood == 4, + onTap: changeMood(context, 4), + ), + ScaleElement( + color: Colors.green, + isSelected: state.selectedMood == 5, + onTap: changeMood(context, 5), + ), + Text("😊"), + // Остальные элементы шкалы + ], + ), + ], + ), + ); + } + + changeMood(BuildContext context, int satiety) { + return () { + context.read().add(ChangeMood(satiety)); + }; + } + + toggleMood(BuildContext context) { + return () { + BlocProvider.of(context).add(ToggleMoodExpandedEvent()); + }; + } + + Future _selectWakeupTime( + BuildContext context, DiaryEditLoadedState state) async { + final TimeOfDay? pickedTime = await showTimePicker( + context: context, + initialTime: state.wakeupController ?? TimeOfDay.now(), + ); + if (pickedTime != null && pickedTime != state.wakeupController) { + state.wakeupController = pickedTime; + context.read().add(WakeupEvent(pickedTime)); + } + } + + Future _selectRetireTime( + BuildContext context, DiaryEditLoadedState state) async { + final TimeOfDay? pickedTime = await showTimePicker( + context: context, + initialTime: state.retireController ?? TimeOfDay.now(), + ); + if (pickedTime != null && pickedTime != state.retireController) { + state.retireController = pickedTime; + context.read().add(RetireEvent(pickedTime)); + } + } + + Future _selectMealTime( + BuildContext context, DiaryEditLoadedState state) async { + final TimeOfDay? pickedTime = await showTimePicker( + context: context, + initialTime: state.mealTimeController ?? TimeOfDay.now(), + ); + if (pickedTime != null && pickedTime != state.mealTimeController) { + state.mealTimeController = pickedTime; + context.read().add(ChangeMealTime(pickedTime)); + } + } +} + +bool checkConsumedValues( + List recommendedValues, List consumedValues) { + for (int i = 0; i < recommendedValues.length; i++) { + if (consumedValues[i] > recommendedValues[i]) { + // Если хотя бы одно потребленное значение превышает рекомендованное + return true; // Возвращаем false + } + } + // Если ни одно потребленное значение не превышает рекомендованное с соответствующим индексом + return false; // Возвращаем true +} diff --git a/lib/features/diary/repositories/diary_repository.dart b/lib/features/diary/repositories/diary_repository.dart new file mode 100644 index 0000000..2f5dc21 --- /dev/null +++ b/lib/features/diary/repositories/diary_repository.dart @@ -0,0 +1,16 @@ +import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:eatvio_app/features/diary/services/diary_service.dart'; + +class DiaryRepository { + final DiaryService blogPostService; + + DiaryRepository({required this.blogPostService}); + + Future getDiary(String blogPostID) async { + try { + return await blogPostService.getDiary(blogPostID); + } catch (e) { + rethrow; + } + } +} diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart new file mode 100644 index 0000000..181005e --- /dev/null +++ b/lib/features/diary/services/diary_service.dart @@ -0,0 +1,13 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:retrofit/retrofit.dart'; + +part 'diary_service.g.dart'; + +@RestApi() +abstract class DiaryService { + factory DiaryService(Dio dio, {String baseUrl}) = _DiaryService; + + @GET('/feed/show/{id}') + Future getDiary(@Path() String id); +} -- 2.49.1 From 5cda945d1fff7733e99072482f23bc4c8c8fadbc Mon Sep 17 00:00:00 2001 From: Anatoliy Poloz Date: Wed, 3 Jul 2024 11:52:40 +0300 Subject: [PATCH 018/110] testing hooks added --- Makefile | 8 ++++++++ package-lock.json | 26 ++++++++++++++++++++++++++ package.json | 22 ++++++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 Makefile create mode 100644 package-lock.json create mode 100644 package.json diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..3b10f12 --- /dev/null +++ b/Makefile @@ -0,0 +1,8 @@ + +run-tests: + flutter test + +run-analyse: + flutter analyze + +run-checks: run-analyse run-tests diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..67e7935 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,26 @@ +{ + "name": "eatvio_app", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "eatvio_app", + "version": "1.0.0", + "license": "ISC", + "devDependencies": { + "simple-git-hooks": "^2.11.1" + } + }, + "node_modules/simple-git-hooks": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/simple-git-hooks/-/simple-git-hooks-2.11.1.tgz", + "integrity": "sha512-tgqwPUMDcNDhuf1Xf6KTUsyeqGdgKMhzaH4PAZZuzguOgTl5uuyeYe/8mWgAr6IBxB5V06uqEf6Dy37gIWDtDg==", + "dev": true, + "hasInstallScript": true, + "bin": { + "simple-git-hooks": "cli.js" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..8c0eba5 --- /dev/null +++ b/package.json @@ -0,0 +1,22 @@ +{ + "name": "eatvio_app", + "version": "1.0.0", + "description": "- Flutter (Channel stable, 3.19.0, on Ubuntu 22.04.3 LTS 6.2.0-39-generic, locale en_US.UTF-8) - Android Studio (version 2023.1) - VS Code (version 1.85.0) - Android SDK (version 34.0.0) - устанавливается из Android Studio (Tools->SDK Manager->Android Command Line Tools) - Эмулятор (2 available)", + "main": "index.js", + "directories": { + "lib": "lib", + "test": "test" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "devDependencies": { + "simple-git-hooks": "^2.11.1" + }, + "simple-git-hooks": { + "pre-push": "make run-checks", + "preserveUnused": true + } +} -- 2.49.1 From 6a03e06f041e00c01c7b850b05cadb72a92c1ffe Mon Sep 17 00:00:00 2001 From: alex Date: Wed, 3 Jul 2024 11:59:32 +0300 Subject: [PATCH 019/110] feat(hooks): prepush hooks --- .gitignore | 3 +- Makefile | 7 ++ lib/app_router.dart | 101 +++++------------- .../initialization_cubit.dart | 93 ++++++++-------- .../initialization_state.dart | 9 +- .../initialization_state.freezed.dart | 79 ++++++++++---- .../blog_post_create_credentials_model.dart | 3 +- .../chat_select_screen.dart | 1 - .../widgets/chat_entry_widget.dart | 2 +- lib/locator_service.dart | 17 ++- lib/main.dart | 3 +- node_modules/.package-lock.json | 18 ++++ node_modules/simple-git-hooks/package.json | 18 ++++ package-lock.json | 26 +++++ package.json | 22 ++++ pubspec.yaml | 18 ++-- 16 files changed, 249 insertions(+), 171 deletions(-) create mode 100644 Makefile create mode 100644 node_modules/.package-lock.json create mode 100644 node_modules/simple-git-hooks/package.json create mode 100644 package-lock.json create mode 100644 package.json diff --git a/.gitignore b/.gitignore index e167a73..9d9b1ce 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,5 @@ /.flutter-plugins /.flutter-plugins-dependencies /.packages -/.env \ No newline at end of file +/.env +/node_modules/ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..cd6bc42 --- /dev/null +++ b/Makefile @@ -0,0 +1,7 @@ +run-tests: + flutter test + +run-analyse: + flutter analyze + +run-checks: run-analyse run-tests \ No newline at end of file diff --git a/lib/app_router.dart b/lib/app_router.dart index dada825..30cda0b 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -45,8 +45,9 @@ class AppRouter { path: '/auth-screen', name: 'authScreen', redirect: (context, state) async { - if (await TokenStorage.haveTokenInStorage()) + if (await TokenStorage.haveTokenInStorage()) { return '/my-profile-screen'; + } return null; }, builder: (context, state) => AuthScreen.builder(context), @@ -59,120 +60,72 @@ class AppRouter { GoRoute( path: 'credentials-screen', name: 'credentialsScreen', - builder: (context, state) => - CredentialsScreen.builder(context, state.extra), + builder: (context, state) => CredentialsScreen.builder(context, state.extra), routes: [ GoRoute( path: 'name-screen', name: 'nameScreen', - builder: (context, state) => - NameScreen.builder(context, state.extra), + builder: (context, state) => NameScreen.builder(context, state.extra), routes: [ GoRoute( path: 'gender-screen', name: 'genderScreen', - builder: (context, state) => - GenderScreen.builder(context, state.extra), + 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), + 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), + builder: (context, state) => CityOfLivingScreen.builder(context, state.extra), routes: [ GoRoute( path: 'body-circumferences-screen', name: 'bodyCircumferencesScreen', - builder: (context, state) => - BodyCircumferencesScreen.builder( - context, state.extra), + builder: (context, state) => BodyCircumferencesScreen.builder(context, state.extra), routes: [ GoRoute( path: 'weight-screen', name: 'weightScreen', - builder: (context, state) => - WeightScreen.builder( - context, state.extra), + builder: (context, state) => WeightScreen.builder(context, state.extra), routes: [ GoRoute( path: 'height-screen', name: 'heightScreen', - builder: (context, state) => - HeightScreen.builder( - context, state.extra), + builder: (context, state) => HeightScreen.builder(context, state.extra), routes: [ GoRoute( path: 'blood-pressure-screen', name: 'bloodPressureScreen', - builder: (context, state) => - BloodPressureScreen.builder( - context, state.extra), + builder: (context, state) => BloodPressureScreen.builder(context, state.extra), routes: [ GoRoute( - path: - 'favorite-sports-screen', - name: - 'favoriteSportsScreen', - builder: (context, state) => - FavoriteSportsScreen - .builder(context, - state.extra), + 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), + builder: (context, state) => AllergiesScreen.builder(context, state.extra), routes: [ GoRoute( - name: - 'medicineIntakeScreen', - path: - 'medicine-intake-screen', - builder: (context, - state) => - MedicineIntakeScreen - .builder( - context, - state - .extra), + 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), + 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: 'additional-information-screen', + name: 'additionalInformationScreen', + builder: (context, state) => AdditionalInformationScreen.builder(context, state.extra), ), ], ), @@ -220,14 +173,12 @@ class AppRouter { GoRoute( path: 'blog-post-create-screen', name: 'blogPostCreateScreen', - builder: (context, state) => - BlogPostCreateScreen.builder(context), + builder: (context, state) => BlogPostCreateScreen.builder(context), ), GoRoute( path: 'blog-post-screen', name: 'blogPostScreen', - builder: (context, state) => - BlogPostScreen(blogPostID: state.extra as String), + builder: (context, state) => BlogPostScreen(blogPostID: state.extra as String), routes: [ GoRoute( path: 'blog-post-edit-screen', diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index 2dabef5..83246b1 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -1,3 +1,4 @@ +import 'package:dart_pusher_channels/dart_pusher_channels.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_state.dart'; import 'package:eatvio_app/core/token_storage.dart'; @@ -8,54 +9,58 @@ class InitializationCubit extends Cubit { InitializationCubit({required this.chatRepository}) : super(const InitializationState.loading()); + // final myPrivateChannel = client.privateChannel( + // 'private-new-chat-messages.${wsUrl.userId}', + // authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( + // authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), + // headers: { + // 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', + // }, + // ), + // ); + // myPrivateChannel.subscribe(); + // myPrivateChannel.bindToAll().listen((event) { + // print(event.name); + // }); + 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(); - // final myPrivateChannel = client.privateChannel( - // 'private-message-events.${wsUrl.userId}', - // authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( - // authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), - // headers: { - // 'Authorization' : 'Bearer ${await TokenStorage.getTokenFromStorage()}', - // }, - // ), - // ); - // myPrivateChannel.subscribe(); - // myPrivateChannel.bindToAll().listen((event) { - // print(event.name); - // }); - emit(const InitializationState.success()); + 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(); + emit(InitializationState.success( + client: client, + )); } catch (e) { - print(e); - emit(InitializationState.error(errorMessage: e.toString())); + emit(InitializationState.error( + errorMessage: e.toString(), + )); } } } diff --git a/lib/core/initialization_cubit/initialization_state.dart b/lib/core/initialization_cubit/initialization_state.dart index 98f881c..43318d0 100644 --- a/lib/core/initialization_cubit/initialization_state.dart +++ b/lib/core/initialization_cubit/initialization_state.dart @@ -1,3 +1,4 @@ +import 'package:dart_pusher_channels/dart_pusher_channels.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'initialization_state.freezed.dart'; @@ -8,7 +9,11 @@ abstract class InitializationState with _$InitializationState { const factory InitializationState.loading() = InitializationStateLoading; - const factory InitializationState.success() = InitializationStateSuccess; + const factory InitializationState.success({ + required PusherChannelsClient client, + }) = InitializationStateSuccess; - const factory InitializationState.error({required String errorMessage}) = InitializationStateError; + const factory InitializationState.error({ + required String errorMessage, + }) = InitializationStateError; } diff --git a/lib/core/initialization_cubit/initialization_state.freezed.dart b/lib/core/initialization_cubit/initialization_state.freezed.dart index 136672f..3364e44 100644 --- a/lib/core/initialization_cubit/initialization_state.freezed.dart +++ b/lib/core/initialization_cubit/initialization_state.freezed.dart @@ -20,7 +20,7 @@ mixin _$InitializationState { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function() success, + required TResult Function(PusherChannelsClient client) success, required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; @@ -28,7 +28,7 @@ mixin _$InitializationState { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function()? success, + TResult? Function(PusherChannelsClient client)? success, TResult? Function(String errorMessage)? error, }) => throw _privateConstructorUsedError; @@ -36,7 +36,7 @@ mixin _$InitializationState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function()? success, + TResult Function(PusherChannelsClient client)? success, TResult Function(String errorMessage)? error, required TResult orElse(), }) => @@ -127,7 +127,7 @@ class _$InitializationStateImpl implements _InitializationState { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function() success, + required TResult Function(PusherChannelsClient client) success, required TResult Function(String errorMessage) error, }) { return $default(); @@ -138,7 +138,7 @@ class _$InitializationStateImpl implements _InitializationState { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function()? success, + TResult? Function(PusherChannelsClient client)? success, TResult? Function(String errorMessage)? error, }) { return $default?.call(); @@ -149,7 +149,7 @@ class _$InitializationStateImpl implements _InitializationState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function()? success, + TResult Function(PusherChannelsClient client)? success, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -245,7 +245,7 @@ class _$InitializationStateLoadingImpl implements InitializationStateLoading { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function() success, + required TResult Function(PusherChannelsClient client) success, required TResult Function(String errorMessage) error, }) { return loading(); @@ -256,7 +256,7 @@ class _$InitializationStateLoadingImpl implements InitializationStateLoading { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function()? success, + TResult? Function(PusherChannelsClient client)? success, TResult? Function(String errorMessage)? error, }) { return loading?.call(); @@ -267,7 +267,7 @@ class _$InitializationStateLoadingImpl implements InitializationStateLoading { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function()? success, + TResult Function(PusherChannelsClient client)? success, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -325,6 +325,8 @@ abstract class _$$InitializationStateSuccessImplCopyWith<$Res> { _$InitializationStateSuccessImpl value, $Res Function(_$InitializationStateSuccessImpl) then) = __$$InitializationStateSuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({PusherChannelsClient client}); } /// @nodoc @@ -336,37 +338,61 @@ class __$$InitializationStateSuccessImplCopyWithImpl<$Res> _$InitializationStateSuccessImpl _value, $Res Function(_$InitializationStateSuccessImpl) _then) : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? client = null, + }) { + return _then(_$InitializationStateSuccessImpl( + client: null == client + ? _value.client + : client // ignore: cast_nullable_to_non_nullable + as PusherChannelsClient, + )); + } } /// @nodoc class _$InitializationStateSuccessImpl implements InitializationStateSuccess { - const _$InitializationStateSuccessImpl(); + const _$InitializationStateSuccessImpl({required this.client}); + + @override + final PusherChannelsClient client; @override String toString() { - return 'InitializationState.success()'; + return 'InitializationState.success(client: $client)'; } @override bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && - other is _$InitializationStateSuccessImpl); + other is _$InitializationStateSuccessImpl && + (identical(other.client, client) || other.client == client)); } @override - int get hashCode => runtimeType.hashCode; + int get hashCode => Object.hash(runtimeType, client); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> + get copyWith => __$$InitializationStateSuccessImplCopyWithImpl< + _$InitializationStateSuccessImpl>(this, _$identity); @override @optionalTypeArgs TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function() success, + required TResult Function(PusherChannelsClient client) success, required TResult Function(String errorMessage) error, }) { - return success(); + return success(client); } @override @@ -374,10 +400,10 @@ class _$InitializationStateSuccessImpl implements InitializationStateSuccess { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function()? success, + TResult? Function(PusherChannelsClient client)? success, TResult? Function(String errorMessage)? error, }) { - return success?.call(); + return success?.call(client); } @override @@ -385,12 +411,12 @@ class _$InitializationStateSuccessImpl implements InitializationStateSuccess { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function()? success, + TResult Function(PusherChannelsClient client)? success, TResult Function(String errorMessage)? error, required TResult orElse(), }) { if (success != null) { - return success(); + return success(client); } return orElse(); } @@ -434,7 +460,14 @@ class _$InitializationStateSuccessImpl implements InitializationStateSuccess { } abstract class InitializationStateSuccess implements InitializationState { - const factory InitializationStateSuccess() = _$InitializationStateSuccessImpl; + const factory InitializationStateSuccess( + {required final PusherChannelsClient client}) = + _$InitializationStateSuccessImpl; + + PusherChannelsClient get client; + @JsonKey(ignore: true) + _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> + get copyWith => throw _privateConstructorUsedError; } /// @nodoc @@ -508,7 +541,7 @@ class _$InitializationStateErrorImpl implements InitializationStateError { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function() success, + required TResult Function(PusherChannelsClient client) success, required TResult Function(String errorMessage) error, }) { return error(errorMessage); @@ -519,7 +552,7 @@ class _$InitializationStateErrorImpl implements InitializationStateError { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function()? success, + TResult? Function(PusherChannelsClient client)? success, TResult? Function(String errorMessage)? error, }) { return error?.call(errorMessage); @@ -530,7 +563,7 @@ class _$InitializationStateErrorImpl implements InitializationStateError { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function()? success, + TResult Function(PusherChannelsClient client)? success, TResult Function(String errorMessage)? error, required TResult orElse(), }) { 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 71c84d3..e961471 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 @@ -11,6 +11,5 @@ class BlogPostCreateCredentialsModel with _$BlogPostCreateCredentialsModel { @Default('active') String status, }) = _BlogPostCreateCredentialsModel; - factory BlogPostCreateCredentialsModel.fromJson(Map json) => - _$BlogPostCreateCredentialsModelFromJson(json); + factory BlogPostCreateCredentialsModel.fromJson(Map json) => _$BlogPostCreateCredentialsModelFromJson(json); } 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 60b889a..d98ea7f 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,7 +1,6 @@ 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'; 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 334aa65..1a8e34a 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 @@ -48,7 +48,7 @@ class ChatEntryWidget extends StatelessWidget { ), ), ), - SizedBox(width: 8), + SizedBox(width: 12), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/lib/locator_service.dart b/lib/locator_service.dart index 2f4ee2f..f2ebc20 100644 --- a/lib/locator_service.dart +++ b/lib/locator_service.dart @@ -15,21 +15,16 @@ import 'package:get_it/get_it.dart'; final sl = GetIt.instance; Future init() async { - // BLoC + // BLoC / Cubit + sl.registerFactory(() => InitializationCubit(chatRepository: sl())); sl.registerFactory(() => ChatRoomCubit(chatRepository: sl())); - sl.registerFactory( - () => InitializationCubit(chatRepository: sl())); sl.registerFactory(() => FeedCubit(feedRepository: sl())); - sl.registerFactory( - () => BlogPostCubit(blogPostRepository: sl())); + sl.registerFactory(() => BlogPostCubit(blogPostRepository: sl())); // Repository - sl.registerLazySingleton( - () => ChatRepository(chatService: sl())); - sl.registerLazySingleton( - () => FeedRepository(feedService: sl())); - sl.registerLazySingleton( - () => BlogPostRepository(blogPostService: sl())); + sl.registerLazySingleton(() => ChatRepository(chatService: sl())); + sl.registerLazySingleton(() => FeedRepository(feedService: sl())); + sl.registerLazySingleton(() => BlogPostRepository(blogPostService: sl())); // Services sl.registerLazySingleton(() => ChatService(sl())); diff --git a/lib/main.dart b/lib/main.dart index 2f81b9f..9d608f2 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -52,8 +52,7 @@ class MyApp extends StatelessWidget { ), ], child: BlocListener( - listener: (BuildContext context, InitializationState state) { - }, + listener: (BuildContext context, InitializationState state) {}, child: BlocBuilder( builder: (context, state) { return KeyboardDismisser( diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..d86fe75 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,18 @@ +{ + "name": "eatvio_app", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/simple-git-hooks": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/simple-git-hooks/-/simple-git-hooks-2.11.1.tgz", + "integrity": "sha512-tgqwPUMDcNDhuf1Xf6KTUsyeqGdgKMhzaH4PAZZuzguOgTl5uuyeYe/8mWgAr6IBxB5V06uqEf6Dy37gIWDtDg==", + "dev": true, + "hasInstallScript": true, + "bin": { + "simple-git-hooks": "cli.js" + } + } + } +} diff --git a/node_modules/simple-git-hooks/package.json b/node_modules/simple-git-hooks/package.json new file mode 100644 index 0000000..f3e8186 --- /dev/null +++ b/node_modules/simple-git-hooks/package.json @@ -0,0 +1,18 @@ +{ + "name": "simple-git-hooks", + "version": "2.11.1", + "description": "A simple, zero dependency tool for setting up git hooks for small projects", + "author": "Mikhail Gorbunov ", + "main": "simple-git-hooks.js", + "bin": "./cli.js", + "keywords": ["pre-commit","pre-push","git","hook","lint","linter"], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/toplenboren/simple-git-hooks.git" + }, + "scripts": { + "postinstall": "node ./postinstall.js", + "uninstall": "node ./uninstall.js" + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..67e7935 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,26 @@ +{ + "name": "eatvio_app", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "eatvio_app", + "version": "1.0.0", + "license": "ISC", + "devDependencies": { + "simple-git-hooks": "^2.11.1" + } + }, + "node_modules/simple-git-hooks": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/simple-git-hooks/-/simple-git-hooks-2.11.1.tgz", + "integrity": "sha512-tgqwPUMDcNDhuf1Xf6KTUsyeqGdgKMhzaH4PAZZuzguOgTl5uuyeYe/8mWgAr6IBxB5V06uqEf6Dy37gIWDtDg==", + "dev": true, + "hasInstallScript": true, + "bin": { + "simple-git-hooks": "cli.js" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..9b39c56 --- /dev/null +++ b/package.json @@ -0,0 +1,22 @@ +{ + "name": "eatvio_app", + "version": "1.0.0", + "description": "- Flutter (Channel stable, 3.19.0, on Ubuntu 22.04.3 LTS 6.2.0-39-generic, locale en_US.UTF-8) - Android Studio (version 2023.1) - VS Code (version 1.85.0) - Android SDK (version 34.0.0) - устанавливается из Android Studio (Tools->SDK Manager->Android Command Line Tools) - Эмулятор (2 available)", + "main": "index.js", + "directories": { + "lib": "lib", + "test": "test" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "devDependencies": { + "simple-git-hooks": "^2.11.1" + }, + "simple-git-hooks": { + "pre-push": "make run-checks", + "preserveUnused": true + } +} \ No newline at end of file diff --git a/pubspec.yaml b/pubspec.yaml index d3572e0..49e9d72 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: eatvio_app description: A new Flutter project. version: 0.0.0+1 -publish_to: 'none' +publish_to: "none" environment: sdk: ">=3.3.4 <4.0.0" @@ -13,7 +13,7 @@ dependencies: flutter_localizations: sdk: flutter - # BLoC state manager + # BLoC flutter_bloc: ^8.1.6 # local storage shared_preferences: ^2.2.3 @@ -22,17 +22,17 @@ dependencies: # cached_network_image: ^3.3.1 # - flutter_svg: ^2.0.9 + flutter_svg: ^2.0.10 # equatable: ^2.0.5 # - freezed_annotation: ^2.4.1 + freezed_annotation: ^2.4.2 # json_annotation: ^4.9.0 # validators: ^3.0.0 # - isar_flutter_libs: ^3.1.0+1 + isar_flutter_libs: ^3.1.0 # path_provider: ^2.1.3 # @@ -50,7 +50,7 @@ dependencies: # flutter_typeahead: ^5.2.0 # navigation - go_router: ^14.1.4 + go_router: ^14.2.0 # keyboard_dismisser: ^3.0.0 # service generator @@ -58,9 +58,9 @@ dependencies: # di get_it: ^7.7.0 # http request - dio: ^5.4.3+1 + dio: ^5.5.0 # pusher - dart_pusher_channels: ^1.2.2+1 + dart_pusher_channels: ^1.2.2 # photo gallery viewer + dismissible page photo_view: ^0.15.0 dismissible_page: ^1.0.2 @@ -71,7 +71,7 @@ dev_dependencies: build_runner: ^2.4.11 freezed: ^2.5.2 json_serializable: ^6.8.0 - retrofit_generator: ^8.1.0 + retrofit_generator: ^8.1.1 flutter_test: sdk: flutter -- 2.49.1 From 424ce3cb349c0c18b44c1784c4cae24b172a620c Mon Sep 17 00:00:00 2001 From: alex Date: Wed, 3 Jul 2024 12:01:42 +0300 Subject: [PATCH 020/110] feat(hooks): prepush hooks broken --- lib/core/initialization_cubit/initialization_cubit.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index 83246b1..7ab6863 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -3,12 +3,14 @@ import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_state.dart'; import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; +import 'package:dio/dio.dart'; class InitializationCubit extends Cubit { final ChatRepository chatRepository; InitializationCubit({required this.chatRepository}) : super(const InitializationState.loading()); + // final myPrivateChannel = client.privateChannel( // 'private-new-chat-messages.${wsUrl.userId}', // authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( -- 2.49.1 From 03eba1d832dddeb70e80330e0a1ec5db463d9d77 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 3 Jul 2024 12:13:02 +0300 Subject: [PATCH 021/110] feat(hooks): git hooks added --- .gitignore | 2 +- Makefile | 7 +++++++ package-lock.json | 26 ++++++++++++++++++++++++++ package.json | 22 ++++++++++++++++++++++ 4 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 Makefile create mode 100644 package-lock.json create mode 100644 package.json diff --git a/.gitignore b/.gitignore index e167a73..5831696 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,4 @@ /.flutter-plugins /.flutter-plugins-dependencies /.packages -/.env \ No newline at end of file +/.env/node_modules/ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..f703e60 --- /dev/null +++ b/Makefile @@ -0,0 +1,7 @@ +run-tests: + flutter test + +run-analyse: + flutter analyze + +run-checks: run-analyse run-tests diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..67e7935 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,26 @@ +{ + "name": "eatvio_app", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "eatvio_app", + "version": "1.0.0", + "license": "ISC", + "devDependencies": { + "simple-git-hooks": "^2.11.1" + } + }, + "node_modules/simple-git-hooks": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/simple-git-hooks/-/simple-git-hooks-2.11.1.tgz", + "integrity": "sha512-tgqwPUMDcNDhuf1Xf6KTUsyeqGdgKMhzaH4PAZZuzguOgTl5uuyeYe/8mWgAr6IBxB5V06uqEf6Dy37gIWDtDg==", + "dev": true, + "hasInstallScript": true, + "bin": { + "simple-git-hooks": "cli.js" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..8c0eba5 --- /dev/null +++ b/package.json @@ -0,0 +1,22 @@ +{ + "name": "eatvio_app", + "version": "1.0.0", + "description": "- Flutter (Channel stable, 3.19.0, on Ubuntu 22.04.3 LTS 6.2.0-39-generic, locale en_US.UTF-8) - Android Studio (version 2023.1) - VS Code (version 1.85.0) - Android SDK (version 34.0.0) - устанавливается из Android Studio (Tools->SDK Manager->Android Command Line Tools) - Эмулятор (2 available)", + "main": "index.js", + "directories": { + "lib": "lib", + "test": "test" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "devDependencies": { + "simple-git-hooks": "^2.11.1" + }, + "simple-git-hooks": { + "pre-push": "make run-checks", + "preserveUnused": true + } +} -- 2.49.1 From 20b3c045ddf471db5bcf8f90ff23d8ca884dc94c Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 3 Jul 2024 12:32:50 +0300 Subject: [PATCH 022/110] Revert "feat(hooks): git hooks added" This reverts commit 03eba1d832dddeb70e80330e0a1ec5db463d9d77. --- .gitignore | 2 +- Makefile | 7 ------- package-lock.json | 26 -------------------------- package.json | 22 ---------------------- 4 files changed, 1 insertion(+), 56 deletions(-) delete mode 100644 Makefile delete mode 100644 package-lock.json delete mode 100644 package.json diff --git a/.gitignore b/.gitignore index 5831696..e167a73 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,4 @@ /.flutter-plugins /.flutter-plugins-dependencies /.packages -/.env/node_modules/ +/.env \ No newline at end of file diff --git a/Makefile b/Makefile deleted file mode 100644 index f703e60..0000000 --- a/Makefile +++ /dev/null @@ -1,7 +0,0 @@ -run-tests: - flutter test - -run-analyse: - flutter analyze - -run-checks: run-analyse run-tests diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index 67e7935..0000000 --- a/package-lock.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "eatvio_app", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "eatvio_app", - "version": "1.0.0", - "license": "ISC", - "devDependencies": { - "simple-git-hooks": "^2.11.1" - } - }, - "node_modules/simple-git-hooks": { - "version": "2.11.1", - "resolved": "https://registry.npmjs.org/simple-git-hooks/-/simple-git-hooks-2.11.1.tgz", - "integrity": "sha512-tgqwPUMDcNDhuf1Xf6KTUsyeqGdgKMhzaH4PAZZuzguOgTl5uuyeYe/8mWgAr6IBxB5V06uqEf6Dy37gIWDtDg==", - "dev": true, - "hasInstallScript": true, - "bin": { - "simple-git-hooks": "cli.js" - } - } - } -} diff --git a/package.json b/package.json deleted file mode 100644 index 8c0eba5..0000000 --- a/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "eatvio_app", - "version": "1.0.0", - "description": "- Flutter (Channel stable, 3.19.0, on Ubuntu 22.04.3 LTS 6.2.0-39-generic, locale en_US.UTF-8) - Android Studio (version 2023.1) - VS Code (version 1.85.0) - Android SDK (version 34.0.0) - устанавливается из Android Studio (Tools->SDK Manager->Android Command Line Tools) - Эмулятор (2 available)", - "main": "index.js", - "directories": { - "lib": "lib", - "test": "test" - }, - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "", - "license": "ISC", - "devDependencies": { - "simple-git-hooks": "^2.11.1" - }, - "simple-git-hooks": { - "pre-push": "make run-checks", - "preserveUnused": true - } -} -- 2.49.1 From deb7b11922ddf24ddcfbddb5bf931be4b7f612b0 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 3 Jul 2024 12:44:00 +0300 Subject: [PATCH 023/110] makefile --- Makefile | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Makefile diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..e69de29 -- 2.49.1 From 6194056dc365771093d1f35ce01ffeed80f3ee3d Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 3 Jul 2024 12:53:21 +0300 Subject: [PATCH 024/110] mompls --- .gitignore | 3 ++- lib/features/diary/models/diary_model.dart | 3 ++- lib/features/diary/presentation/bloc/diary_cubit.dart | 3 ++- lib/features/diary/presentation/bloc/diary_state.dart | 3 ++- lib/features/diary/presentation/pages/diary_screen.dart | 3 ++- lib/features/diary/repositories/diary_repository.dart | 3 ++- lib/features/diary/services/diary_service.dart | 3 ++- 7 files changed, 14 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index e167a73..0a42850 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,5 @@ /.flutter-plugins /.flutter-plugins-dependencies /.packages -/.env \ No newline at end of file +/.env +/node_modules \ No newline at end of file diff --git a/lib/features/diary/models/diary_model.dart b/lib/features/diary/models/diary_model.dart index dbf6cee..63aaefc 100644 --- a/lib/features/diary/models/diary_model.dart +++ b/lib/features/diary/models/diary_model.dart @@ -1,4 +1,4 @@ -import 'package:freezed_annotation/freezed_annotation.dart'; +/*import 'package:freezed_annotation/freezed_annotation.dart'; part 'diary_model.freezed.dart'; part 'diary_model.g.dart'; @@ -21,3 +21,4 @@ class DiaryModel with _$DiaryModel { factory DiaryModel.fromJson(Map json) => _$DiaryModelFromJson(json); } +*/ \ No newline at end of file diff --git a/lib/features/diary/presentation/bloc/diary_cubit.dart b/lib/features/diary/presentation/bloc/diary_cubit.dart index 3a67666..07477bd 100644 --- a/lib/features/diary/presentation/bloc/diary_cubit.dart +++ b/lib/features/diary/presentation/bloc/diary_cubit.dart @@ -1,4 +1,4 @@ -import 'package:eatvio_app/core/app_export.dart'; +/*import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; @@ -19,3 +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 e37b05e..d4305c8 100644 --- a/lib/features/diary/presentation/bloc/diary_state.dart +++ b/lib/features/diary/presentation/bloc/diary_state.dart @@ -1,4 +1,4 @@ -import 'package:eatvio_app/features/diary/models/diary_model.dart'; +/*import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'diary_state.freezed.dart'; @@ -17,3 +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 d780616..9cbf204 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -1,6 +1,6 @@ // ignore_for_file: unused_local_variable -import 'bloc/diary_edit_bloc.dart'; +/*import 'bloc/diary_edit_bloc.dart'; import 'models/diary_edit_model.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -1296,3 +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 2f5dc21..1ae40d8 100644 --- a/lib/features/diary/repositories/diary_repository.dart +++ b/lib/features/diary/repositories/diary_repository.dart @@ -1,4 +1,4 @@ -import 'package:eatvio_app/features/diary/models/diary_model.dart'; +/*import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:eatvio_app/features/diary/services/diary_service.dart'; class DiaryRepository { @@ -14,3 +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 181005e..6b6cb6b 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -1,4 +1,4 @@ -import 'package:dio/dio.dart'; +/*import 'package:dio/dio.dart'; import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:retrofit/retrofit.dart'; @@ -11,3 +11,4 @@ abstract class DiaryService { @GET('/feed/show/{id}') Future getDiary(@Path() String id); } +*/ \ No newline at end of file -- 2.49.1 From b2f164da46fd0b1618b0057a43ff2aecbd124f0b Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 3 Jul 2024 13:37:38 +0300 Subject: [PATCH 025/110] fix(diary): Type mismatch fix --- .../bloc/diary_edit_bloc.dart | 487 ++++++++------ .../bloc/diary_edit_state.dart | 135 ++-- .../diary_edit_screen/diary_edit_screen.dart | 616 ++++++++++-------- 3 files changed, 687 insertions(+), 551 deletions(-) diff --git a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart index d279105..1ad049d 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 @@ -29,15 +29,18 @@ class DiaryEditBloc extends Bloc { on(_addPortion); //пользователь нажимает "Добавить продукт" on(_removePortion); on( - _removeImage,); // пользователь нажимает на крестик около продукта + _removeImage, + ); // пользователь нажимает на крестик около продукта on(_uploadImages); //пользователь нажимает "Добавить фото" on(_addComment); //пользователь нажимает "Добавить комментарий" on( - _inputProduct,); //пользователь нажимает "Добавить комментарий" + _inputProduct, + ); //пользователь нажимает "Добавить комментарий" on(_finishDay); //пользователь нажимает "Добавить комментарий" on(_sendModeration); on( - reloadScreen,); //пользователь нажимает "Добавить комментарий" + reloadScreen, + ); //пользователь нажимает "Добавить комментарий" on(_clearInput); } @@ -62,7 +65,8 @@ class DiaryEditBloc extends Bloc { if (state is DiaryEditLoadedState) { // Если текущее состояние уже загружено, обновляем его var currentState = state as DiaryEditLoadedState; - emit((currentState).copyWith( + emit( + (currentState).copyWith( currentMeal: currentState.currentMeal, wakeupExpanded: currentState.wakeupExpanded, moodExpanded: currentState.moodExpanded, @@ -84,20 +88,24 @@ class DiaryEditBloc extends Bloc { selectedMood: currentState.selectedMood, diaryDate: currentState.diaryDate, diaryId: currentState.diaryId, - productQuantityController: - currentState.productQuantityController, + productQuantityController: currentState.productQuantityController, recommendedChartValues: currentState.recommendedChartValues, consumedChartValues: currentState.consumedChartValues, autocompleteList: currentState.autocompleteList, - diaryEditModelObj: currentState.diaryEditModelObj,),); + diaryEditModelObj: currentState.diaryEditModelObj, + ), + ); } else { // Если текущее состояние - начальное, создаем новое загруженное состояние - final List meals = - fillMealList(diary['meals']); - emit(DiaryEditLoadedState( + final List meals = fillMealList(diary['meals']); + emit( + DiaryEditLoadedState( currentMeal: meals[0], portionController: SelectionPopupModel( - id: 0, title: "порций", isSelected: true,), + id: 0, + title: "порций", + isSelected: true, + ), wakeupExpanded: true, moodExpanded: true, moderationExpanded: false, @@ -109,12 +117,10 @@ class DiaryEditBloc extends Bloc { photos: diary['meals'][0]['photos'], wakeupController: toTime(diary['wakeup'] ?? "09:00"), retireController: toTime(diary['retire'] ?? "23:00"), - mealTimeController: - toTime(diary['meals'][0]['time'] ?? "10:00"), + mealTimeController: toTime(diary['meals'][0]['time'] ?? "10:00"), selectedSatiety: diary['meals'][0]['satiety'], selectedMood: diary['meals'][0]['mood'], - commentController: - TextEditingController(text: diary['comment']), + commentController: TextEditingController(text: diary['comment']), productNameController: TextEditingController(), productQuantityController: TextEditingController(), caloriesController: TextEditingController(), @@ -124,8 +130,9 @@ class DiaryEditBloc extends Bloc { diaryId: diaryId, diaryDate: diaryDate, autocompleteList: [], - diaryEditModelObj: state.diaryEditModelObj - ?.copyWith(mealList: meals, portionList: fillPortions()),),); + diaryEditModelObj: state.diaryEditModelObj?.copyWith(mealList: meals, portionList: fillPortions()), + ), + ); } } } catch (e) { @@ -177,31 +184,28 @@ class DiaryEditBloc extends Bloc { } fetchChartValues( - String token, int diaryID, Emitter emit,) async { + String token, + int diaryID, + Emitter emit, + ) async { final responseChart = await http.get( Uri.parse( - dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/dailyNutritionData/',), + dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/dailyNutritionData/', + ), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $token', }, ); if (responseChart.statusCode == 200) { - final recommendedChartValues = - jsonDecode(responseChart.body)['dailyNutritionRecommendation'] - .values - .map((value) => value as double) - .toList(); - final consumedChartValues = - jsonDecode(responseChart.body)['dailyNutritionIntake'] - .values - .map((value) => value as double) - .toList(); + final recommendedChartValues = jsonDecode(responseChart.body)['dailyNutritionRecommendation'].values.map((value) => value as int).toList(); + final consumedChartValues = jsonDecode(responseChart.body)['dailyNutritionIntake'].values.map((value) => value as int).toList(); + print([recommendedChartValues, consumedChartValues]); return [recommendedChartValues, consumedChartValues]; } else { emit(DiaryEditErrorState('Ошибка при декодировании данных КБЖУ')); print('fail'); - return -1; + return [[], []]; // Возвращаем пустые списки вместо -1 } } @@ -249,8 +253,9 @@ class DiaryEditBloc extends Bloc { if (diary is Map) { final String diaryDate = diary['date'] ?? DateTime.now().toString(); final responseChart = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + - '/diary/$diaryId/dailyNutritionData/',), + Uri.parse( + dotenv.env['SERVER_ROOT']! + '/diary/$diaryId/dailyNutritionData/', + ), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer $token', @@ -258,39 +263,41 @@ class DiaryEditBloc extends Bloc { ); if (responseChart.statusCode == 200) { final recommendedChartValues = jsonDecode( - responseChart.body,)['dailyNutritionRecommendation']; - final consumedChartValues = - jsonDecode(responseChart.body)['dailyNutritionIntake']; - final List meals = - fillMealList(diary['meals']); + responseChart.body, + )['dailyNutritionRecommendation']; + final consumedChartValues = jsonDecode(responseChart.body)['dailyNutritionIntake']; + final List meals = fillMealList(diary['meals']); + print(recommendedChartValues); + print(consumedChartValues); try { - await Future(() => emit(DiaryEditLoadedState( + await Future( + () => emit( + DiaryEditLoadedState( diaryEditModelObj: state.diaryEditModelObj?.copyWith( - mealList: meals, portionList: fillPortions(),), + mealList: meals, + portionList: fillPortions(), + ), currentMeal: meals[0], portionController: SelectionPopupModel( - id: 0, title: "порций", isSelected: true,), + id: 0, + title: "порций", + isSelected: true, + ), wakeupExpanded: true, moodExpanded: true, moderationExpanded: false, token: token, - recommendedChartValues: recommendedChartValues.values - .map((value) => value as double) - .toList(), - consumedChartValues: consumedChartValues.values - .map((value) => value as double) - .toList(), + recommendedChartValues: recommendedChartValues.values.map((value) => value as double).toList(), + consumedChartValues: consumedChartValues.values.map((value) => value as double).toList(), meals: diary['meals'], portions: diary['meals'][0]['portions'], photos: diary['meals'][0]['photos'], wakeupController: toTime(diary['wakeup'] ?? "09:00"), retireController: toTime(diary['retire'] ?? "23:00"), - mealTimeController: - toTime(diary['meals'][0]['time'] ?? "10:00"), + mealTimeController: toTime(diary['meals'][0]['time'] ?? "10:00"), selectedSatiety: diary['meals'][0]['satiety'], selectedMood: diary['meals'][0]['mood'], - commentController: - TextEditingController(text: diary['comment']), + commentController: TextEditingController(text: diary['comment']), productNameController: TextEditingController(), productQuantityController: TextEditingController(), caloriesController: TextEditingController(), @@ -301,7 +308,9 @@ class DiaryEditBloc extends Bloc { diaryDate: diaryDate, isLoading: false, autocompleteList: [], - ),),); + ), + ), + ); print("Updated"); } catch (e) { @@ -311,12 +320,16 @@ class DiaryEditBloc extends Bloc { emit(DiaryEditErrorState('Ошибка при декодировании данных КБЖУ')); } } else { - emit(DiaryEditErrorState( - 'Ошибка при декодировании данных дневника',),); + emit( + DiaryEditErrorState( + 'Ошибка при декодировании данных дневника', + ), + ); } } else { emit( - DiaryEditErrorState('Некоторые необходимые данные отсутствуют.'),); + DiaryEditErrorState('Некоторые необходимые данные отсутствуют.'), + ); } } else { emit(DiaryEditErrorState('Ошибка сервера: ${response.statusCode}')); @@ -327,18 +340,20 @@ class DiaryEditBloc extends Bloc { } Future _changeSatiety( - ChangeSatiety event, Emitter emit,) async { + ChangeSatiety event, + Emitter emit, + ) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; - var updatedState = - currentState.copyWith(selectedSatiety: event.selectedElement); + var updatedState = currentState.copyWith(selectedSatiety: event.selectedElement); // Отправляем данные по HTTP маршруту и ждем ответ var response = await sendSatietyData( - currentState.token, - event.selectedElement, - currentState.currentMeal?.id, - currentState.diaryId,); + currentState.token, + event.selectedElement, + currentState.currentMeal?.id, + currentState.diaryId, + ); if (response.statusCode == 200) { updatedState.selectedSatiety = event.selectedElement; @@ -353,38 +368,42 @@ class DiaryEditBloc extends Bloc { int? mealID, int diaryID, ) async { - String url = dotenv.env['SERVER_ROOT']! + - '/diary/$diaryID/meal/$mealID/satiety/fill'; + String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/meal/$mealID/satiety/fill'; final Map credentials = { 'satiety': selectedSatiety, }; - 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; } Future _changeMood( - ChangeMood event, Emitter emit,) async { + ChangeMood event, + Emitter emit, + ) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; - var updatedState = - currentState.copyWith(selectedMood: event.selectedElement); + var updatedState = currentState.copyWith(selectedMood: event.selectedElement); // Отправляем данные по HTTP маршруту и ждем ответ var response = await sendMoodData( - currentState.token, - event.selectedElement, - currentState.currentMeal?.id, - currentState.diaryId,); + currentState.token, + event.selectedElement, + currentState.currentMeal?.id, + currentState.diaryId, + ); if (response.statusCode == 200) { print( - 'Mood change success! meal_id: ${currentState.currentMeal?.id}, mood: ${event.selectedElement}',); + 'Mood change success! meal_id: ${currentState.currentMeal?.id}, mood: ${event.selectedElement}', + ); updatedState.selectedMood = event.selectedElement; emit(updatedState); // Передаем обновленное состояние в emit } @@ -397,33 +416,38 @@ class DiaryEditBloc extends Bloc { int? mealID, int diaryID, ) async { - String url = - dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/meal/$mealID/mood/fill'; + String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/meal/$mealID/mood/fill'; final Map credentials = { 'mood': selectedMood, }; - 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; } FutureOr _changeWakeup( - WakeupEvent event, Emitter emit,) async { + WakeupEvent event, + Emitter emit, + ) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; var response = await sendWakeupData( - currentState.token, event.selectedTime, currentState.diaryId,); + currentState.token, + event.selectedTime, + currentState.diaryId, + ); if (response.statusCode == 200) { await reloadScreen(event, emit); - var updatedState = - currentState.copyWith(wakeupController: event.selectedTime); + var updatedState = currentState.copyWith(wakeupController: event.selectedTime); print("Wakeup time changed to ${event.selectedTime}"); emit(updatedState); // Передаем обновленное состояние в emit } else @@ -432,15 +456,19 @@ class DiaryEditBloc extends Bloc { } FutureOr _changeRetire( - RetireEvent event, Emitter emit,) async { + RetireEvent event, + Emitter emit, + ) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; var response = await sendRetireData( - currentState.token, event.selectedTime, currentState.diaryId,); + currentState.token, + event.selectedTime, + currentState.diaryId, + ); if (response.statusCode == 200) { await reloadScreen(event, emit); - var updatedState = - currentState.copyWith(retireController: event.selectedTime); + var updatedState = currentState.copyWith(retireController: event.selectedTime); print("Retire time changed to ${event.selectedTime}"); emit(updatedState); // Передаем обновленное состояние в emit } else @@ -455,46 +483,53 @@ class DiaryEditBloc extends Bloc { ) async { String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/wakeUp/fill'; final formatter = DateFormat('HH:mm'); - final wakeupString = - formatter.format(DateTime(2022, 1, 1, wakeup.hour, wakeup.minute)); + final wakeupString = formatter.format(DateTime(2022, 1, 1, wakeup.hour, wakeup.minute)); final Map credentials = { 'wakeUp': wakeupString, }; - 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; } Future sendRetireData( - String? token, TimeOfDay retire, int diaryID,) async { + String? token, + TimeOfDay retire, + int diaryID, + ) async { String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill'; final formatter = DateFormat('HH:mm'); - final retireString = - formatter.format(DateTime(2022, 1, 1, retire.hour, retire.minute)); + final retireString = formatter.format(DateTime(2022, 1, 1, retire.hour, retire.minute)); final Map credentials = { 'retire': retireString, }; - 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; } FutureOr _changeMealTime( - ChangeMealTime event, Emitter emit,) async { + ChangeMealTime event, + Emitter emit, + ) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; var updatedState = currentState.copyWith(mealTimeController: event.time); @@ -516,51 +551,59 @@ class DiaryEditBloc extends Bloc { 'diary_id': diaryID, }; - 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; } FutureOr _changeMeal( - ChangeMeal event, Emitter emit,) async { + ChangeMeal event, + Emitter emit, + ) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; final meal = currentState.meals?.firstWhere( - (meal) => meal['id'] == event.value.id, - orElse: () => null,); + (meal) => meal['id'] == event.value.id, + orElse: () => null, + ); int? id = event.value.id; print(meal['photos']); DiaryEditLoadedState updatedState = currentState.copyWith( - currentMeal: event.value, - portions: meal['portions'], - photos: meal['photos'], - mealTimeController: toTime(meal['time'] ?? "1$id:00"), - selectedMood: meal['mood'], - selectedSatiety: meal['satiety'],); + currentMeal: event.value, + portions: meal['portions'], + photos: meal['photos'], + mealTimeController: toTime(meal['time'] ?? "1$id:00"), + selectedMood: meal['mood'], + selectedSatiety: meal['satiety'], + ); print(updatedState.photos); emit(updatedState); } } - FutureOr _clearInput( - ClearInput event, Emitter emit,) { + ClearInput event, + Emitter emit, + ) { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; - DiaryEditLoadedState updatedState = currentState.copyWith( - ); + DiaryEditLoadedState updatedState = currentState.copyWith(); emit(updatedState); } } FutureOr _changePortion( - ChangePortion event, Emitter emit,) { + ChangePortion event, + Emitter emit, + ) { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; DiaryEditLoadedState updatedState = currentState.copyWith( @@ -571,7 +614,9 @@ class DiaryEditBloc extends Bloc { } FutureOr _toggleMood( - ToggleMoodExpandedEvent event, Emitter emit,) { + ToggleMoodExpandedEvent event, + Emitter emit, + ) { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; @@ -581,7 +626,9 @@ class DiaryEditBloc extends Bloc { } FutureOr _toggleWakeup( - ToggleWakeupExpandedEvent event, Emitter emit,) { + ToggleWakeupExpandedEvent event, + Emitter emit, + ) { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; @@ -591,7 +638,9 @@ class DiaryEditBloc extends Bloc { } FutureOr _addPortion( - AddPortionEvent event, Emitter emit,) async { + AddPortionEvent event, + Emitter emit, + ) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; @@ -609,15 +658,21 @@ class DiaryEditBloc extends Bloc { await reloadScreen(event, emit); } else { print( - 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}',); + 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}', + ); } } } - FutureOr sendPortionData(String? token, String? name, - String portion, int? quantity, int? mealID, int diaryID,) async { - String url = - '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/create'; + FutureOr sendPortionData( + String? token, + String? name, + String portion, + int? quantity, + int? mealID, + int diaryID, + ) async { + String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/create'; final Map credentials = { 'product_name': name, @@ -639,14 +694,17 @@ class DiaryEditBloc extends Bloc { } Future _inputProduct( - ProductInput event, Emitter emit,) async { + ProductInput event, + Emitter emit, + ) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; String? token = currentState.token; final Map credentials = {'name': event.input}; final uri = Uri.parse( - '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/filter?${Uri(queryParameters: credentials).query}',); + '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/filter?${Uri(queryParameters: credentials).query}', + ); final response = await http.get( uri, @@ -656,16 +714,13 @@ class DiaryEditBloc extends Bloc { }, ); - final productNutritionalValues = - jsonDecode(response.body)['product_nutritional_value']; + final productNutritionalValues = jsonDecode(response.body)['product_nutritional_value']; if (productNutritionalValues is List) { // Create a new controller with the input text and update the autocomplete list var updatedState = currentState.copyWith( productNameController: TextEditingController(text: event.input), - autocompleteList: productNutritionalValues - .map((product) => product['name']) - .toList(), + autocompleteList: productNutritionalValues.map((product) => product['name']).toList(), ); if (event.input.length > 3) { updatedState = updatedState.copyWith(moderationExpanded: true); @@ -679,12 +734,13 @@ class DiaryEditBloc extends Bloc { } Future _removePortion( - RemovePortionEvent event, Emitter emit,) async { + RemovePortionEvent event, + Emitter emit, + ) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; - int? mealId = - currentState.currentMeal?.id; // Rename id to mealId for clarity + int? mealId = currentState.currentMeal?.id; // Rename id to mealId for clarity var response = await sendRemovePortion( currentState.token, @@ -697,15 +753,19 @@ class DiaryEditBloc extends Bloc { await reloadScreen(event, emit); } else { print( - 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}',); + 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}', + ); } } } Future sendRemovePortion( - String? token, int? portionID, int? mealID, int diaryID,) async { - String url = - '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete'; + String? token, + int? portionID, + int? mealID, + int diaryID, + ) async { + String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete'; var response = await http.delete( Uri.parse(url), @@ -720,7 +780,9 @@ class DiaryEditBloc extends Bloc { } FutureOr _removeImage( - RemoveImageEvent event, Emitter emit,) async { + RemoveImageEvent event, + Emitter emit, + ) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; @@ -736,15 +798,20 @@ class DiaryEditBloc extends Bloc { await reloadScreen(event, emit); } else { print( - 'Failed to remove photo. Status Code: ${response.statusCode} ${response.body}',); + 'Failed to remove photo. Status Code: ${response.statusCode} ${response.body}', + ); } } } - Future sendRemovePhoto(String? token, String? path, - String? photoID, int? mealID, int diaryID,) async { - String url = - '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete'; + Future sendRemovePhoto( + String? token, + String? path, + String? photoID, + int? mealID, + int diaryID, + ) async { + String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete'; final Map credentials = { 'id': photoID, 'path': path, @@ -780,13 +847,16 @@ class DiaryEditBloc extends Bloc { } } - Future sendFinishDay(String? token, int diaryID, - TimeOfDay? wakeup, TimeOfDay? retire, String? comment,) async { + Future sendFinishDay( + String? token, + int diaryID, + TimeOfDay? wakeup, + TimeOfDay? retire, + String? comment, + ) async { final formatter = DateFormat('HH:mm'); - final wakeupString = - formatter.format(DateTime(2022, 1, 1, wakeup!.hour, wakeup.minute)); - final retireString = - formatter.format(DateTime(2022, 1, 1, retire!.hour, retire.minute)); + final wakeupString = formatter.format(DateTime(2022, 1, 1, wakeup!.hour, wakeup.minute)); + final retireString = formatter.format(DateTime(2022, 1, 1, retire!.hour, retire.minute)); final Map credentials = { 'wakeup': wakeupString, @@ -810,21 +880,30 @@ class DiaryEditBloc extends Bloc { } Future _uploadImages( - UploadImages event, Emitter emit,) async { + UploadImages event, + Emitter emit, + ) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; emit(currentState.copyWith(isLoading: true)); - await uploadImageToServer(event.image.path, currentState.diaryId, - currentState.currentMeal!.id!, currentState.token,); + await uploadImageToServer( + event.image.path, + currentState.diaryId, + currentState.currentMeal!.id!, + currentState.token, + ); await reloadScreen(event, emit); } } Future uploadImageToServer( - String imagePath, int diaryID, int mealId, String? token,) async { - String url = - '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload'; + String imagePath, + int diaryID, + int mealId, + String? token, + ) async { + String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload'; var request = http.MultipartRequest('POST', Uri.parse(url)); request.headers['Authorization'] = 'Bearer $token'; @@ -841,12 +920,15 @@ class DiaryEditBloc extends Bloc { return imageUrl; } else { throw Exception( - 'Failed to upload image. Status code: ${streamedResponse.statusCode}}',); + 'Failed to upload image. Status code: ${streamedResponse.statusCode}}', + ); } } FutureOr _sendModeration( - SendModeration event, Emitter emit,) async { + SendModeration event, + Emitter emit, + ) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; final response = await _sendModerationData( @@ -866,14 +948,16 @@ class DiaryEditBloc extends Bloc { } Future _sendModerationData( - String name, - String energy_on_100gr, - String proteins_on_100gr, - String fats_on_100gr, - String carbohydrates_on_100gr, - String? token,) async { + String name, + String energy_on_100gr, + String proteins_on_100gr, + String fats_on_100gr, + String carbohydrates_on_100gr, + String? token, + ) async { final Uri url = Uri.parse( - '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/sendToModeration',); + '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/sendToModeration', + ); final Uri serverURL = Uri.parse('${dotenv.env['SERVER_ROOT']!}'); String host = serverURL.host; final Map credentials = { @@ -901,12 +985,15 @@ class DiaryEditBloc extends Bloc { return response; } else { throw Exception( - 'Failed to send a product for moderation ${response.statusCode}',); + 'Failed to send a product for moderation ${response.statusCode}', + ); } } FutureOr _addComment( - AddComment event, Emitter emit,) async { + AddComment event, + Emitter emit, + ) async { if (state is DiaryEditLoadedState) { var currentState = state as DiaryEditLoadedState; var updatedState = currentState.copyWith( @@ -915,7 +1002,10 @@ class DiaryEditBloc extends Bloc { // Отправляем данные по HTTP маршруту и ждем ответ var response = await sendCommentData( - currentState.token, event.comment, currentState.diaryId,); + currentState.token, + event.comment, + currentState.diaryId, + ); if (response.statusCode == 200) { emit(updatedState); // Передаем обновленное состояние в emit @@ -924,19 +1014,24 @@ class DiaryEditBloc extends Bloc { } Future sendCommentData( - String? token, String comment, int diaryID,) async { + String? token, + String comment, + int diaryID, + ) async { String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill'; final Map credentials = { 'comment': comment, }; - 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/diary/diary_edit_screen/bloc/diary_edit_state.dart b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart index 6486b03..71551d6 100644 --- a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart +++ b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart @@ -12,43 +12,42 @@ class DiaryEditState extends Equatable { } class DiaryEditInitialState extends DiaryEditState { - DiaryEditInitialState({required DiaryEditModel diaryEditModelObj}) - : super(diaryEditModelObj: diaryEditModelObj); + DiaryEditInitialState({required DiaryEditModel diaryEditModelObj}) : super(diaryEditModelObj: diaryEditModelObj); } /// Represents the state of DiaryEdit in the application. class DiaryEditLoadedState extends DiaryEditState { - DiaryEditLoadedState( - {this.diaryEditModelObj, - this.diaryDate, - this.token, - this.meals, - this.portions, - this.photos, - this.autocompleteList, - this.wakeupController, - this.retireController, - this.commentController, - this.mealTimeController, - this.portionController, - this.productNameController, - this.productQuantityController, - this.selectedMood, - this.currentMeal, - this.caloriesController, - this.fatsController, - this.proteinsController, - this.carbsController, - this.isLoading = false, - this.isAdded = false, - required this.recommendedChartValues, - required this.consumedChartValues, - required this.diaryId, - required this.selectedSatiety, - required this.moderationExpanded, - required this.wakeupExpanded, - required this.moodExpanded,}) - : super(diaryEditModelObj: null); + DiaryEditLoadedState({ + this.diaryEditModelObj, + this.diaryDate, + this.token, + this.meals, + this.portions, + this.photos, + this.autocompleteList, + this.wakeupController, + this.retireController, + this.commentController, + this.mealTimeController, + this.portionController, + this.productNameController, + this.productQuantityController, + this.selectedMood, + this.currentMeal, + this.caloriesController, + this.fatsController, + this.proteinsController, + this.carbsController, + this.isLoading = false, + this.isAdded = false, + required this.recommendedChartValues, + required this.consumedChartValues, + required this.diaryId, + required this.selectedSatiety, + required this.moderationExpanded, + required this.wakeupExpanded, + required this.moodExpanded, + }) : super(diaryEditModelObj: null); DiaryEditModel? diaryEditModelObj; String? diaryDate; @@ -57,8 +56,8 @@ class DiaryEditLoadedState extends DiaryEditState { List? portions; List? photos; List? autocompleteList; - List recommendedChartValues; - List consumedChartValues; + List recommendedChartValues; + List consumedChartValues; SelectionPopupModel? currentMeal; SelectionPopupModel? portionController; TimeOfDay? wakeupController; @@ -117,8 +116,8 @@ class DiaryEditLoadedState extends DiaryEditState { SelectionPopupModel? portionController, String? diaryDate, String? token, - List? recommendedChartValues, - List? consumedChartValues, + List? recommendedChartValues, + List? consumedChartValues, List? meals, List? portions, List? photos, @@ -143,38 +142,36 @@ class DiaryEditLoadedState extends DiaryEditState { bool? isAdded, }) { return DiaryEditLoadedState( - diaryEditModelObj: diaryEditModelObj ?? this.diaryEditModelObj, - diaryDate: diaryDate ?? this.diaryDate, - token: token ?? this.token, - meals: meals ?? this.meals, - photos: photos ?? this.photos, - autocompleteList: autocompleteList ?? this.autocompleteList, - portions: portions ?? this.portions, - recommendedChartValues: - recommendedChartValues ?? this.recommendedChartValues, - consumedChartValues: consumedChartValues ?? this.consumedChartValues, - wakeupController: wakeupController ?? this.wakeupController, - retireController: retireController ?? this.retireController, - mealTimeController: mealTimeController ?? this.mealTimeController, - commentController: commentController ?? this.commentController, - portionController: portionController ?? this.portionController, - productNameController: - productNameController ?? this.productNameController, - productQuantityController: - productQuantityController ?? this.productQuantityController, - selectedMood: selectedMood ?? this.selectedMood, - selectedSatiety: selectedSatiety ?? this.selectedSatiety, - diaryId: diaryId ?? this.diaryId, - currentMeal: currentMeal ?? this.currentMeal, - caloriesController: caloriesController ?? this.caloriesController, - fatsController: fatsController ?? this.fatsController, - proteinsController: proteinsController ?? this.proteinsController, - carbsController: carbsController ?? this.carbsController, - wakeupExpanded: wakeupExpanded ?? this.wakeupExpanded, - moderationExpanded: moderationExpanded ?? this.moderationExpanded, - moodExpanded: moodExpanded ?? this.moodExpanded, - isAdded: isAdded ?? this.isAdded, - isLoading: isLoading ?? this.isLoading,); + diaryEditModelObj: diaryEditModelObj ?? this.diaryEditModelObj, + diaryDate: diaryDate ?? this.diaryDate, + token: token ?? this.token, + meals: meals ?? this.meals, + photos: photos ?? this.photos, + autocompleteList: autocompleteList ?? this.autocompleteList, + portions: portions ?? this.portions, + recommendedChartValues: recommendedChartValues ?? this.recommendedChartValues, + consumedChartValues: consumedChartValues ?? this.consumedChartValues, + wakeupController: wakeupController ?? this.wakeupController, + retireController: retireController ?? this.retireController, + mealTimeController: mealTimeController ?? this.mealTimeController, + commentController: commentController ?? this.commentController, + portionController: portionController ?? this.portionController, + productNameController: productNameController ?? this.productNameController, + productQuantityController: productQuantityController ?? this.productQuantityController, + selectedMood: selectedMood ?? this.selectedMood, + selectedSatiety: selectedSatiety ?? this.selectedSatiety, + diaryId: diaryId ?? this.diaryId, + currentMeal: currentMeal ?? this.currentMeal, + caloriesController: caloriesController ?? this.caloriesController, + fatsController: fatsController ?? this.fatsController, + proteinsController: proteinsController ?? this.proteinsController, + carbsController: carbsController ?? this.carbsController, + wakeupExpanded: wakeupExpanded ?? this.wakeupExpanded, + moderationExpanded: moderationExpanded ?? this.moderationExpanded, + moodExpanded: moodExpanded ?? this.moodExpanded, + isAdded: isAdded ?? this.isAdded, + isLoading: isLoading ?? this.isLoading, + ); } } 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 5f94a18..dfea7c2 100644 --- a/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart +++ b/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart @@ -21,7 +21,9 @@ class DiaryEditScreen extends StatelessWidget { static Widget builder(BuildContext context) { return BlocProvider( - create: (context) => DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel()))..add(DiaryEditInitialEvent()), child: DiaryEditScreen(),); + create: (context) => DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel()))..add(DiaryEditInitialEvent()), + child: DiaryEditScreen(), + ); } Widget build(BuildContext context) { @@ -264,237 +266,241 @@ class DiaryEditScreen extends StatelessWidget { //print(_options); FocusNode focusNodeName = FocusNode(); return Container( - margin: EdgeInsets.symmetric(horizontal: 16.h), - padding: EdgeInsets.symmetric( - horizontal: 24.h, - vertical: 12.v, - ), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: const BorderRadius.all(Radius.circular(12)), - boxShadow: [ - BoxShadow( - color: Colors.grey.withOpacity(0.5), - spreadRadius: 2, - blurRadius: 5, - offset: Offset(0, 3), - ), - ], - ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: EdgeInsets.symmetric(horizontal: 10.h), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - "Время приема пищи", - style: CustomTextStyles.bodyMediumBlack900, - ), - Expanded( - // Adding Expanded widget - child: Padding( - padding: EdgeInsets.symmetric(horizontal: 10.h), - child: ConstrainedBox( - constraints: BoxConstraints( - maxWidth: MediaQuery.of(context).size.width - 260, - ), - child: GestureDetector( - onTap: () => _selectMealTime(context, state), - child: AbsorbPointer( - child: CustomTextFormField( - hintText: state.mealTimeController?.format(context).toString(), - autofocus: false, - ), + margin: EdgeInsets.symmetric(horizontal: 16.h), + padding: EdgeInsets.symmetric( + horizontal: 24.h, + vertical: 12.v, + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.all(Radius.circular(12)), + boxShadow: [ + BoxShadow( + color: Colors.grey.withOpacity(0.5), + spreadRadius: 2, + blurRadius: 5, + offset: Offset(0, 3), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: EdgeInsets.symmetric(horizontal: 10.h), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + "Время приема пищи", + style: CustomTextStyles.bodyMediumBlack900, + ), + Expanded( + // Adding Expanded widget + child: Padding( + padding: EdgeInsets.symmetric(horizontal: 10.h), + child: ConstrainedBox( + constraints: BoxConstraints( + maxWidth: MediaQuery.of(context).size.width - 260, + ), + child: GestureDetector( + onTap: () => _selectMealTime(context, state), + child: AbsorbPointer( + child: CustomTextFormField( + hintText: state.mealTimeController?.format(context).toString(), + autofocus: false, ), ), ), ), ), + ), + ], + ), + ), + SizedBox(height: 20.v), + Padding( + padding: EdgeInsets.symmetric(horizontal: 10.h), + child: BlocSelector( + selector: (state) => state.diaryEditModelObj, + builder: (context, diaryEditModelObj) { + return CustomDropDown( + hintText: "Прием пищи", + items: diaryEditModelObj?.mealList, + contentPadding: EdgeInsets.symmetric( + horizontal: 10.h, + vertical: 9.v, + ), + defaultValue: diaryEditModelObj?.mealList[0], + onChanged: changeMeal(context, state), + ); + }, + ), + ), + SizedBox(height: 20.v), + Padding( + padding: EdgeInsets.symmetric(horizontal: 10.h), + child: RawAutocomplete( + optionsBuilder: buildOptions(_options), + fieldViewBuilder: ( + BuildContext context, + TextEditingController productEditingController, + FocusNode focusNodeName, + VoidCallback onFieldSubmitted, + ) { + if (state.isAdded) { + print("Clear"); + } + return CustomTextFormField( + hintText: "Введите название продукта", + controller: productEditingController, + focusNode: focusNodeName, + onChanged: getAutocomplete(context, focusNodeName), + ); + }, + 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: selectProduct(onSelected, option, state), + child: ListTile( + title: Text(option), + ), + ); + }, + ), + ), + ), + ); + }, + ), + ), + SizedBox(height: 20.v), + if (state.moderationExpanded) + Padding( + padding: EdgeInsets.symmetric(horizontal: 10.h), + child: GestureDetector( + onTap: () => openCaloriesDialog(context, state), + child: Text("Отправить на модерацию"), + ), + ), + SizedBox(height: 20.v), + Padding( + padding: EdgeInsets.symmetric(horizontal: 10.h), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + CustomTextFormField( + width: 150.h, + hintText: "Кол-во", + textInputAction: TextInputAction.done, + // focusNode: focusNodeQuantity, + controller: state.productQuantityController, + keyboardType: TextInputType.number, + inputFormatters: [digitsOnly], + ), + Padding( + padding: EdgeInsets.only(left: 30.h), + child: BlocSelector( + selector: (state) => state.diaryEditModelObj, + builder: (context, diaryEditModelObj) { + return CustomDropDown( + items: diaryEditModelObj?.portionList, + defaultValue: diaryEditModelObj?.portionList?[0], + onChanged: changePortion(context, state), + ); + }, + ), + ), ], ), ), - SizedBox(height: 20.v), - Padding( - padding: EdgeInsets.symmetric(horizontal: 10.h), - child: BlocSelector( - selector: (state) => state.diaryEditModelObj, - builder: (context, diaryEditModelObj) { - return CustomDropDown( - hintText: "Прием пищи", - items: diaryEditModelObj?.mealList, - contentPadding: EdgeInsets.symmetric( - horizontal: 10.h, - vertical: 9.v, - ), - defaultValue: diaryEditModelObj?.mealList[0], - onChanged: changeMeal(context, state), - ); - },),), - SizedBox(height: 20.v), - Padding( - padding: EdgeInsets.symmetric(horizontal: 10.h), - child: RawAutocomplete( - optionsBuilder: buildOptions(_options), - fieldViewBuilder: ( - BuildContext context, - TextEditingController productEditingController, - FocusNode focusNodeName, - VoidCallback onFieldSubmitted, - ) { - if (state.isAdded) { - print("Clear"); - } - return CustomTextFormField( - hintText: "Введите название продукта", - controller: productEditingController, - focusNode: focusNodeName, - onChanged: getAutocomplete(context, focusNodeName), - ); - }, - 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: selectProduct(onSelected, option, state), - child: ListTile( - title: Text(option), - ), - ); - }, - ), - ), - ), - ); - },), - ), - SizedBox(height: 20.v), - if (state.moderationExpanded) - Padding( - padding: EdgeInsets.symmetric(horizontal: 10.h), - child: GestureDetector( - onTap: () => openCaloriesDialog(context, state), - child: Text("Отправить на модерацию"), - ), - ), - SizedBox(height: 20.v), - Padding( - padding: EdgeInsets.symmetric(horizontal: 10.h), - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - CustomTextFormField( - width: 150.h, - hintText: "Кол-во", - textInputAction: TextInputAction.done, - // focusNode: focusNodeQuantity, - controller: state.productQuantityController, - keyboardType: TextInputType.number, - inputFormatters: [digitsOnly], - ), - Padding( - padding: EdgeInsets.only(left: 30.h), - child: BlocSelector( - selector: (state) => state.diaryEditModelObj, - builder: (context, diaryEditModelObj) { - return CustomDropDown( - items: diaryEditModelObj?.portionList, - defaultValue: diaryEditModelObj?.portionList?[0], - onChanged: changePortion(context, state), - ); - }, - ), - ), - ], - ), - ), - ), - SizedBox(height: 30.v), - _buildAddProduct(context, state), - SizedBox(height: 30.v), - ...state.portions!.map((portion) => _buildProduct(context, portion)).toList(), - SizedBox(height: 30.v), - /*...state.photos != null + ), + SizedBox(height: 30.v), + _buildAddProduct(context, state), + SizedBox(height: 30.v), + ...state.portions!.map((portion) => _buildProduct(context, portion)).toList(), + SizedBox(height: 30.v), + /*...state.photos != null ? state.photos!.isEmpty ? [Text('Фото пока нет')] : state.photos! .map((photo) => _buildPhoto(context, photo)) .toList() : [Text('Фото нет')],*/ - _buildCarousel(context, state), - SizedBox(height: 20.v), - _buildAddPhoto(context, state), - SizedBox(height: 30.v), - Text( - "Ваша сытость после приёма пищи", - style: CustomTextStyles.bodyMediumBlack900, - ), - SizedBox(height: 15.v), - BlocBuilder( - builder: (context, state) { - if (state is DiaryEditLoadedState) { - return Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text("😭"), - ScaleElement( - color: Colors.red, - isSelected: state.selectedSatiety == 0, - onTap: changeSatiety(context, 0), - ), - ScaleElement( - color: Colors.orange, - isSelected: state.selectedSatiety == 1, - onTap: changeSatiety(context, 1), - ), - ScaleElement( - color: Colors.yellow, - isSelected: state.selectedSatiety == 2, - onTap: changeSatiety(context, 2), - ), - ScaleElement( - color: Colors.lime, - isSelected: state.selectedSatiety == 3, - onTap: changeSatiety(context, 3), - ), - ScaleElement( - color: Colors.lightGreen, - isSelected: state.selectedSatiety == 4, - onTap: changeSatiety(context, 4), - ), - ScaleElement( - color: Colors.green, - isSelected: state.selectedSatiety == 5, - onTap: changeSatiety(context, 5), - ), - Text("😊"), - // Остальные элементы шкалы - ], - ); - } else { - return Container(); // Возвращаем пустой контейнер, если состояние не является DiaryEditLoadedState - } - }, - ), - ], - ),); + _buildCarousel(context, state), + SizedBox(height: 20.v), + _buildAddPhoto(context, state), + SizedBox(height: 30.v), + Text( + "Ваша сытость после приёма пищи", + style: CustomTextStyles.bodyMediumBlack900, + ), + SizedBox(height: 15.v), + BlocBuilder( + builder: (context, state) { + if (state is DiaryEditLoadedState) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("😭"), + ScaleElement( + color: Colors.red, + isSelected: state.selectedSatiety == 0, + onTap: changeSatiety(context, 0), + ), + ScaleElement( + color: Colors.orange, + isSelected: state.selectedSatiety == 1, + onTap: changeSatiety(context, 1), + ), + ScaleElement( + color: Colors.yellow, + isSelected: state.selectedSatiety == 2, + onTap: changeSatiety(context, 2), + ), + ScaleElement( + color: Colors.lime, + isSelected: state.selectedSatiety == 3, + onTap: changeSatiety(context, 3), + ), + ScaleElement( + color: Colors.lightGreen, + isSelected: state.selectedSatiety == 4, + onTap: changeSatiety(context, 4), + ), + ScaleElement( + color: Colors.green, + isSelected: state.selectedSatiety == 5, + onTap: changeSatiety(context, 5), + ), + Text("😊"), + // Остальные элементы шкалы + ], + ); + } else { + return Container(); // Возвращаем пустой контейнер, если состояние не является DiaryEditLoadedState + } + }, + ), + ], + ), + ); } openCaloriesDialog(BuildContext context, DiaryEditLoadedState state) { @@ -542,8 +548,15 @@ class DiaryEditScreen extends StatelessWidget { child: Text('Отмена'), ), TextButton( - onPressed: triggerModeration(context, state.productNameController!.text, state.caloriesController!.text, state.proteinsController!.text, - state.fatsController!.text, state.carbsController!.text, dialogContext,), + onPressed: triggerModeration( + context, + state.productNameController!.text, + state.caloriesController!.text, + state.proteinsController!.text, + state.fatsController!.text, + state.carbsController!.text, + dialogContext, + ), child: Text('Отправить'), ), ], @@ -552,12 +565,26 @@ class DiaryEditScreen extends StatelessWidget { ); } - triggerModeration(BuildContext context, String name, String energyOn100gr, String proteinsOn100gr, String fatsOn100gr, String carbohydratesOn100gr, - BuildContext dialogContext,) { + triggerModeration( + BuildContext context, + String name, + String energyOn100gr, + String proteinsOn100gr, + String fatsOn100gr, + String carbohydratesOn100gr, + BuildContext dialogContext, + ) { return () { // Call function to send moderation with the entered values - context.read().add(SendModeration( - name: name, energyOn100gr: energyOn100gr, proteinsOn100gr: proteinsOn100gr, fatsOn100gr: fatsOn100gr, carbohydratesOn100gr: carbohydratesOn100gr,),); + context.read().add( + SendModeration( + name: name, + energyOn100gr: energyOn100gr, + proteinsOn100gr: proteinsOn100gr, + fatsOn100gr: fatsOn100gr, + carbohydratesOn100gr: carbohydratesOn100gr, + ), + ); Navigator.of(dialogContext).pop(); // Dismiss the dialog }; } @@ -640,14 +667,15 @@ class DiaryEditScreen extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ Padding( - padding: EdgeInsets.only( - left: 7.h, - top: 5.v, - ), - child: Text( - portion['product_name'].length > 8 ? portion['product_name'].substring(0, 8) : portion['product_name'], - style: CustomTextStyles.titleMedium16, - ),), + padding: EdgeInsets.only( + left: 7.h, + top: 5.v, + ), + child: Text( + portion['product_name'].length > 8 ? portion['product_name'].substring(0, 8) : portion['product_name'], + style: CustomTextStyles.titleMedium16, + ), + ), Padding( padding: EdgeInsets.only( left: 20.h, @@ -660,14 +688,15 @@ class DiaryEditScreen extends StatelessWidget { ), Spacer(), GestureDetector( - onTap: removePortion(context, portion), - child: Padding( - padding: const EdgeInsets.only(right: 10), - child: Icon( - Icons.close, - color: appTheme.blueGray300, - ), - ),), + onTap: removePortion(context, portion), + child: Padding( + padding: const EdgeInsets.only(right: 10), + child: Icon( + Icons.close, + color: appTheme.blueGray300, + ), + ), + ), ], ), ); @@ -720,8 +749,8 @@ class DiaryEditScreen extends StatelessWidget { } _buildNutritionChart(BuildContext context, DiaryEditLoadedState state) { - final List recommendedValues = state.recommendedChartValues; // Рекомендуемые значения: калории, жиры, белки, углеводы - final List consumedValues = state.consumedChartValues; // + final List recommendedValues = state.recommendedChartValues; // Рекомендуемые значения: калории, жиры, белки, углеводы + final List consumedValues = state.consumedChartValues; // return Container( margin: EdgeInsets.symmetric(horizontal: 16.h), padding: EdgeInsets.symmetric( @@ -779,30 +808,42 @@ class DiaryEditScreen extends StatelessWidget { ), borderData: FlBorderData(show: false), barGroups: [ - BarChartGroupData(x: 0, barRods: [ - BarChartRodData( - toY: consumedValues[0] / recommendedValues[0] * 100, - color: checkConsumedValues([recommendedValues[0]], [consumedValues[1]]) ? Colors.red : Colors.blue, - ), - ],), - BarChartGroupData(x: 1, barRods: [ - BarChartRodData( - toY: consumedValues[1] / recommendedValues[1] * 100, - color: checkConsumedValues([recommendedValues[1]], [consumedValues[1]]) ? Colors.red : Colors.blue, - ), - ],), - BarChartGroupData(x: 2, barRods: [ - BarChartRodData( - toY: consumedValues[2] / recommendedValues[2] * 100, - color: checkConsumedValues([recommendedValues[2]], [consumedValues[2]]) ? Colors.red : Colors.blue, - ), - ],), - BarChartGroupData(x: 3, barRods: [ - BarChartRodData( - toY: consumedValues[3] / recommendedValues[3] * 100, - color: checkConsumedValues([recommendedValues[3]], [consumedValues[3]]) ? Colors.red : Colors.blue, - ), - ],), + BarChartGroupData( + x: 0, + barRods: [ + BarChartRodData( + toY: consumedValues[0] / recommendedValues[0] * 100, + color: checkConsumedValues([recommendedValues[0]], [consumedValues[1]]) ? Colors.red : Colors.blue, + ), + ], + ), + BarChartGroupData( + x: 1, + barRods: [ + BarChartRodData( + toY: consumedValues[1] / recommendedValues[1] * 100, + color: checkConsumedValues([recommendedValues[1]], [consumedValues[1]]) ? Colors.red : Colors.blue, + ), + ], + ), + BarChartGroupData( + x: 2, + barRods: [ + BarChartRodData( + toY: consumedValues[2] / recommendedValues[2] * 100, + color: checkConsumedValues([recommendedValues[2]], [consumedValues[2]]) ? Colors.red : Colors.blue, + ), + ], + ), + BarChartGroupData( + x: 3, + barRods: [ + BarChartRodData( + toY: consumedValues[3] / recommendedValues[3] * 100, + color: checkConsumedValues([recommendedValues[3]], [consumedValues[3]]) ? Colors.red : Colors.blue, + ), + ], + ), ], ), ), @@ -1077,24 +1118,25 @@ class DiaryEditScreen extends StatelessWidget { _buildMood(BuildContext context, DiaryEditLoadedState state) { return Container( - margin: EdgeInsets.symmetric(horizontal: 16.h), - padding: EdgeInsets.symmetric( - horizontal: 24.h, - vertical: 12.v, - ), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: const BorderRadius.all(Radius.circular(12)), - boxShadow: [ - BoxShadow( - color: Colors.grey.withOpacity(0.5), - spreadRadius: 2, - blurRadius: 5, - offset: Offset(0, 3), - ), - ], - ), - child: Column(children: [ + margin: EdgeInsets.symmetric(horizontal: 16.h), + padding: EdgeInsets.symmetric( + horizontal: 24.h, + vertical: 12.v, + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.all(Radius.circular(12)), + boxShadow: [ + BoxShadow( + color: Colors.grey.withOpacity(0.5), + spreadRadius: 2, + blurRadius: 5, + offset: Offset(0, 3), + ), + ], + ), + child: Column( + children: [ GestureDetector( onTap: toggleMood(context), child: Row( @@ -1147,7 +1189,9 @@ class DiaryEditScreen extends StatelessWidget { // Остальные элементы шкалы ], ), - ],),); + ], + ), + ); } changeMood(BuildContext context, int satiety) { @@ -1196,7 +1240,7 @@ class DiaryEditScreen extends StatelessWidget { } } -bool checkConsumedValues(List recommendedValues, List consumedValues) { +bool checkConsumedValues(List recommendedValues, List consumedValues) { for (int i = 0; i < recommendedValues.length; i++) { if (consumedValues[i] > recommendedValues[i]) { // Если хотя бы одно потребленное значение превышает рекомендованное -- 2.49.1 From d58e96d07aab178c113eba243a0455b436f8d308 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 3 Jul 2024 15:33:02 +0300 Subject: [PATCH 026/110] fix(diary): changeMeal fix --- .../bloc/diary_edit_bloc.dart | 29 +++++++++++++------ 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart index 1ad049d..1e8af7f 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 @@ -197,15 +197,20 @@ class DiaryEditBloc extends Bloc { 'Authorization': 'Bearer $token', }, ); + if (responseChart.statusCode == 200) { - final recommendedChartValues = jsonDecode(responseChart.body)['dailyNutritionRecommendation'].values.map((value) => value as int).toList(); - final consumedChartValues = jsonDecode(responseChart.body)['dailyNutritionIntake'].values.map((value) => value as int).toList(); + final responseBody = jsonDecode(responseChart.body); + + final recommendedChartValues = responseBody['dailyNutritionRecommendation'].values.map((value) => convertToInt(value)).toList(); + + final consumedChartValues = responseBody['dailyNutritionIntake'].values.map((value) => convertToInt(value)).toList(); + print([recommendedChartValues, consumedChartValues]); return [recommendedChartValues, consumedChartValues]; } else { emit(DiaryEditErrorState('Ошибка при декодировании данных КБЖУ')); print('fail'); - return [[], []]; // Возвращаем пустые списки вместо -1 + return [[], []]; // Return empty lists instead of -1 } } @@ -267,8 +272,6 @@ class DiaryEditBloc extends Bloc { )['dailyNutritionRecommendation']; final consumedChartValues = jsonDecode(responseChart.body)['dailyNutritionIntake']; final List meals = fillMealList(diary['meals']); - print(recommendedChartValues); - print(consumedChartValues); try { await Future( () => emit( @@ -287,9 +290,8 @@ class DiaryEditBloc extends Bloc { moodExpanded: true, moderationExpanded: false, token: token, - recommendedChartValues: recommendedChartValues.values.map((value) => value as double).toList(), - consumedChartValues: consumedChartValues.values.map((value) => value as double).toList(), - meals: diary['meals'], + recommendedChartValues: recommendedChartValues.values.map((value) => convertToInt(value)).toList(), + consumedChartValues: consumedChartValues.values.map((value) => convertToInt(value)).toList(), portions: diary['meals'][0]['portions'], photos: diary['meals'][0]['photos'], wakeupController: toTime(diary['wakeup'] ?? "09:00"), @@ -575,7 +577,6 @@ class DiaryEditBloc extends Bloc { orElse: () => null, ); int? id = event.value.id; - print(meal['photos']); DiaryEditLoadedState updatedState = currentState.copyWith( currentMeal: event.value, portions: meal['portions'], @@ -1064,3 +1065,13 @@ class DiaryEditBloc extends Bloc { ]; } } + +int convertToInt(dynamic value) { + if (value is int) { + return value; + } else if (value is double) { + return value.toInt(); + } else { + throw FormatException('Unexpected value type: ${value.runtimeType}'); + } +} -- 2.49.1 From 1b2b7646b6744fe2687ecc30ce32d8f365f14816 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 3 Jul 2024 16:39:06 +0300 Subject: [PATCH 027/110] refactor(diary): Diary, Meals, Portions and Models models --- lib/features/diary/models/diary_model.dart | 124 +++++++- .../diary/models/diary_model.freezed.dart | 282 ++++++++++++++++++ lib/features/diary/models/diary_model.g.dart | 31 ++ .../bloc/diary_edit_bloc.dart | 1 + 4 files changed, 422 insertions(+), 16 deletions(-) create mode 100644 lib/features/diary/models/diary_model.freezed.dart create mode 100644 lib/features/diary/models/diary_model.g.dart diff --git a/lib/features/diary/models/diary_model.dart b/lib/features/diary/models/diary_model.dart index 63aaefc..84832f1 100644 --- a/lib/features/diary/models/diary_model.dart +++ b/lib/features/diary/models/diary_model.dart @@ -1,24 +1,116 @@ -/*import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; part 'diary_model.freezed.dart'; part 'diary_model.g.dart'; @freezed class DiaryModel with _$DiaryModel { - const factory DiaryModel({ - required int id, - required String state, - String? image, - required String description, - String? author_name, - String? author_avatar_path, - @JsonKey(name: "youtube_url") required String youtubeUrl, - @JsonKey(name: "created_at") required DateTime createdAt, - @JsonKey(name: "updated_at") required DateTime updatedAt, - required String title, - }) = _DiaryModel; + const factory DiaryModel( + {required int id, + required DateTime date, + required DateTime wakeup, + required DateTime retire, + required int closed, + required String comment, + required List meals}) = _DiaryModel; - factory DiaryModel.fromJson(Map json) => - _$DiaryModelFromJson(json); + factory DiaryModel.fromJson(Map json) => _$DiaryModelFromJson(json); +} + +class Meals { + int? id; + String? time; + int? type; + int? satiety; + int? mood; + List? portions; + List? photos; + + Meals({this.id, this.time, this.type, this.satiety, this.mood, this.portions, this.photos}); + + Meals.fromJson(Map json) { + List portions = []; + List photos = []; + id = json['id']; + time = json['time']; + type = json['type']; + satiety = json['satiety']; + mood = json['mood']; + if (json['portions'] != null) { + json['portions'].forEach((v) { + portions.add(new Portions.fromJson(v)); + }); + } + if (json['photos'] != null) { + json['photos'].forEach((v) { + photos.add(new Photos.fromJson(v)); + }); + } + } + + Map toJson() { + final Map data = new Map(); + data['id'] = this.id; + data['time'] = this.time; + data['type'] = this.type; + data['satiety'] = this.satiety; + data['mood'] = this.mood; + if (this.portions != null) { + data['portions'] = this.portions?.map((v) => v.toJson()).toList(); + } + if (this.photos != null) { + data['photos'] = this.photos?.map((v) => v.toJson()).toList(); + } + return data; + } +} + +class Portions { + int? id; + String? productName; + int? quantity; + String? portion; + + Portions({this.id, this.productName, this.quantity, this.portion}); + + Portions.fromJson(Map json) { + id = json['id']; + productName = json['product_name']; + quantity = json['quantity']; + portion = json['portion']; + } + + Map toJson() { + final Map data = new Map(); + data['id'] = this.id; + data['product_name'] = this.productName; + data['quantity'] = this.quantity; + data['portion'] = this.portion; + return data; + } +} + +class Photos { + int? id; + String? originalName; + String? path; + int? size; + + Photos({this.id, this.originalName, this.path, this.size}); + + Photos.fromJson(Map json) { + id = json['id']; + originalName = json['original_name']; + path = json['path']; + size = json['size']; + } + + Map toJson() { + final Map data = new Map(); + data['id'] = this.id; + data['original_name'] = this.originalName; + data['path'] = this.path; + data['size'] = this.size; + return data; + } } -*/ \ No newline at end of file diff --git a/lib/features/diary/models/diary_model.freezed.dart b/lib/features/diary/models/diary_model.freezed.dart new file mode 100644 index 0000000..5ede010 --- /dev/null +++ b/lib/features/diary/models/diary_model.freezed.dart @@ -0,0 +1,282 @@ +// 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 'diary_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'); + +DiaryModel _$DiaryModelFromJson(Map json) { + return _DiaryModel.fromJson(json); +} + +/// @nodoc +mixin _$DiaryModel { + int get id => throw _privateConstructorUsedError; + DateTime get date => throw _privateConstructorUsedError; + DateTime get wakeup => throw _privateConstructorUsedError; + DateTime get retire => throw _privateConstructorUsedError; + int get closed => throw _privateConstructorUsedError; + String get comment => throw _privateConstructorUsedError; + List get meals => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $DiaryModelCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DiaryModelCopyWith<$Res> { + factory $DiaryModelCopyWith( + DiaryModel value, $Res Function(DiaryModel) then) = + _$DiaryModelCopyWithImpl<$Res, DiaryModel>; + @useResult + $Res call( + {int id, + DateTime date, + DateTime wakeup, + DateTime retire, + int closed, + String comment, + List meals}); +} + +/// @nodoc +class _$DiaryModelCopyWithImpl<$Res, $Val extends DiaryModel> + implements $DiaryModelCopyWith<$Res> { + _$DiaryModelCopyWithImpl(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 = null, + Object? date = null, + Object? wakeup = null, + Object? retire = null, + Object? closed = null, + Object? comment = null, + Object? meals = null, + }) { + return _then(_value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + date: null == date + ? _value.date + : date // ignore: cast_nullable_to_non_nullable + as DateTime, + wakeup: null == wakeup + ? _value.wakeup + : wakeup // ignore: cast_nullable_to_non_nullable + as DateTime, + retire: null == retire + ? _value.retire + : retire // ignore: cast_nullable_to_non_nullable + as DateTime, + closed: null == closed + ? _value.closed + : closed // ignore: cast_nullable_to_non_nullable + as int, + comment: null == comment + ? _value.comment + : comment // ignore: cast_nullable_to_non_nullable + as String, + meals: null == meals + ? _value.meals + : meals // ignore: cast_nullable_to_non_nullable + as List, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$DiaryModelImplCopyWith<$Res> + implements $DiaryModelCopyWith<$Res> { + factory _$$DiaryModelImplCopyWith( + _$DiaryModelImpl value, $Res Function(_$DiaryModelImpl) then) = + __$$DiaryModelImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {int id, + DateTime date, + DateTime wakeup, + DateTime retire, + int closed, + String comment, + List meals}); +} + +/// @nodoc +class __$$DiaryModelImplCopyWithImpl<$Res> + extends _$DiaryModelCopyWithImpl<$Res, _$DiaryModelImpl> + implements _$$DiaryModelImplCopyWith<$Res> { + __$$DiaryModelImplCopyWithImpl( + _$DiaryModelImpl _value, $Res Function(_$DiaryModelImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? date = null, + Object? wakeup = null, + Object? retire = null, + Object? closed = null, + Object? comment = null, + Object? meals = null, + }) { + return _then(_$DiaryModelImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + date: null == date + ? _value.date + : date // ignore: cast_nullable_to_non_nullable + as DateTime, + wakeup: null == wakeup + ? _value.wakeup + : wakeup // ignore: cast_nullable_to_non_nullable + as DateTime, + retire: null == retire + ? _value.retire + : retire // ignore: cast_nullable_to_non_nullable + as DateTime, + closed: null == closed + ? _value.closed + : closed // ignore: cast_nullable_to_non_nullable + as int, + comment: null == comment + ? _value.comment + : comment // ignore: cast_nullable_to_non_nullable + as String, + meals: null == meals + ? _value._meals + : meals // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$DiaryModelImpl implements _DiaryModel { + const _$DiaryModelImpl( + {required this.id, + required this.date, + required this.wakeup, + required this.retire, + required this.closed, + required this.comment, + required final List meals}) + : _meals = meals; + + factory _$DiaryModelImpl.fromJson(Map json) => + _$$DiaryModelImplFromJson(json); + + @override + final int id; + @override + final DateTime date; + @override + final DateTime wakeup; + @override + final DateTime retire; + @override + final int closed; + @override + final String comment; + final List _meals; + @override + List get meals { + if (_meals is EqualUnmodifiableListView) return _meals; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_meals); + } + + @override + String toString() { + return 'DiaryModel(id: $id, date: $date, wakeup: $wakeup, retire: $retire, closed: $closed, comment: $comment, meals: $meals)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DiaryModelImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.date, date) || other.date == date) && + (identical(other.wakeup, wakeup) || other.wakeup == wakeup) && + (identical(other.retire, retire) || other.retire == retire) && + (identical(other.closed, closed) || other.closed == closed) && + (identical(other.comment, comment) || other.comment == comment) && + const DeepCollectionEquality().equals(other._meals, _meals)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, id, date, wakeup, retire, closed, + comment, const DeepCollectionEquality().hash(_meals)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$DiaryModelImplCopyWith<_$DiaryModelImpl> get copyWith => + __$$DiaryModelImplCopyWithImpl<_$DiaryModelImpl>(this, _$identity); + + @override + Map toJson() { + return _$$DiaryModelImplToJson( + this, + ); + } +} + +abstract class _DiaryModel implements DiaryModel { + const factory _DiaryModel( + {required final int id, + required final DateTime date, + required final DateTime wakeup, + required final DateTime retire, + required final int closed, + required final String comment, + required final List meals}) = _$DiaryModelImpl; + + factory _DiaryModel.fromJson(Map json) = + _$DiaryModelImpl.fromJson; + + @override + int get id; + @override + DateTime get date; + @override + DateTime get wakeup; + @override + DateTime get retire; + @override + int get closed; + @override + String get comment; + @override + List get meals; + @override + @JsonKey(ignore: true) + _$$DiaryModelImplCopyWith<_$DiaryModelImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/diary/models/diary_model.g.dart b/lib/features/diary/models/diary_model.g.dart new file mode 100644 index 0000000..cab25b6 --- /dev/null +++ b/lib/features/diary/models/diary_model.g.dart @@ -0,0 +1,31 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'diary_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$DiaryModelImpl _$$DiaryModelImplFromJson(Map json) => + _$DiaryModelImpl( + id: (json['id'] as num).toInt(), + date: DateTime.parse(json['date'] as String), + wakeup: DateTime.parse(json['wakeup'] as String), + retire: DateTime.parse(json['retire'] as String), + closed: (json['closed'] as num).toInt(), + comment: json['comment'] as String, + meals: (json['meals'] as List) + .map((e) => Meals.fromJson(e as Map)) + .toList(), + ); + +Map _$$DiaryModelImplToJson(_$DiaryModelImpl instance) => + { + 'id': instance.id, + 'date': instance.date.toIso8601String(), + 'wakeup': instance.wakeup.toIso8601String(), + 'retire': instance.retire.toIso8601String(), + 'closed': instance.closed, + 'comment': instance.comment, + 'meals': instance.meals, + }; 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 1e8af7f..e93f295 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 @@ -60,6 +60,7 @@ class DiaryEditBloc extends Bloc { final diary = await fetchDiaryData(token, diaryId); print("Screen load success"); if (diary is Map) { + print(diary); final String diaryDate = diary['date'] ?? DateTime.now().toString(); final chartValues = await fetchChartValues(token, diaryId, emit); if (state is DiaryEditLoadedState) { -- 2.49.1 From 4c7519ee4c348a0c300996da80fa0bb70bcd76ed Mon Sep 17 00:00:00 2001 From: alex Date: Wed, 3 Jul 2024 16:50:09 +0300 Subject: [PATCH 028/110] feat(chat): add init and dispose chat, typing info, receive a messages --- .../initialization_cubit.dart | 19 +- .../services/blog_post_service.g.dart | 6 +- .../services/blog_service.g.dart | 6 +- .../chat/models/chat_message_model.dart | 2 +- .../models/chat_message_model.freezed.dart | 32 ++-- .../chat/models/chat_message_model.g.dart | 2 +- .../chat/models/chat_messages_model.dart | 16 ++ .../models/chat_messages_model.freezed.dart | 168 ++++++++++++++++++ .../chat/models/chat_messages_model.g.dart | 21 +++ lib/features/chat/models/chat_room_model.dart | 2 - .../chat/models/chat_room_model.freezed.dart | 37 +--- .../chat/models/chat_room_model.g.dart | 4 - .../bloc/chat_room_cubit/chat_room_cubit.dart | 92 +++++++++- .../bloc/chat_room_cubit/chat_room_state.dart | 5 +- .../chat_room_state.freezed.dart | 136 ++++++++++---- .../chat/presentation/pages/chat_screen.dart | 58 ++++-- .../widgets/chat_entry_widget.dart | 2 +- .../widgets/chat_bubble_widget.dart | 29 +-- .../chat/repositories/chat_repository.dart | 18 +- lib/features/chat/services/chat_service.dart | 6 +- .../chat/services/chat_service.g.dart | 39 +++- .../feed/services/feed_service.g.dart | 6 +- lib/locator_service.dart | 3 +- lib/main.dart | 2 +- .../app_navigation_screen.dart | 3 - lib/theme/theme_helper.dart | 2 +- pubspec.yaml | 4 +- 27 files changed, 553 insertions(+), 167 deletions(-) create mode 100644 lib/features/chat/models/chat_messages_model.dart create mode 100644 lib/features/chat/models/chat_messages_model.freezed.dart create mode 100644 lib/features/chat/models/chat_messages_model.g.dart diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index 7ab6863..4db6546 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -3,29 +3,13 @@ import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_state.dart'; import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; -import 'package:dio/dio.dart'; class InitializationCubit extends Cubit { final ChatRepository chatRepository; InitializationCubit({required this.chatRepository}) : super(const InitializationState.loading()); - - // final myPrivateChannel = client.privateChannel( - // 'private-new-chat-messages.${wsUrl.userId}', - // authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( - // authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), - // headers: { - // 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', - // }, - // ), - // ); - // myPrivateChannel.subscribe(); - // myPrivateChannel.bindToAll().listen((event) { - // print(event.name); - // }); - - runInitialization() async { + Future runInitialization() async { try { await TokenStorage.haveTokenInStorage(); final wsUrl = await chatRepository.getWebsocket(); @@ -63,6 +47,7 @@ class InitializationCubit extends Cubit { emit(InitializationState.error( errorMessage: e.toString(), )); + rethrow; } } } 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 7af4607..c99e785 100644 --- a/lib/features/blog_post/services/blog_post_service.g.dart +++ b/lib/features/blog_post/services/blog_post_service.g.dart @@ -6,7 +6,7 @@ part of 'blog_post_service.dart'; // RetrofitGenerator // ************************************************************************** -// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers +// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers,unused_element class _BlogPostService implements BlogPostService { _BlogPostService( @@ -41,8 +41,8 @@ class _BlogPostService implements BlogPostService { _dio.options.baseUrl, baseUrl, )))); - final value = BlogPostModel.fromJson(_result.data!); - return value; + final _value = BlogPostModel.fromJson(_result.data!); + return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { 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 eef2fc9..71ca211 100644 --- a/lib/features/blog_post_create/services/blog_service.g.dart +++ b/lib/features/blog_post_create/services/blog_service.g.dart @@ -6,7 +6,7 @@ part of 'blog_service.dart'; // RetrofitGenerator // ************************************************************************** -// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers +// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers,unused_element class _BlogService implements BlogService { _BlogService( @@ -42,8 +42,8 @@ class _BlogService implements BlogService { _dio.options.baseUrl, baseUrl, )))); - final value = BlogPostCreateCredentialsModel.fromJson(_result.data!); - return value; + final _value = BlogPostCreateCredentialsModel.fromJson(_result.data!); + return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { diff --git a/lib/features/chat/models/chat_message_model.dart b/lib/features/chat/models/chat_message_model.dart index 220df3b..00e17f5 100644 --- a/lib/features/chat/models/chat_message_model.dart +++ b/lib/features/chat/models/chat_message_model.dart @@ -9,7 +9,7 @@ class ChatMessageModel with _$ChatMessageModel { const factory ChatMessageModel({ required int id, required String data, - @JsonKey(name: 'media_data') required List mediaData, + @JsonKey(name: 'media_data') required List? mediaData, @JsonKey(name: 'author_id') required int authorId, @JsonKey(name: 'updated_at') required String updatedAt, }) = _ChatMessageModel; diff --git a/lib/features/chat/models/chat_message_model.freezed.dart b/lib/features/chat/models/chat_message_model.freezed.dart index 6185608..76a91cb 100644 --- a/lib/features/chat/models/chat_message_model.freezed.dart +++ b/lib/features/chat/models/chat_message_model.freezed.dart @@ -23,7 +23,7 @@ mixin _$ChatMessageModel { int get id => throw _privateConstructorUsedError; String get data => throw _privateConstructorUsedError; @JsonKey(name: 'media_data') - List get mediaData => throw _privateConstructorUsedError; + List? get mediaData => throw _privateConstructorUsedError; @JsonKey(name: 'author_id') int get authorId => throw _privateConstructorUsedError; @JsonKey(name: 'updated_at') @@ -44,7 +44,7 @@ abstract class $ChatMessageModelCopyWith<$Res> { $Res call( {int id, String data, - @JsonKey(name: 'media_data') List mediaData, + @JsonKey(name: 'media_data') List? mediaData, @JsonKey(name: 'author_id') int authorId, @JsonKey(name: 'updated_at') String updatedAt}); } @@ -64,7 +64,7 @@ class _$ChatMessageModelCopyWithImpl<$Res, $Val extends ChatMessageModel> $Res call({ Object? id = null, Object? data = null, - Object? mediaData = null, + Object? mediaData = freezed, Object? authorId = null, Object? updatedAt = null, }) { @@ -77,10 +77,10 @@ class _$ChatMessageModelCopyWithImpl<$Res, $Val extends ChatMessageModel> ? _value.data : data // ignore: cast_nullable_to_non_nullable as String, - mediaData: null == mediaData + mediaData: freezed == mediaData ? _value.mediaData : mediaData // ignore: cast_nullable_to_non_nullable - as List, + as List?, authorId: null == authorId ? _value.authorId : authorId // ignore: cast_nullable_to_non_nullable @@ -104,7 +104,7 @@ abstract class _$$ChatMessageModelImplCopyWith<$Res> $Res call( {int id, String data, - @JsonKey(name: 'media_data') List mediaData, + @JsonKey(name: 'media_data') List? mediaData, @JsonKey(name: 'author_id') int authorId, @JsonKey(name: 'updated_at') String updatedAt}); } @@ -122,7 +122,7 @@ class __$$ChatMessageModelImplCopyWithImpl<$Res> $Res call({ Object? id = null, Object? data = null, - Object? mediaData = null, + Object? mediaData = freezed, Object? authorId = null, Object? updatedAt = null, }) { @@ -135,10 +135,10 @@ class __$$ChatMessageModelImplCopyWithImpl<$Res> ? _value.data : data // ignore: cast_nullable_to_non_nullable as String, - mediaData: null == mediaData + mediaData: freezed == mediaData ? _value._mediaData : mediaData // ignore: cast_nullable_to_non_nullable - as List, + as List?, authorId: null == authorId ? _value.authorId : authorId // ignore: cast_nullable_to_non_nullable @@ -157,7 +157,7 @@ class _$ChatMessageModelImpl implements _ChatMessageModel { const _$ChatMessageModelImpl( {required this.id, required this.data, - @JsonKey(name: 'media_data') required final List mediaData, + @JsonKey(name: 'media_data') required final List? mediaData, @JsonKey(name: 'author_id') required this.authorId, @JsonKey(name: 'updated_at') required this.updatedAt}) : _mediaData = mediaData; @@ -169,13 +169,15 @@ class _$ChatMessageModelImpl implements _ChatMessageModel { final int id; @override final String data; - final List _mediaData; + final List? _mediaData; @override @JsonKey(name: 'media_data') - List get mediaData { + List? get mediaData { + final value = _mediaData; + if (value == null) return null; if (_mediaData is EqualUnmodifiableListView) return _mediaData; // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_mediaData); + return EqualUnmodifiableListView(value); } @override @@ -229,7 +231,7 @@ abstract class _ChatMessageModel implements ChatMessageModel { const factory _ChatMessageModel( {required final int id, required final String data, - @JsonKey(name: 'media_data') required final List mediaData, + @JsonKey(name: 'media_data') required final List? mediaData, @JsonKey(name: 'author_id') required final int authorId, @JsonKey(name: 'updated_at') required final String updatedAt}) = _$ChatMessageModelImpl; @@ -243,7 +245,7 @@ abstract class _ChatMessageModel implements ChatMessageModel { String get data; @override @JsonKey(name: 'media_data') - List get mediaData; + List? get mediaData; @override @JsonKey(name: 'author_id') int get authorId; diff --git a/lib/features/chat/models/chat_message_model.g.dart b/lib/features/chat/models/chat_message_model.g.dart index 8b28b74..3a8d182 100644 --- a/lib/features/chat/models/chat_message_model.g.dart +++ b/lib/features/chat/models/chat_message_model.g.dart @@ -11,7 +11,7 @@ _$ChatMessageModelImpl _$$ChatMessageModelImplFromJson( _$ChatMessageModelImpl( id: (json['id'] as num).toInt(), data: json['data'] as String, - mediaData: json['media_data'] as List, + mediaData: json['media_data'] as List?, authorId: (json['author_id'] as num).toInt(), updatedAt: json['updated_at'] as String, ); diff --git a/lib/features/chat/models/chat_messages_model.dart b/lib/features/chat/models/chat_messages_model.dart new file mode 100644 index 0000000..fbf6fc0 --- /dev/null +++ b/lib/features/chat/models/chat_messages_model.dart @@ -0,0 +1,16 @@ +import 'package:eatvio_app/features/chat/models/chat_message_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'chat_messages_model.freezed.dart'; + +part 'chat_messages_model.g.dart'; + +@freezed +class ChatMessagesModel with _$ChatMessagesModel { + const factory ChatMessagesModel({ + @JsonKey(name: 'data') + required List messagesList, + }) = _ChatMessagesModel; + + factory ChatMessagesModel.fromJson(Map json) => _$ChatMessagesModelFromJson(json); +} diff --git a/lib/features/chat/models/chat_messages_model.freezed.dart b/lib/features/chat/models/chat_messages_model.freezed.dart new file mode 100644 index 0000000..594498a --- /dev/null +++ b/lib/features/chat/models/chat_messages_model.freezed.dart @@ -0,0 +1,168 @@ +// 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 'chat_messages_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'); + +ChatMessagesModel _$ChatMessagesModelFromJson(Map json) { + return _ChatMessagesModel.fromJson(json); +} + +/// @nodoc +mixin _$ChatMessagesModel { + @JsonKey(name: 'data') + List get messagesList => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $ChatMessagesModelCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $ChatMessagesModelCopyWith<$Res> { + factory $ChatMessagesModelCopyWith( + ChatMessagesModel value, $Res Function(ChatMessagesModel) then) = + _$ChatMessagesModelCopyWithImpl<$Res, ChatMessagesModel>; + @useResult + $Res call({@JsonKey(name: 'data') List messagesList}); +} + +/// @nodoc +class _$ChatMessagesModelCopyWithImpl<$Res, $Val extends ChatMessagesModel> + implements $ChatMessagesModelCopyWith<$Res> { + _$ChatMessagesModelCopyWithImpl(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? messagesList = null, + }) { + return _then(_value.copyWith( + messagesList: null == messagesList + ? _value.messagesList + : messagesList // ignore: cast_nullable_to_non_nullable + as List, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$ChatMessagesModelImplCopyWith<$Res> + implements $ChatMessagesModelCopyWith<$Res> { + factory _$$ChatMessagesModelImplCopyWith(_$ChatMessagesModelImpl value, + $Res Function(_$ChatMessagesModelImpl) then) = + __$$ChatMessagesModelImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({@JsonKey(name: 'data') List messagesList}); +} + +/// @nodoc +class __$$ChatMessagesModelImplCopyWithImpl<$Res> + extends _$ChatMessagesModelCopyWithImpl<$Res, _$ChatMessagesModelImpl> + implements _$$ChatMessagesModelImplCopyWith<$Res> { + __$$ChatMessagesModelImplCopyWithImpl(_$ChatMessagesModelImpl _value, + $Res Function(_$ChatMessagesModelImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? messagesList = null, + }) { + return _then(_$ChatMessagesModelImpl( + messagesList: null == messagesList + ? _value._messagesList + : messagesList // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$ChatMessagesModelImpl implements _ChatMessagesModel { + const _$ChatMessagesModelImpl( + {@JsonKey(name: 'data') + required final List messagesList}) + : _messagesList = messagesList; + + factory _$ChatMessagesModelImpl.fromJson(Map json) => + _$$ChatMessagesModelImplFromJson(json); + + final List _messagesList; + @override + @JsonKey(name: 'data') + List get messagesList { + if (_messagesList is EqualUnmodifiableListView) return _messagesList; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_messagesList); + } + + @override + String toString() { + return 'ChatMessagesModel(messagesList: $messagesList)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ChatMessagesModelImpl && + const DeepCollectionEquality() + .equals(other._messagesList, _messagesList)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_messagesList)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => + __$$ChatMessagesModelImplCopyWithImpl<_$ChatMessagesModelImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$ChatMessagesModelImplToJson( + this, + ); + } +} + +abstract class _ChatMessagesModel implements ChatMessagesModel { + const factory _ChatMessagesModel( + {@JsonKey(name: 'data') + required final List messagesList}) = + _$ChatMessagesModelImpl; + + factory _ChatMessagesModel.fromJson(Map json) = + _$ChatMessagesModelImpl.fromJson; + + @override + @JsonKey(name: 'data') + List get messagesList; + @override + @JsonKey(ignore: true) + _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/chat/models/chat_messages_model.g.dart b/lib/features/chat/models/chat_messages_model.g.dart new file mode 100644 index 0000000..80f7874 --- /dev/null +++ b/lib/features/chat/models/chat_messages_model.g.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'chat_messages_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$ChatMessagesModelImpl _$$ChatMessagesModelImplFromJson( + Map json) => + _$ChatMessagesModelImpl( + messagesList: (json['data'] as List) + .map((e) => ChatMessageModel.fromJson(e as Map)) + .toList(), + ); + +Map _$$ChatMessagesModelImplToJson( + _$ChatMessagesModelImpl instance) => + { + 'data': instance.messagesList, + }; diff --git a/lib/features/chat/models/chat_room_model.dart b/lib/features/chat/models/chat_room_model.dart index 1fa5afe..0196b49 100644 --- a/lib/features/chat/models/chat_room_model.dart +++ b/lib/features/chat/models/chat_room_model.dart @@ -1,4 +1,3 @@ -import 'package:eatvio_app/features/chat/models/chat_message_model.dart'; import 'package:eatvio_app/features/chat/models/chat_room_settings_model.dart'; import 'package:eatvio_app/features/chat/models/chat_user_model.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; @@ -12,7 +11,6 @@ class ChatRoomModel with _$ChatRoomModel { const factory ChatRoomModel({ required String id, @JsonKey(name: 'chat_room_setting') required ChatRoomSettingsModel chatRoomSettings, - required List messages, required Map users, }) = _ChatRoomModel; diff --git a/lib/features/chat/models/chat_room_model.freezed.dart b/lib/features/chat/models/chat_room_model.freezed.dart index b8b4ce4..5a0b6e6 100644 --- a/lib/features/chat/models/chat_room_model.freezed.dart +++ b/lib/features/chat/models/chat_room_model.freezed.dart @@ -24,7 +24,6 @@ mixin _$ChatRoomModel { @JsonKey(name: 'chat_room_setting') ChatRoomSettingsModel get chatRoomSettings => throw _privateConstructorUsedError; - List get messages => throw _privateConstructorUsedError; Map get users => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @@ -43,7 +42,6 @@ abstract class $ChatRoomModelCopyWith<$Res> { {String id, @JsonKey(name: 'chat_room_setting') ChatRoomSettingsModel chatRoomSettings, - List messages, Map users}); $ChatRoomSettingsModelCopyWith<$Res> get chatRoomSettings; @@ -64,7 +62,6 @@ class _$ChatRoomModelCopyWithImpl<$Res, $Val extends ChatRoomModel> $Res call({ Object? id = null, Object? chatRoomSettings = null, - Object? messages = null, Object? users = null, }) { return _then(_value.copyWith( @@ -76,10 +73,6 @@ class _$ChatRoomModelCopyWithImpl<$Res, $Val extends ChatRoomModel> ? _value.chatRoomSettings : chatRoomSettings // ignore: cast_nullable_to_non_nullable as ChatRoomSettingsModel, - messages: null == messages - ? _value.messages - : messages // ignore: cast_nullable_to_non_nullable - as List, users: null == users ? _value.users : users // ignore: cast_nullable_to_non_nullable @@ -109,7 +102,6 @@ abstract class _$$ChatRoomModelImplCopyWith<$Res> {String id, @JsonKey(name: 'chat_room_setting') ChatRoomSettingsModel chatRoomSettings, - List messages, Map users}); @override @@ -129,7 +121,6 @@ class __$$ChatRoomModelImplCopyWithImpl<$Res> $Res call({ Object? id = null, Object? chatRoomSettings = null, - Object? messages = null, Object? users = null, }) { return _then(_$ChatRoomModelImpl( @@ -141,10 +132,6 @@ class __$$ChatRoomModelImplCopyWithImpl<$Res> ? _value.chatRoomSettings : chatRoomSettings // ignore: cast_nullable_to_non_nullable as ChatRoomSettingsModel, - messages: null == messages - ? _value._messages - : messages // ignore: cast_nullable_to_non_nullable - as List, users: null == users ? _value._users : users // ignore: cast_nullable_to_non_nullable @@ -159,10 +146,8 @@ class _$ChatRoomModelImpl implements _ChatRoomModel { const _$ChatRoomModelImpl( {required this.id, @JsonKey(name: 'chat_room_setting') required this.chatRoomSettings, - required final List messages, required final Map users}) - : _messages = messages, - _users = users; + : _users = users; factory _$ChatRoomModelImpl.fromJson(Map json) => _$$ChatRoomModelImplFromJson(json); @@ -172,14 +157,6 @@ class _$ChatRoomModelImpl implements _ChatRoomModel { @override @JsonKey(name: 'chat_room_setting') final ChatRoomSettingsModel chatRoomSettings; - final List _messages; - @override - List get messages { - if (_messages is EqualUnmodifiableListView) return _messages; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_messages); - } - final Map _users; @override Map get users { @@ -190,7 +167,7 @@ class _$ChatRoomModelImpl implements _ChatRoomModel { @override String toString() { - return 'ChatRoomModel(id: $id, chatRoomSettings: $chatRoomSettings, messages: $messages, users: $users)'; + return 'ChatRoomModel(id: $id, chatRoomSettings: $chatRoomSettings, users: $users)'; } @override @@ -201,17 +178,12 @@ class _$ChatRoomModelImpl implements _ChatRoomModel { (identical(other.id, id) || other.id == id) && (identical(other.chatRoomSettings, chatRoomSettings) || other.chatRoomSettings == chatRoomSettings) && - const DeepCollectionEquality().equals(other._messages, _messages) && const DeepCollectionEquality().equals(other._users, _users)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash( - runtimeType, - id, - chatRoomSettings, - const DeepCollectionEquality().hash(_messages), + int get hashCode => Object.hash(runtimeType, id, chatRoomSettings, const DeepCollectionEquality().hash(_users)); @JsonKey(ignore: true) @@ -233,7 +205,6 @@ abstract class _ChatRoomModel implements ChatRoomModel { {required final String id, @JsonKey(name: 'chat_room_setting') required final ChatRoomSettingsModel chatRoomSettings, - required final List messages, required final Map users}) = _$ChatRoomModelImpl; factory _ChatRoomModel.fromJson(Map json) = @@ -245,8 +216,6 @@ abstract class _ChatRoomModel implements ChatRoomModel { @JsonKey(name: 'chat_room_setting') ChatRoomSettingsModel get chatRoomSettings; @override - List get messages; - @override Map get users; @override @JsonKey(ignore: true) diff --git a/lib/features/chat/models/chat_room_model.g.dart b/lib/features/chat/models/chat_room_model.g.dart index 4ab3867..68d3195 100644 --- a/lib/features/chat/models/chat_room_model.g.dart +++ b/lib/features/chat/models/chat_room_model.g.dart @@ -11,9 +11,6 @@ _$ChatRoomModelImpl _$$ChatRoomModelImplFromJson(Map json) => id: json['id'] as String, chatRoomSettings: ChatRoomSettingsModel.fromJson( json['chat_room_setting'] as Map), - messages: (json['messages'] as List) - .map((e) => ChatMessageModel.fromJson(e as Map)) - .toList(), users: (json['users'] as Map).map( (k, e) => MapEntry(k, ChatUserModel.fromJson(e as Map)), @@ -24,6 +21,5 @@ Map _$$ChatRoomModelImplToJson(_$ChatRoomModelImpl instance) => { 'id': instance.id, 'chat_room_setting': instance.chatRoomSettings, - 'messages': instance.messages, 'users': instance.users, }; diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart index f66069e..aff8fa8 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart @@ -1,20 +1,108 @@ +import 'dart:convert'; + +import 'package:dart_pusher_channels/dart_pusher_channels.dart'; +import 'package:easy_debounce/easy_debounce.dart'; +import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.dart'; +import 'package:eatvio_app/core/initialization_cubit/initialization_state.dart'; +import 'package:eatvio_app/core/token_storage.dart'; +import 'package:eatvio_app/features/chat/models/chat_message_model.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; +import 'package:eatvio_app/locator_service.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class ChatRoomCubit extends Cubit { final ChatRepository chatRepository; + late final PusherChannelsClient client; + late final PrivateChannel privateChannel; + ChatRoomCubit({ required this.chatRepository, }) : super(ChatRoomState.loading()); initChat(String chatId) async { try { - final chatRoomModel = await chatRepository.getChatRoom(chatId); - emit(ChatRoomState.loaded(chatRoomModel: chatRoomModel)); + final chatRoom = await chatRepository.getChatRoom(chatId); + + final chatMessages = await chatRepository.getChatMessages(chatId); + + final initCubit = sl(); + + if (initCubit.state is InitializationStateSuccess) { + await subscribeToChatChannel(initCubit: initCubit, chatId: chatId); + } else { + await initCubit.runInitialization(); + await subscribeToChatChannel(initCubit: initCubit, chatId: chatId); + } + + emit(ChatRoomState.loaded( + chatRoom: chatRoom, + chatMessages: chatMessages, + isTyping: false, + )); } catch (e) { emit(ChatRoomState.error(errorMessage: 'Ошибка получеия данных')); } } + + Future subscribeToChatChannel({ + required InitializationCubit initCubit, + required String chatId, + }) async { + client = (initCubit.state as InitializationStateSuccess).client; + + privateChannel = await client.privateChannel( + 'private-direct-chat.$chatId', + authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( + authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), + headers: { + 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', + }, + ), + ); + + privateChannel.subscribe(); + + privateChannel.bind('App\\Events\\ChatMessageUpdated').listen((event) { + List messagesList = [ + ChatMessageModel.fromJson(jsonDecode(event.data)['message']), + ...(state as ChatRoomStateLoaded).chatMessages.messagesList, + ]; + emit( + ChatRoomState.loaded( + chatRoom: (state as ChatRoomStateLoaded).chatRoom, + chatMessages: (state as ChatRoomStateLoaded).chatMessages.copyWith(messagesList: messagesList), + isTyping: (state as ChatRoomStateLoaded).isTyping, + ), + ); + }); + + privateChannel.bind('client-typing').listen((event) { + emit( + ChatRoomState.loaded( + chatRoom: (state as ChatRoomStateLoaded).chatRoom, + chatMessages: (state as ChatRoomStateLoaded).chatMessages, + isTyping: true, + ), + ); + EasyDebounce.debounce( + 'client-typing', + Duration(seconds: 3), + () => emit( + ChatRoomState.loaded( + chatRoom: (state as ChatRoomStateLoaded).chatRoom, + chatMessages: (state as ChatRoomStateLoaded).chatMessages, + isTyping: false, + ), + ), + ); + }); + } + + @override + Future close() async { + privateChannel.unsubscribe(); + super.close(); + } } diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart index 89184a6..dbf8238 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart @@ -1,3 +1,4 @@ +import 'package:eatvio_app/features/chat/models/chat_messages_model.dart'; import 'package:eatvio_app/features/chat/models/chat_room_model.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; @@ -10,7 +11,9 @@ abstract class ChatRoomState with _$ChatRoomState { const factory ChatRoomState.loading() = ChatRoomStateLoading; const factory ChatRoomState.loaded({ - required ChatRoomModel chatRoomModel, + required ChatRoomModel chatRoom, + required ChatMessagesModel chatMessages, + required bool isTyping, }) = ChatRoomStateLoaded; const factory ChatRoomState.error({ diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart index 5bd9ae8..4831ccc 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart @@ -20,7 +20,9 @@ mixin _$ChatRoomState { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoomModel) loaded, + required TResult Function(ChatRoomModel chatRoom, + ChatMessagesModel chatMessages, bool isTyping) + loaded, required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; @@ -28,7 +30,9 @@ mixin _$ChatRoomState { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoomModel)? loaded, + TResult? Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, + bool isTyping)? + loaded, TResult? Function(String errorMessage)? error, }) => throw _privateConstructorUsedError; @@ -36,7 +40,9 @@ mixin _$ChatRoomState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoomModel)? loaded, + TResult Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, + bool isTyping)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) => @@ -126,7 +132,9 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoomModel) loaded, + required TResult Function(ChatRoomModel chatRoom, + ChatMessagesModel chatMessages, bool isTyping) + loaded, required TResult Function(String errorMessage) error, }) { return $default(); @@ -137,7 +145,9 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoomModel)? loaded, + TResult? Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, + bool isTyping)? + loaded, TResult? Function(String errorMessage)? error, }) { return $default?.call(); @@ -148,7 +158,9 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoomModel)? loaded, + TResult Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, + bool isTyping)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -241,7 +253,9 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoomModel) loaded, + required TResult Function(ChatRoomModel chatRoom, + ChatMessagesModel chatMessages, bool isTyping) + loaded, required TResult Function(String errorMessage) error, }) { return loading(); @@ -252,7 +266,9 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoomModel)? loaded, + TResult? Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, + bool isTyping)? + loaded, TResult? Function(String errorMessage)? error, }) { return loading?.call(); @@ -263,7 +279,9 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoomModel)? loaded, + TResult Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, + bool isTyping)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -321,9 +339,11 @@ abstract class _$$ChatRoomStateLoadedImplCopyWith<$Res> { $Res Function(_$ChatRoomStateLoadedImpl) then) = __$$ChatRoomStateLoadedImplCopyWithImpl<$Res>; @useResult - $Res call({ChatRoomModel chatRoomModel}); + $Res call( + {ChatRoomModel chatRoom, ChatMessagesModel chatMessages, bool isTyping}); - $ChatRoomModelCopyWith<$Res> get chatRoomModel; + $ChatRoomModelCopyWith<$Res> get chatRoom; + $ChatMessagesModelCopyWith<$Res> get chatMessages; } /// @nodoc @@ -337,21 +357,39 @@ class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> @pragma('vm:prefer-inline') @override $Res call({ - Object? chatRoomModel = null, + Object? chatRoom = null, + Object? chatMessages = null, + Object? isTyping = null, }) { return _then(_$ChatRoomStateLoadedImpl( - chatRoomModel: null == chatRoomModel - ? _value.chatRoomModel - : chatRoomModel // ignore: cast_nullable_to_non_nullable + chatRoom: null == chatRoom + ? _value.chatRoom + : chatRoom // ignore: cast_nullable_to_non_nullable as ChatRoomModel, + chatMessages: null == chatMessages + ? _value.chatMessages + : chatMessages // ignore: cast_nullable_to_non_nullable + as ChatMessagesModel, + isTyping: null == isTyping + ? _value.isTyping + : isTyping // ignore: cast_nullable_to_non_nullable + as bool, )); } @override @pragma('vm:prefer-inline') - $ChatRoomModelCopyWith<$Res> get chatRoomModel { - return $ChatRoomModelCopyWith<$Res>(_value.chatRoomModel, (value) { - return _then(_value.copyWith(chatRoomModel: value)); + $ChatRoomModelCopyWith<$Res> get chatRoom { + return $ChatRoomModelCopyWith<$Res>(_value.chatRoom, (value) { + return _then(_value.copyWith(chatRoom: value)); + }); + } + + @override + @pragma('vm:prefer-inline') + $ChatMessagesModelCopyWith<$Res> get chatMessages { + return $ChatMessagesModelCopyWith<$Res>(_value.chatMessages, (value) { + return _then(_value.copyWith(chatMessages: value)); }); } } @@ -359,14 +397,21 @@ class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> /// @nodoc class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { - const _$ChatRoomStateLoadedImpl({required this.chatRoomModel}); + const _$ChatRoomStateLoadedImpl( + {required this.chatRoom, + required this.chatMessages, + required this.isTyping}); @override - final ChatRoomModel chatRoomModel; + final ChatRoomModel chatRoom; + @override + final ChatMessagesModel chatMessages; + @override + final bool isTyping; @override String toString() { - return 'ChatRoomState.loaded(chatRoomModel: $chatRoomModel)'; + return 'ChatRoomState.loaded(chatRoom: $chatRoom, chatMessages: $chatMessages, isTyping: $isTyping)'; } @override @@ -374,12 +419,17 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateLoadedImpl && - (identical(other.chatRoomModel, chatRoomModel) || - other.chatRoomModel == chatRoomModel)); + (identical(other.chatRoom, chatRoom) || + other.chatRoom == chatRoom) && + (identical(other.chatMessages, chatMessages) || + other.chatMessages == chatMessages) && + (identical(other.isTyping, isTyping) || + other.isTyping == isTyping)); } @override - int get hashCode => Object.hash(runtimeType, chatRoomModel); + int get hashCode => + Object.hash(runtimeType, chatRoom, chatMessages, isTyping); @JsonKey(ignore: true) @override @@ -393,10 +443,12 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoomModel) loaded, + required TResult Function(ChatRoomModel chatRoom, + ChatMessagesModel chatMessages, bool isTyping) + loaded, required TResult Function(String errorMessage) error, }) { - return loaded(chatRoomModel); + return loaded(chatRoom, chatMessages, isTyping); } @override @@ -404,10 +456,12 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoomModel)? loaded, + TResult? Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, + bool isTyping)? + loaded, TResult? Function(String errorMessage)? error, }) { - return loaded?.call(chatRoomModel); + return loaded?.call(chatRoom, chatMessages, isTyping); } @override @@ -415,12 +469,14 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoomModel)? loaded, + TResult Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, + bool isTyping)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { if (loaded != null) { - return loaded(chatRoomModel); + return loaded(chatRoom, chatMessages, isTyping); } return orElse(); } @@ -465,9 +521,13 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { abstract class ChatRoomStateLoaded implements ChatRoomState { const factory ChatRoomStateLoaded( - {required final ChatRoomModel chatRoomModel}) = _$ChatRoomStateLoadedImpl; + {required final ChatRoomModel chatRoom, + required final ChatMessagesModel chatMessages, + required final bool isTyping}) = _$ChatRoomStateLoadedImpl; - ChatRoomModel get chatRoomModel; + ChatRoomModel get chatRoom; + ChatMessagesModel get chatMessages; + bool get isTyping; @JsonKey(ignore: true) _$$ChatRoomStateLoadedImplCopyWith<_$ChatRoomStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; @@ -541,7 +601,9 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoomModel) loaded, + required TResult Function(ChatRoomModel chatRoom, + ChatMessagesModel chatMessages, bool isTyping) + loaded, required TResult Function(String errorMessage) error, }) { return error(errorMessage); @@ -552,7 +614,9 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoomModel)? loaded, + TResult? Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, + bool isTyping)? + loaded, TResult? Function(String errorMessage)? error, }) { return error?.call(errorMessage); @@ -563,7 +627,9 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoomModel)? loaded, + TResult Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, + bool isTyping)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { diff --git a/lib/features/chat/presentation/pages/chat_screen.dart b/lib/features/chat/presentation/pages/chat_screen.dart index 31f431a..b25be66 100644 --- a/lib/features/chat/presentation/pages/chat_screen.dart +++ b/lib/features/chat/presentation/pages/chat_screen.dart @@ -19,6 +19,8 @@ class ChatScreen extends StatefulWidget { } class _ChatScreenState extends State { + final scrollController = ScrollController(); + Widget build(BuildContext context) { return BlocProvider( create: (BuildContext context) => sl()..initChat(widget.chatId), @@ -33,7 +35,12 @@ class _ChatScreenState extends State { } else if (state is ChatRoomStateLoaded) { return _buildChat(context, state); } else if (state is ChatRoomStateError) { - return Center(child: Text(state.errorMessage)); + return Scaffold( + appBar: AppBar(), + body: Center( + child: Text(state.errorMessage), + ), + ); } else { return Scaffold( body: Center( @@ -46,6 +53,16 @@ class _ChatScreenState extends State { ); } + void setupScrollController(BuildContext context) { + scrollController.addListener(() { + if (scrollController.position.atEdge) { + if (scrollController.position.pixels != 0) { + context.read(); + } + } + }); + } + _buildChat(BuildContext context, ChatRoomStateLoaded state) { mediaQueryData = MediaQuery.of(context); return Scaffold( @@ -68,7 +85,7 @@ class _ChatScreenState extends State { shape: BoxShape.circle, ), child: Text( - state.chatRoomModel.users['to_chat_user']!.name.split(' ').first[0] + state.chatRoomModel.users['to_chat_user']!.name.split(' ')[1][0], + state.chatRoom.users['to_chat_user']!.name.split(' ').first[0] + state.chatRoom.users['to_chat_user']!.name.split(' ')[1][0], style: TextStyle( color: Color(0xFF7F9CF5), fontWeight: FontWeight.w400, @@ -77,11 +94,27 @@ class _ChatScreenState extends State { ), ), SizedBox(width: 16), - Text( - state.chatRoomModel.users['to_chat_user']!.name, - style: CustomTextStyles.titleSmallBold.copyWith( - color: PrimaryColors().blueGray800, - ), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + state.chatRoom.users['to_chat_user']!.name, + style: CustomTextStyles.titleSmallBold.copyWith( + color: PrimaryColors().blueGray800, + ), + ), + AnimatedCrossFade( + firstChild: Text( + 'Печатает...', + style: CustomTextStyles.bodySmallMulishPrimary, + ), + firstCurve: Curves.easeIn, + secondCurve: Curves.easeOut, + secondChild: const SizedBox.shrink(), + crossFadeState: state.isTyping ? CrossFadeState.showFirst : CrossFadeState.showSecond, + duration: Duration(milliseconds: 150), + ), + ], ), ], ), @@ -95,6 +128,8 @@ class _ChatScreenState extends State { color: Color(0xFFF0F2F5), width: double.maxFinite, child: CustomScrollView( + physics: BouncingScrollPhysics(), + controller: scrollController, reverse: true, slivers: [ SliverPadding( @@ -102,12 +137,11 @@ class _ChatScreenState extends State { sliver: SliverList( delegate: SliverChildBuilderDelegate( (context, index) => ChatBubbleWidget( - text: state.chatRoomModel.messages[state.chatRoomModel.messages.length - index - 1].data, - isCurrentUser: state.chatRoomModel.users['to_chat_user']!.id != - state.chatRoomModel.messages[state.chatRoomModel.messages.length - index - 1].authorId, - mediaData: state.chatRoomModel.messages[state.chatRoomModel.messages.length - index - 1].mediaData, + text: state.chatMessages.messagesList[index].data.trim(), + isCurrentUser: state.chatRoom.users['to_chat_user']!.id != state.chatMessages.messagesList[index].authorId, + mediaData: state.chatMessages.messagesList[index].mediaData ?? [], ), - childCount: state.chatRoomModel.messages.length, + childCount: state.chatMessages.messagesList.length, ), ), ), 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 1a8e34a..4836f94 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 @@ -80,7 +80,7 @@ class ChatEntryWidget extends StatelessWidget { ), SizedBox(height: 6.v), Text( - chatEntryObj.greetingText!, + chatEntryObj.greetingText!.trim(), style: CustomTextStyles.bodyMediumBluegray800, ), ], diff --git a/lib/features/chat/presentation/widgets/chat_bubble_widget.dart b/lib/features/chat/presentation/widgets/chat_bubble_widget.dart index 39a1325..6f9e938 100644 --- a/lib/features/chat/presentation/widgets/chat_bubble_widget.dart +++ b/lib/features/chat/presentation/widgets/chat_bubble_widget.dart @@ -11,12 +11,12 @@ class ChatBubbleWidget extends StatelessWidget { super.key, required this.text, required this.isCurrentUser, - this.mediaData, + required this.mediaData, }); final String text; final bool isCurrentUser; - final List? mediaData; + final List mediaData; @override Widget build(BuildContext context) { @@ -32,23 +32,24 @@ class ChatBubbleWidget extends StatelessWidget { child: Padding( padding: const EdgeInsets.all(12), child: Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ - if (mediaData != null) + if (mediaData.isNotEmpty) CustomScrollView( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), slivers: [ SliverList.separated( itemBuilder: (BuildContext context, int index) { - if (!mediaData![index].toString().contains('.png') && - !mediaData![index].toString().contains('.jpg') && - !mediaData![index].toString().contains('.jpeg')) { + if (!mediaData[index].toString().contains('.png') && + !mediaData[index].toString().contains('.jpg') && + !mediaData[index].toString().contains('.jpeg')) { return ListTile( contentPadding: EdgeInsets.zero, horizontalTitleGap: 8, onTap: () async { - if (!await launchUrl(Uri.parse(dotenv.env['STORAGE_URL']! + mediaData![index].toString()))) { - throw Exception('Could not launch ${mediaData![index].toString()}'); + if (!await launchUrl(Uri.parse(dotenv.env['STORAGE_URL']! + mediaData[index].toString()))) { + throw Exception('Could not launch ${mediaData[index].toString()}'); } }, leading: Icon( @@ -60,7 +61,7 @@ class ChatBubbleWidget extends StatelessWidget { color: Color(0xFF2F80ED), ), title: Text( - mediaData![index].toString().replaceAll('chat_files/', ''), + mediaData[index].toString().replaceAll('chat_files/', ''), maxLines: 2, style: TextStyle( color: Color(0xFF323F4B), @@ -74,29 +75,29 @@ class ChatBubbleWidget extends StatelessWidget { onTap: () { context.pushTransparentRoute( PhotoViewScreen( - imageUrls: mediaData!.map((e) => dotenv.env['STORAGE_URL']! + e.toString()).toList(), + imageUrls: mediaData.map((e) => dotenv.env['STORAGE_URL']! + e.toString()).toList(), index: index, ), ); }, child: Hero( - tag: dotenv.env['STORAGE_URL']! + '${mediaData![index]}', + tag: dotenv.env['STORAGE_URL']! + '${mediaData[index]}', transitionOnUserGestures: true, child: ClipRRect( borderRadius: BorderRadiusStyle.roundedBorder8, child: CachedNetworkImage( - imageUrl: dotenv.env['STORAGE_URL']! + '${mediaData![index]}', + imageUrl: dotenv.env['STORAGE_URL']! + '${mediaData[index]}', ), ), ), ); }, separatorBuilder: (BuildContext context, int index) => const SizedBox(height: 8), - itemCount: mediaData!.length, + itemCount: mediaData.length, ), ], ), - if (mediaData!.length > 0 && text.isNotEmpty) SizedBox(height: 8), + if (mediaData.length > 0 && text.isNotEmpty) SizedBox(height: 8), if (text.isNotEmpty) Text( text, diff --git a/lib/features/chat/repositories/chat_repository.dart b/lib/features/chat/repositories/chat_repository.dart index 137aa87..38383f2 100644 --- a/lib/features/chat/repositories/chat_repository.dart +++ b/lib/features/chat/repositories/chat_repository.dart @@ -1,3 +1,4 @@ +import 'package:eatvio_app/features/chat/models/chat_messages_model.dart'; import 'package:eatvio_app/features/chat/models/chat_room_model.dart'; import 'package:eatvio_app/features/chat/models/websocket_info_model.dart'; import 'package:eatvio_app/features/chat/services/chat_service.dart'; @@ -9,23 +10,30 @@ class ChatRepository { required this.chatService, }); - /// TODO use "dartz" package because need Either for error handling Future getChatRoom(String chatId) async { try { - return (await chatService.getChatRoomModel(chatId))['chatRoom']!; + return (await chatService.getChatRoom(chatId))['chatRoom']!; } catch (e) { print(e); - throw (e); + rethrow; + } + } + + Future getChatMessages(String chatId) async { + try { + return (await chatService.getChatMessages(chatId)); + } catch (e) { + print(e); + rethrow; } } - /// TODO use "dartz" package because need Either for error handling Future getWebsocket() async { try { return (await chatService.getWebsocket()); } catch (e) { print(e); - throw (e); + rethrow; } } } diff --git a/lib/features/chat/services/chat_service.dart b/lib/features/chat/services/chat_service.dart index 5b27ccf..3dd4a12 100644 --- a/lib/features/chat/services/chat_service.dart +++ b/lib/features/chat/services/chat_service.dart @@ -1,3 +1,4 @@ +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'; @@ -10,7 +11,10 @@ abstract class ChatService { factory ChatService(Dio dio, {String baseUrl}) = _ChatService; @GET('/chat/show/{id}') - Future> getChatRoomModel(@Path() String id); + Future> getChatRoom(@Path() String id); + + @GET('/chat/show/{id}/messages') + Future getChatMessages(@Path() String id); @GET('/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 db9fdea..f4f04d1 100644 --- a/lib/features/chat/services/chat_service.g.dart +++ b/lib/features/chat/services/chat_service.g.dart @@ -6,7 +6,7 @@ part of 'chat_service.dart'; // RetrofitGenerator // ************************************************************************** -// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers +// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers,unused_element class _ChatService implements ChatService { _ChatService( @@ -19,7 +19,7 @@ class _ChatService implements ChatService { String? baseUrl; @override - Future> getChatRoomModel(String id) async { + Future> getChatRoom(String id) async { final _extra = {}; final queryParameters = {}; final _headers = {}; @@ -41,9 +41,36 @@ class _ChatService implements ChatService { _dio.options.baseUrl, baseUrl, )))); - var value = _result.data!.map((k, dynamic v) => + var _value = _result.data!.map((k, dynamic v) => MapEntry(k, ChatRoomModel.fromJson(v as Map))); - return value; + return _value; + } + + @override + Future getChatMessages(String id) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio + .fetch>(_setStreamType(Options( + method: 'GET', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/chat/show/${id}/messages', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = ChatMessagesModel.fromJson(_result.data!); + return _value; } @override @@ -69,8 +96,8 @@ class _ChatService implements ChatService { _dio.options.baseUrl, baseUrl, )))); - final value = WebsocketInfoModel.fromJson(_result.data!); - return value; + final _value = WebsocketInfoModel.fromJson(_result.data!); + return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { diff --git a/lib/features/feed/services/feed_service.g.dart b/lib/features/feed/services/feed_service.g.dart index 6184cfb..39b15fb 100644 --- a/lib/features/feed/services/feed_service.g.dart +++ b/lib/features/feed/services/feed_service.g.dart @@ -6,7 +6,7 @@ part of 'feed_service.dart'; // RetrofitGenerator // ************************************************************************** -// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers +// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers,unused_element class _FeedService implements FeedService { _FeedService( @@ -41,11 +41,11 @@ class _FeedService implements FeedService { _dio.options.baseUrl, baseUrl, )))); - var value = _result.data! + var _value = _result.data! .map((dynamic i) => FeedBlogPostModel.fromJson(i as Map)) .toList(); - return value; + return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { diff --git a/lib/locator_service.dart b/lib/locator_service.dart index f2ebc20..fb2637e 100644 --- a/lib/locator_service.dart +++ b/lib/locator_service.dart @@ -16,7 +16,8 @@ final sl = GetIt.instance; Future init() async { // BLoC / Cubit - sl.registerFactory(() => InitializationCubit(chatRepository: sl())); + sl.registerLazySingleton(() => InitializationCubit(chatRepository: sl())); + sl.registerFactory(() => ChatRoomCubit(chatRepository: sl())); sl.registerFactory(() => FeedCubit(feedRepository: sl())); sl.registerFactory(() => BlogPostCubit(blogPostRepository: sl())); diff --git a/lib/main.dart b/lib/main.dart index 9d608f2..684e227 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -42,7 +42,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MultiBlocProvider( providers: [ - BlocProvider(create: (context) => InitializationCubit(chatRepository: sl())..runInitialization()), + BlocProvider(create: (context) => InitializationCubit(chatRepository: 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/registration/app_navigation_screen/app_navigation_screen.dart b/lib/presentation/registration/app_navigation_screen/app_navigation_screen.dart index 29c5748..cbf92f0 100644 --- a/lib/presentation/registration/app_navigation_screen/app_navigation_screen.dart +++ b/lib/presentation/registration/app_navigation_screen/app_navigation_screen.dart @@ -156,7 +156,6 @@ class _AppNavigationScreenState extends State { style: TextStyle( color: Color(0XFF000000), fontSize: 20.fSize, - fontFamily: 'Roboto', fontWeight: FontWeight.w400, ), ), @@ -173,7 +172,6 @@ class _AppNavigationScreenState extends State { style: TextStyle( color: Color(0XFF888888), fontSize: 16.fSize, - fontFamily: 'Roboto', fontWeight: FontWeight.w400, ), ), @@ -215,7 +213,6 @@ class _AppNavigationScreenState extends State { style: TextStyle( color: Color(0XFF000000), fontSize: 20.fSize, - fontFamily: 'Roboto', fontWeight: FontWeight.w400, ), ), diff --git a/lib/theme/theme_helper.dart b/lib/theme/theme_helper.dart index 8a5d5ed..c912cb2 100644 --- a/lib/theme/theme_helper.dart +++ b/lib/theme/theme_helper.dart @@ -121,7 +121,7 @@ class TextThemes { bodySmall: TextStyle( color: appTheme.gray500, fontSize: 10.fSize, - fontFamily: 'Roboto', + fontFamily: 'Mulish', fontWeight: FontWeight.w400, ), labelLarge: TextStyle( diff --git a/pubspec.yaml b/pubspec.yaml index 49e9d72..256f892 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -64,8 +64,10 @@ dependencies: # photo gallery viewer + dismissible page photo_view: ^0.15.0 dismissible_page: ^1.0.2 - #url launcher + # url launcher url_launcher: ^6.3.0 + # debounce + easy_debounce: ^2.0.3 dev_dependencies: build_runner: ^2.4.11 -- 2.49.1 From 562935a30f585bff44e5a937f17e1e2e9b06385b Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 3 Jul 2024 16:54:38 +0300 Subject: [PATCH 029/110] fix(app): Merge conflict resolve --- .gitignore | 2 +- Makefile | 3 +-- package.json | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 0a42850..9d9b1ce 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,4 @@ /.flutter-plugins-dependencies /.packages /.env -/node_modules \ No newline at end of file +/node_modules/ diff --git a/Makefile b/Makefile index 3b10f12..cd6bc42 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,7 @@ - run-tests: flutter test run-analyse: flutter analyze -run-checks: run-analyse run-tests +run-checks: run-analyse run-tests \ No newline at end of file diff --git a/package.json b/package.json index 8c0eba5..9b39c56 100644 --- a/package.json +++ b/package.json @@ -19,4 +19,4 @@ "pre-push": "make run-checks", "preserveUnused": true } -} +} \ No newline at end of file -- 2.49.1 From 0a258000387983be2cde2d4803e8e7143f5e5304 Mon Sep 17 00:00:00 2001 From: alex Date: Wed, 3 Jul 2024 17:06:28 +0300 Subject: [PATCH 030/110] fix(feed): fix feed repository --- .../feed/presentation/pages/feed_screen.dart | 15 +++++++++++---- .../feed/repositories/feed_repository.dart | 2 +- lib/features/feed/services/feed_service.dart | 2 +- lib/features/feed/services/feed_service.g.dart | 12 +++++------- 4 files changed, 18 insertions(+), 13 deletions(-) diff --git a/lib/features/feed/presentation/pages/feed_screen.dart b/lib/features/feed/presentation/pages/feed_screen.dart index d42e776..797bfbb 100644 --- a/lib/features/feed/presentation/pages/feed_screen.dart +++ b/lib/features/feed/presentation/pages/feed_screen.dart @@ -18,6 +18,15 @@ class FeedScreen extends StatelessWidget { builder: (BuildContext context, FeedState state) { if (state is FeedStateLoaded) { return _buildFeedScreen(context, state); + } else if (state is FeedStateError) { + return Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: Center( + child: Text(state.errorMessage), + ), + ), + ); } else { return Scaffold( body: Center( @@ -100,8 +109,7 @@ class FeedScreen extends StatelessWidget { flex: 1, child: CustomOutlinedButton( text: "+", - onPressed: () => - GoRouter.of(context).goNamed('blogPostCreateScreen'), + onPressed: () => GoRouter.of(context).goNamed('blogPostCreateScreen'), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, ), ), @@ -220,8 +228,7 @@ class FeedScreen extends StatelessWidget { imageBuilder: (context, imageProvider) => Stack( children: [ ClipRRect( - borderRadius: - const BorderRadius.all(Radius.circular(8.0)), + borderRadius: const BorderRadius.all(Radius.circular(8.0)), child: Image( image: imageProvider, ), diff --git a/lib/features/feed/repositories/feed_repository.dart b/lib/features/feed/repositories/feed_repository.dart index fb87104..50799a0 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(); + return (await feedService.getBlocPostList()).entries.map((entry) => entry.value).toList(); } catch (e) { rethrow; } diff --git a/lib/features/feed/services/feed_service.dart b/lib/features/feed/services/feed_service.dart index 80deb91..d4f728f 100644 --- a/lib/features/feed/services/feed_service.dart +++ b/lib/features/feed/services/feed_service.dart @@ -9,5 +9,5 @@ abstract class FeedService { factory FeedService(Dio dio, {String baseUrl}) = _FeedService; @GET('/feed/index') - Future> getBlocPostList(); + Future> getBlocPostList(); } diff --git a/lib/features/feed/services/feed_service.g.dart b/lib/features/feed/services/feed_service.g.dart index 39b15fb..03aa238 100644 --- a/lib/features/feed/services/feed_service.g.dart +++ b/lib/features/feed/services/feed_service.g.dart @@ -19,13 +19,13 @@ 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( + final _result = await _dio.fetch>( + _setStreamType>(Options( method: 'GET', headers: _headers, extra: _extra, @@ -41,10 +41,8 @@ class _FeedService implements FeedService { _dio.options.baseUrl, baseUrl, )))); - var _value = _result.data! - .map((dynamic i) => - FeedBlogPostModel.fromJson(i as Map)) - .toList(); + var _value = _result.data!.map((k, dynamic v) => + MapEntry(k, FeedBlogPostModel.fromJson(v as Map))); return _value; } -- 2.49.1 From 3c4afe96d6cb4568838d4c85dece2c66c9ad4a11 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 3 Jul 2024 17:39:18 +0300 Subject: [PATCH 031/110] refactor(diary): Cubit and state for diary --- .../diary/presentation/bloc/diary_cubit.dart | 14 +- .../diary/presentation/bloc/diary_state.dart | 5 +- .../bloc/diary_state.freezed.dart | 620 ++++++++++++++++++ .../diary/repositories/diary_repository.dart | 19 +- .../diary/services/diary_service.dart | 8 +- .../diary/services/diary_service.g.dart | 103 +++ 6 files changed, 749 insertions(+), 20 deletions(-) create mode 100644 lib/features/diary/presentation/bloc/diary_state.freezed.dart create mode 100644 lib/features/diary/services/diary_service.g.dart diff --git a/lib/features/diary/presentation/bloc/diary_cubit.dart b/lib/features/diary/presentation/bloc/diary_cubit.dart index 07477bd..26092c1 100644 --- a/lib/features/diary/presentation/bloc/diary_cubit.dart +++ b/lib/features/diary/presentation/bloc/diary_cubit.dart @@ -1,22 +1,20 @@ -/*import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; class DiaryCubit extends Cubit { - final DiaryRepository blogPostRepository; + final DiaryRepository diaryRepository; - DiaryCubit({required this.blogPostRepository}) - : super(const DiaryState.loading()); + DiaryCubit({required this.diaryRepository}) : super(const DiaryState.loading()); - loadDiary(String blogPostID) async { + loadDiary(String diaryID) async { emit(const DiaryState.loading()); try { - final blogPost = await blogPostRepository.getDiary(blogPostID); - emit(DiaryState.loaded(blogPost: blogPost)); + final diary = await diaryRepository.getDiary(await diaryRepository.getDiaryID().toString()); + emit(DiaryState.loaded(diary: diary)); } catch (e) { emit(DiaryState.error(errorMessage: e.toString())); print(e); } } } -*/ \ 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 d4305c8..c673faf 100644 --- a/lib/features/diary/presentation/bloc/diary_state.dart +++ b/lib/features/diary/presentation/bloc/diary_state.dart @@ -1,4 +1,4 @@ -/*import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'diary_state.freezed.dart'; @@ -10,11 +10,10 @@ abstract class DiaryState with _$DiaryState { const factory DiaryState.loading() = DiaryStateLoading; const factory DiaryState.loaded({ - required DiaryModel blogPost, + required DiaryModel diary, }) = DiaryStateLoaded; const factory DiaryState.error({ required String errorMessage, }) = DiaryStateError; } -*/ \ No newline at end of file diff --git a/lib/features/diary/presentation/bloc/diary_state.freezed.dart b/lib/features/diary/presentation/bloc/diary_state.freezed.dart new file mode 100644 index 0000000..04256ba --- /dev/null +++ b/lib/features/diary/presentation/bloc/diary_state.freezed.dart @@ -0,0 +1,620 @@ +// 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 'diary_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 _$DiaryState { + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(DiaryModel diary) loaded, + required TResult Function(String errorMessage) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(DiaryModel diary)? loaded, + TResult? Function(String errorMessage)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(DiaryModel diary)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map( + TResult Function(_DiaryState value) $default, { + required TResult Function(DiaryStateLoading value) loading, + required TResult Function(DiaryStateLoaded value) loaded, + required TResult Function(DiaryStateError value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_DiaryState value)? $default, { + TResult? Function(DiaryStateLoading value)? loading, + TResult? Function(DiaryStateLoaded value)? loaded, + TResult? Function(DiaryStateError value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap( + TResult Function(_DiaryState value)? $default, { + TResult Function(DiaryStateLoading value)? loading, + TResult Function(DiaryStateLoaded value)? loaded, + TResult Function(DiaryStateError value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DiaryStateCopyWith<$Res> { + factory $DiaryStateCopyWith( + DiaryState value, $Res Function(DiaryState) then) = + _$DiaryStateCopyWithImpl<$Res, DiaryState>; +} + +/// @nodoc +class _$DiaryStateCopyWithImpl<$Res, $Val extends DiaryState> + implements $DiaryStateCopyWith<$Res> { + _$DiaryStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; +} + +/// @nodoc +abstract class _$$DiaryStateImplCopyWith<$Res> { + factory _$$DiaryStateImplCopyWith( + _$DiaryStateImpl value, $Res Function(_$DiaryStateImpl) then) = + __$$DiaryStateImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$DiaryStateImplCopyWithImpl<$Res> + extends _$DiaryStateCopyWithImpl<$Res, _$DiaryStateImpl> + implements _$$DiaryStateImplCopyWith<$Res> { + __$$DiaryStateImplCopyWithImpl( + _$DiaryStateImpl _value, $Res Function(_$DiaryStateImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$DiaryStateImpl implements _DiaryState { + const _$DiaryStateImpl(); + + @override + String toString() { + return 'DiaryState()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$DiaryStateImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(DiaryModel diary) loaded, + required TResult Function(String errorMessage) error, + }) { + return $default(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(DiaryModel diary)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return $default?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(DiaryModel diary)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_DiaryState value) $default, { + required TResult Function(DiaryStateLoading value) loading, + required TResult Function(DiaryStateLoaded value) loaded, + required TResult Function(DiaryStateError value) error, + }) { + return $default(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_DiaryState value)? $default, { + TResult? Function(DiaryStateLoading value)? loading, + TResult? Function(DiaryStateLoaded value)? loaded, + TResult? Function(DiaryStateError value)? error, + }) { + return $default?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_DiaryState value)? $default, { + TResult Function(DiaryStateLoading value)? loading, + TResult Function(DiaryStateLoaded value)? loaded, + TResult Function(DiaryStateError value)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(this); + } + return orElse(); + } +} + +abstract class _DiaryState implements DiaryState { + const factory _DiaryState() = _$DiaryStateImpl; +} + +/// @nodoc +abstract class _$$DiaryStateLoadingImplCopyWith<$Res> { + factory _$$DiaryStateLoadingImplCopyWith(_$DiaryStateLoadingImpl value, + $Res Function(_$DiaryStateLoadingImpl) then) = + __$$DiaryStateLoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$DiaryStateLoadingImplCopyWithImpl<$Res> + extends _$DiaryStateCopyWithImpl<$Res, _$DiaryStateLoadingImpl> + implements _$$DiaryStateLoadingImplCopyWith<$Res> { + __$$DiaryStateLoadingImplCopyWithImpl(_$DiaryStateLoadingImpl _value, + $Res Function(_$DiaryStateLoadingImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$DiaryStateLoadingImpl implements DiaryStateLoading { + const _$DiaryStateLoadingImpl(); + + @override + String toString() { + return 'DiaryState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$DiaryStateLoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(DiaryModel diary) loaded, + required TResult Function(String errorMessage) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(DiaryModel diary)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(DiaryModel diary)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_DiaryState value) $default, { + required TResult Function(DiaryStateLoading value) loading, + required TResult Function(DiaryStateLoaded value) loaded, + required TResult Function(DiaryStateError value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_DiaryState value)? $default, { + TResult? Function(DiaryStateLoading value)? loading, + TResult? Function(DiaryStateLoaded value)? loaded, + TResult? Function(DiaryStateError value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_DiaryState value)? $default, { + TResult Function(DiaryStateLoading value)? loading, + TResult Function(DiaryStateLoaded value)? loaded, + TResult Function(DiaryStateError value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class DiaryStateLoading implements DiaryState { + const factory DiaryStateLoading() = _$DiaryStateLoadingImpl; +} + +/// @nodoc +abstract class _$$DiaryStateLoadedImplCopyWith<$Res> { + factory _$$DiaryStateLoadedImplCopyWith(_$DiaryStateLoadedImpl value, + $Res Function(_$DiaryStateLoadedImpl) then) = + __$$DiaryStateLoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({DiaryModel diary}); + + $DiaryModelCopyWith<$Res> get diary; +} + +/// @nodoc +class __$$DiaryStateLoadedImplCopyWithImpl<$Res> + extends _$DiaryStateCopyWithImpl<$Res, _$DiaryStateLoadedImpl> + implements _$$DiaryStateLoadedImplCopyWith<$Res> { + __$$DiaryStateLoadedImplCopyWithImpl(_$DiaryStateLoadedImpl _value, + $Res Function(_$DiaryStateLoadedImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? diary = null, + }) { + return _then(_$DiaryStateLoadedImpl( + diary: null == diary + ? _value.diary + : diary // ignore: cast_nullable_to_non_nullable + as DiaryModel, + )); + } + + @override + @pragma('vm:prefer-inline') + $DiaryModelCopyWith<$Res> get diary { + return $DiaryModelCopyWith<$Res>(_value.diary, (value) { + return _then(_value.copyWith(diary: value)); + }); + } +} + +/// @nodoc + +class _$DiaryStateLoadedImpl implements DiaryStateLoaded { + const _$DiaryStateLoadedImpl({required this.diary}); + + @override + final DiaryModel diary; + + @override + String toString() { + return 'DiaryState.loaded(diary: $diary)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DiaryStateLoadedImpl && + (identical(other.diary, diary) || other.diary == diary)); + } + + @override + int get hashCode => Object.hash(runtimeType, diary); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$DiaryStateLoadedImplCopyWith<_$DiaryStateLoadedImpl> get copyWith => + __$$DiaryStateLoadedImplCopyWithImpl<_$DiaryStateLoadedImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(DiaryModel diary) loaded, + required TResult Function(String errorMessage) error, + }) { + return loaded(diary); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(DiaryModel diary)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return loaded?.call(diary); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(DiaryModel diary)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(diary); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_DiaryState value) $default, { + required TResult Function(DiaryStateLoading value) loading, + required TResult Function(DiaryStateLoaded value) loaded, + required TResult Function(DiaryStateError value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_DiaryState value)? $default, { + TResult? Function(DiaryStateLoading value)? loading, + TResult? Function(DiaryStateLoaded value)? loaded, + TResult? Function(DiaryStateError value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_DiaryState value)? $default, { + TResult Function(DiaryStateLoading value)? loading, + TResult Function(DiaryStateLoaded value)? loaded, + TResult Function(DiaryStateError value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class DiaryStateLoaded implements DiaryState { + const factory DiaryStateLoaded({required final DiaryModel diary}) = + _$DiaryStateLoadedImpl; + + DiaryModel get diary; + @JsonKey(ignore: true) + _$$DiaryStateLoadedImplCopyWith<_$DiaryStateLoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$DiaryStateErrorImplCopyWith<$Res> { + factory _$$DiaryStateErrorImplCopyWith(_$DiaryStateErrorImpl value, + $Res Function(_$DiaryStateErrorImpl) then) = + __$$DiaryStateErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String errorMessage}); +} + +/// @nodoc +class __$$DiaryStateErrorImplCopyWithImpl<$Res> + extends _$DiaryStateCopyWithImpl<$Res, _$DiaryStateErrorImpl> + implements _$$DiaryStateErrorImplCopyWith<$Res> { + __$$DiaryStateErrorImplCopyWithImpl( + _$DiaryStateErrorImpl _value, $Res Function(_$DiaryStateErrorImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? errorMessage = null, + }) { + return _then(_$DiaryStateErrorImpl( + errorMessage: null == errorMessage + ? _value.errorMessage + : errorMessage // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$DiaryStateErrorImpl implements DiaryStateError { + const _$DiaryStateErrorImpl({required this.errorMessage}); + + @override + final String errorMessage; + + @override + String toString() { + return 'DiaryState.error(errorMessage: $errorMessage)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DiaryStateErrorImpl && + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); + } + + @override + int get hashCode => Object.hash(runtimeType, errorMessage); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$DiaryStateErrorImplCopyWith<_$DiaryStateErrorImpl> get copyWith => + __$$DiaryStateErrorImplCopyWithImpl<_$DiaryStateErrorImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(DiaryModel diary) loaded, + required TResult Function(String errorMessage) error, + }) { + return error(errorMessage); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(DiaryModel diary)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return error?.call(errorMessage); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(DiaryModel diary)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(errorMessage); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_DiaryState value) $default, { + required TResult Function(DiaryStateLoading value) loading, + required TResult Function(DiaryStateLoaded value) loaded, + required TResult Function(DiaryStateError value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_DiaryState value)? $default, { + TResult? Function(DiaryStateLoading value)? loading, + TResult? Function(DiaryStateLoaded value)? loaded, + TResult? Function(DiaryStateError value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_DiaryState value)? $default, { + TResult Function(DiaryStateLoading value)? loading, + TResult Function(DiaryStateLoaded value)? loaded, + TResult Function(DiaryStateError value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class DiaryStateError implements DiaryState { + const factory DiaryStateError({required final String errorMessage}) = + _$DiaryStateErrorImpl; + + String get errorMessage; + @JsonKey(ignore: true) + _$$DiaryStateErrorImplCopyWith<_$DiaryStateErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/diary/repositories/diary_repository.dart b/lib/features/diary/repositories/diary_repository.dart index 1ae40d8..c6b1dc4 100644 --- a/lib/features/diary/repositories/diary_repository.dart +++ b/lib/features/diary/repositories/diary_repository.dart @@ -1,17 +1,24 @@ -/*import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:eatvio_app/features/diary/services/diary_service.dart'; class DiaryRepository { - final DiaryService blogPostService; + final DiaryService diaryService; - DiaryRepository({required this.blogPostService}); + DiaryRepository({required this.diaryService}); - Future getDiary(String blogPostID) async { + Future getDiaryID() async { try { - return await blogPostService.getDiary(blogPostID); + return await diaryService.getDiaryID(); + } catch (e) { + rethrow; + } + } + + Future getDiary(String diaryID) async { + try { + return await diaryService.getDiary(diaryID); } catch (e) { rethrow; } } } -*/ \ 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 6b6cb6b..bf56e85 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -1,4 +1,4 @@ -/*import 'package:dio/dio.dart'; +import 'package:dio/dio.dart'; import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:retrofit/retrofit.dart'; @@ -8,7 +8,9 @@ part 'diary_service.g.dart'; abstract class DiaryService { factory DiaryService(Dio dio, {String baseUrl}) = _DiaryService; - @GET('/feed/show/{id}') + @GET('/diary/index') + Future getDiaryID(); + + @GET('/feed/{id}/show/') Future getDiary(@Path() String id); } -*/ \ No newline at end of file diff --git a/lib/features/diary/services/diary_service.g.dart b/lib/features/diary/services/diary_service.g.dart new file mode 100644 index 0000000..09ce900 --- /dev/null +++ b/lib/features/diary/services/diary_service.g.dart @@ -0,0 +1,103 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'diary_service.dart'; + +// ************************************************************************** +// RetrofitGenerator +// ************************************************************************** + +// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers,unused_element + +class _DiaryService implements DiaryService { + _DiaryService( + this._dio, { + this.baseUrl, + }); + + final Dio _dio; + + String? baseUrl; + + @override + Future getDiaryID() async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio.fetch(_setStreamType(Options( + method: 'GET', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/index', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = _result.data!; + return _value; + } + + @override + Future getDiary(String id) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio + .fetch>(_setStreamType(Options( + method: 'GET', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/feed/${id}/show/', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = DiaryModel.fromJson(_result.data!); + 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(); + } +} -- 2.49.1 From def95aeeb5be9fece6d61e4932e59b67621c09e0 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 3 Jul 2024 17:45:36 +0300 Subject: [PATCH 032/110] refactor(diary): LocatorService reg --- lib/locator_service.dart | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/locator_service.dart b/lib/locator_service.dart index fb2637e..0328dc6 100644 --- a/lib/locator_service.dart +++ b/lib/locator_service.dart @@ -9,6 +9,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:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; +import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; +import 'package:eatvio_app/features/diary/services/diary_service.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:get_it/get_it.dart'; @@ -21,16 +24,19 @@ Future init() async { sl.registerFactory(() => ChatRoomCubit(chatRepository: sl())); sl.registerFactory(() => FeedCubit(feedRepository: sl())); sl.registerFactory(() => BlogPostCubit(blogPostRepository: sl())); + sl.registerFactory(() => DiaryCubit(diaryRepository: sl())); // Repository sl.registerLazySingleton(() => ChatRepository(chatService: sl())); sl.registerLazySingleton(() => FeedRepository(feedService: sl())); sl.registerLazySingleton(() => BlogPostRepository(blogPostService: sl())); + sl.registerLazySingleton(() => DiaryRepository(diaryService: sl())); // Services sl.registerLazySingleton(() => ChatService(sl())); sl.registerLazySingleton(() => FeedService(sl())); sl.registerLazySingleton(() => BlogPostService(sl())); + sl.registerLazySingleton(() => DiaryService(sl())); // External sl.registerLazySingleton( -- 2.49.1 From 7514a9b75ffea40d60ecd397d31a5334a490c6af Mon Sep 17 00:00:00 2001 From: alex Date: Wed, 3 Jul 2024 19:06:51 +0300 Subject: [PATCH 033/110] feat(chat): add chat load --- .../chat/models/chat_messages_model.dart | 5 +- .../models/chat_messages_model.freezed.dart | 53 +++++- .../chat/models/chat_messages_model.g.dart | 2 + lib/features/chat/models/chat_meta_model.dart | 14 ++ .../chat/models/chat_meta_model.freezed.dart | 158 ++++++++++++++++++ .../chat/models/chat_meta_model.g.dart | 17 ++ .../bloc/chat_room_cubit/chat_room_cubit.dart | 44 ++++- .../bloc/chat_room_cubit/chat_room_state.dart | 5 +- .../chat_room_state.freezed.dart | 117 +++++++------ .../chat/presentation/pages/chat_screen.dart | 40 +++-- .../chat/repositories/chat_repository.dart | 4 +- lib/features/chat/services/chat_service.dart | 4 +- .../chat/services/chat_service.g.dart | 7 +- 13 files changed, 380 insertions(+), 90 deletions(-) create mode 100644 lib/features/chat/models/chat_meta_model.dart create mode 100644 lib/features/chat/models/chat_meta_model.freezed.dart create mode 100644 lib/features/chat/models/chat_meta_model.g.dart diff --git a/lib/features/chat/models/chat_messages_model.dart b/lib/features/chat/models/chat_messages_model.dart index fbf6fc0..84a51b4 100644 --- a/lib/features/chat/models/chat_messages_model.dart +++ b/lib/features/chat/models/chat_messages_model.dart @@ -1,4 +1,5 @@ import 'package:eatvio_app/features/chat/models/chat_message_model.dart'; +import 'package:eatvio_app/features/chat/models/chat_meta_model.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'chat_messages_model.freezed.dart'; @@ -8,8 +9,8 @@ part 'chat_messages_model.g.dart'; @freezed class ChatMessagesModel with _$ChatMessagesModel { const factory ChatMessagesModel({ - @JsonKey(name: 'data') - required List messagesList, + @JsonKey(name: 'data') required List messagesList, + required ChatMetaModel meta, }) = _ChatMessagesModel; factory ChatMessagesModel.fromJson(Map json) => _$ChatMessagesModelFromJson(json); diff --git a/lib/features/chat/models/chat_messages_model.freezed.dart b/lib/features/chat/models/chat_messages_model.freezed.dart index 594498a..a970241 100644 --- a/lib/features/chat/models/chat_messages_model.freezed.dart +++ b/lib/features/chat/models/chat_messages_model.freezed.dart @@ -22,6 +22,7 @@ ChatMessagesModel _$ChatMessagesModelFromJson(Map json) { mixin _$ChatMessagesModel { @JsonKey(name: 'data') List get messagesList => throw _privateConstructorUsedError; + ChatMetaModel get meta => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -35,7 +36,11 @@ abstract class $ChatMessagesModelCopyWith<$Res> { ChatMessagesModel value, $Res Function(ChatMessagesModel) then) = _$ChatMessagesModelCopyWithImpl<$Res, ChatMessagesModel>; @useResult - $Res call({@JsonKey(name: 'data') List messagesList}); + $Res call( + {@JsonKey(name: 'data') List messagesList, + ChatMetaModel meta}); + + $ChatMetaModelCopyWith<$Res> get meta; } /// @nodoc @@ -52,14 +57,27 @@ class _$ChatMessagesModelCopyWithImpl<$Res, $Val extends ChatMessagesModel> @override $Res call({ Object? messagesList = null, + Object? meta = null, }) { return _then(_value.copyWith( messagesList: null == messagesList ? _value.messagesList : messagesList // ignore: cast_nullable_to_non_nullable as List, + meta: null == meta + ? _value.meta + : meta // ignore: cast_nullable_to_non_nullable + as ChatMetaModel, ) as $Val); } + + @override + @pragma('vm:prefer-inline') + $ChatMetaModelCopyWith<$Res> get meta { + return $ChatMetaModelCopyWith<$Res>(_value.meta, (value) { + return _then(_value.copyWith(meta: value) as $Val); + }); + } } /// @nodoc @@ -70,7 +88,12 @@ abstract class _$$ChatMessagesModelImplCopyWith<$Res> __$$ChatMessagesModelImplCopyWithImpl<$Res>; @override @useResult - $Res call({@JsonKey(name: 'data') List messagesList}); + $Res call( + {@JsonKey(name: 'data') List messagesList, + ChatMetaModel meta}); + + @override + $ChatMetaModelCopyWith<$Res> get meta; } /// @nodoc @@ -85,12 +108,17 @@ class __$$ChatMessagesModelImplCopyWithImpl<$Res> @override $Res call({ Object? messagesList = null, + Object? meta = null, }) { return _then(_$ChatMessagesModelImpl( messagesList: null == messagesList ? _value._messagesList : messagesList // ignore: cast_nullable_to_non_nullable as List, + meta: null == meta + ? _value.meta + : meta // ignore: cast_nullable_to_non_nullable + as ChatMetaModel, )); } } @@ -100,7 +128,8 @@ class __$$ChatMessagesModelImplCopyWithImpl<$Res> class _$ChatMessagesModelImpl implements _ChatMessagesModel { const _$ChatMessagesModelImpl( {@JsonKey(name: 'data') - required final List messagesList}) + required final List messagesList, + required this.meta}) : _messagesList = messagesList; factory _$ChatMessagesModelImpl.fromJson(Map json) => @@ -115,9 +144,12 @@ class _$ChatMessagesModelImpl implements _ChatMessagesModel { return EqualUnmodifiableListView(_messagesList); } + @override + final ChatMetaModel meta; + @override String toString() { - return 'ChatMessagesModel(messagesList: $messagesList)'; + return 'ChatMessagesModel(messagesList: $messagesList, meta: $meta)'; } @override @@ -126,13 +158,14 @@ class _$ChatMessagesModelImpl implements _ChatMessagesModel { (other.runtimeType == runtimeType && other is _$ChatMessagesModelImpl && const DeepCollectionEquality() - .equals(other._messagesList, _messagesList)); + .equals(other._messagesList, _messagesList) && + (identical(other.meta, meta) || other.meta == meta)); } @JsonKey(ignore: true) @override int get hashCode => Object.hash( - runtimeType, const DeepCollectionEquality().hash(_messagesList)); + runtimeType, const DeepCollectionEquality().hash(_messagesList), meta); @JsonKey(ignore: true) @override @@ -151,9 +184,9 @@ class _$ChatMessagesModelImpl implements _ChatMessagesModel { abstract class _ChatMessagesModel implements ChatMessagesModel { const factory _ChatMessagesModel( - {@JsonKey(name: 'data') - required final List messagesList}) = - _$ChatMessagesModelImpl; + {@JsonKey(name: 'data') + required final List messagesList, + required final ChatMetaModel meta}) = _$ChatMessagesModelImpl; factory _ChatMessagesModel.fromJson(Map json) = _$ChatMessagesModelImpl.fromJson; @@ -162,6 +195,8 @@ abstract class _ChatMessagesModel implements ChatMessagesModel { @JsonKey(name: 'data') List get messagesList; @override + ChatMetaModel get meta; + @override @JsonKey(ignore: true) _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => throw _privateConstructorUsedError; diff --git a/lib/features/chat/models/chat_messages_model.g.dart b/lib/features/chat/models/chat_messages_model.g.dart index 80f7874..6216cd8 100644 --- a/lib/features/chat/models/chat_messages_model.g.dart +++ b/lib/features/chat/models/chat_messages_model.g.dart @@ -12,10 +12,12 @@ _$ChatMessagesModelImpl _$$ChatMessagesModelImplFromJson( messagesList: (json['data'] as List) .map((e) => ChatMessageModel.fromJson(e as Map)) .toList(), + meta: ChatMetaModel.fromJson(json['meta'] as Map), ); Map _$$ChatMessagesModelImplToJson( _$ChatMessagesModelImpl instance) => { 'data': instance.messagesList, + 'meta': instance.meta, }; diff --git a/lib/features/chat/models/chat_meta_model.dart b/lib/features/chat/models/chat_meta_model.dart new file mode 100644 index 0000000..4c4d6cf --- /dev/null +++ b/lib/features/chat/models/chat_meta_model.dart @@ -0,0 +1,14 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'chat_meta_model.freezed.dart'; + +part 'chat_meta_model.g.dart'; + +@freezed +class ChatMetaModel with _$ChatMetaModel { + const factory ChatMetaModel({ + @JsonKey(name: "last_page") required int lastPage, + }) = _ChatMetaModel; + + factory ChatMetaModel.fromJson(Map json) => _$ChatMetaModelFromJson(json); +} diff --git a/lib/features/chat/models/chat_meta_model.freezed.dart b/lib/features/chat/models/chat_meta_model.freezed.dart new file mode 100644 index 0000000..11ecb9e --- /dev/null +++ b/lib/features/chat/models/chat_meta_model.freezed.dart @@ -0,0 +1,158 @@ +// 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 'chat_meta_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'); + +ChatMetaModel _$ChatMetaModelFromJson(Map json) { + return _ChatMetaModel.fromJson(json); +} + +/// @nodoc +mixin _$ChatMetaModel { + @JsonKey(name: "last_page") + int get lastPage => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $ChatMetaModelCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $ChatMetaModelCopyWith<$Res> { + factory $ChatMetaModelCopyWith( + ChatMetaModel value, $Res Function(ChatMetaModel) then) = + _$ChatMetaModelCopyWithImpl<$Res, ChatMetaModel>; + @useResult + $Res call({@JsonKey(name: "last_page") int lastPage}); +} + +/// @nodoc +class _$ChatMetaModelCopyWithImpl<$Res, $Val extends ChatMetaModel> + implements $ChatMetaModelCopyWith<$Res> { + _$ChatMetaModelCopyWithImpl(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? lastPage = null, + }) { + return _then(_value.copyWith( + lastPage: null == lastPage + ? _value.lastPage + : lastPage // ignore: cast_nullable_to_non_nullable + as int, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$ChatMetaModelImplCopyWith<$Res> + implements $ChatMetaModelCopyWith<$Res> { + factory _$$ChatMetaModelImplCopyWith( + _$ChatMetaModelImpl value, $Res Function(_$ChatMetaModelImpl) then) = + __$$ChatMetaModelImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({@JsonKey(name: "last_page") int lastPage}); +} + +/// @nodoc +class __$$ChatMetaModelImplCopyWithImpl<$Res> + extends _$ChatMetaModelCopyWithImpl<$Res, _$ChatMetaModelImpl> + implements _$$ChatMetaModelImplCopyWith<$Res> { + __$$ChatMetaModelImplCopyWithImpl( + _$ChatMetaModelImpl _value, $Res Function(_$ChatMetaModelImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? lastPage = null, + }) { + return _then(_$ChatMetaModelImpl( + lastPage: null == lastPage + ? _value.lastPage + : lastPage // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$ChatMetaModelImpl implements _ChatMetaModel { + const _$ChatMetaModelImpl( + {@JsonKey(name: "last_page") required this.lastPage}); + + factory _$ChatMetaModelImpl.fromJson(Map json) => + _$$ChatMetaModelImplFromJson(json); + + @override + @JsonKey(name: "last_page") + final int lastPage; + + @override + String toString() { + return 'ChatMetaModel(lastPage: $lastPage)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ChatMetaModelImpl && + (identical(other.lastPage, lastPage) || + other.lastPage == lastPage)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, lastPage); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => + __$$ChatMetaModelImplCopyWithImpl<_$ChatMetaModelImpl>(this, _$identity); + + @override + Map toJson() { + return _$$ChatMetaModelImplToJson( + this, + ); + } +} + +abstract class _ChatMetaModel implements ChatMetaModel { + const factory _ChatMetaModel( + {@JsonKey(name: "last_page") required final int lastPage}) = + _$ChatMetaModelImpl; + + factory _ChatMetaModel.fromJson(Map json) = + _$ChatMetaModelImpl.fromJson; + + @override + @JsonKey(name: "last_page") + int get lastPage; + @override + @JsonKey(ignore: true) + _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/chat/models/chat_meta_model.g.dart b/lib/features/chat/models/chat_meta_model.g.dart new file mode 100644 index 0000000..7126e2d --- /dev/null +++ b/lib/features/chat/models/chat_meta_model.g.dart @@ -0,0 +1,17 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'chat_meta_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$ChatMetaModelImpl _$$ChatMetaModelImplFromJson(Map json) => + _$ChatMetaModelImpl( + lastPage: (json['last_page'] as num).toInt(), + ); + +Map _$$ChatMetaModelImplToJson(_$ChatMetaModelImpl instance) => + { + 'last_page': instance.lastPage, + }; diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart index aff8fa8..712adf0 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart @@ -14,6 +14,9 @@ import 'package:flutter_bloc/flutter_bloc.dart'; class ChatRoomCubit extends Cubit { final ChatRepository chatRepository; + int currentPage = 1; + late final int lastPage; + late final PusherChannelsClient client; late final PrivateChannel privateChannel; @@ -21,11 +24,40 @@ class ChatRoomCubit extends Cubit { required this.chatRepository, }) : super(ChatRoomState.loading()); + loadNextPage(String chatId) async { + if (currentPage < lastPage) { + emit(ChatRoomState.loaded( + chatRoom: (state as ChatRoomStateLoaded).chatRoom, + chatMessages: (state as ChatRoomStateLoaded).chatMessages, + isTyping: (state as ChatRoomStateLoaded).isTyping, + isLoading: true, + )); + + try { + final chatMessages = await chatRepository.getChatMessages(chatId, currentPage + 1); + + emit(ChatRoomState.loaded( + chatRoom: (state as ChatRoomStateLoaded).chatRoom, + chatMessages: [...(state as ChatRoomStateLoaded).chatMessages, ...chatMessages.messagesList], + isTyping: (state as ChatRoomStateLoaded).isTyping, + isLoading: false, + )); + + currentPage++; + + } catch (e) { + print(e); + emit(ChatRoomState.error(errorMessage: 'Ошибка получеия данных')); + } + } + } + initChat(String chatId) async { try { final chatRoom = await chatRepository.getChatRoom(chatId); - final chatMessages = await chatRepository.getChatMessages(chatId); + final chatMessages = await chatRepository.getChatMessages(chatId, currentPage); + lastPage = chatMessages.meta.lastPage; final initCubit = sl(); @@ -38,8 +70,9 @@ class ChatRoomCubit extends Cubit { emit(ChatRoomState.loaded( chatRoom: chatRoom, - chatMessages: chatMessages, + chatMessages: chatMessages.messagesList, isTyping: false, + isLoading: false, )); } catch (e) { emit(ChatRoomState.error(errorMessage: 'Ошибка получеия данных')); @@ -67,13 +100,14 @@ class ChatRoomCubit extends Cubit { privateChannel.bind('App\\Events\\ChatMessageUpdated').listen((event) { List messagesList = [ ChatMessageModel.fromJson(jsonDecode(event.data)['message']), - ...(state as ChatRoomStateLoaded).chatMessages.messagesList, + ...(state as ChatRoomStateLoaded).chatMessages, ]; emit( ChatRoomState.loaded( chatRoom: (state as ChatRoomStateLoaded).chatRoom, - chatMessages: (state as ChatRoomStateLoaded).chatMessages.copyWith(messagesList: messagesList), + chatMessages: messagesList, isTyping: (state as ChatRoomStateLoaded).isTyping, + isLoading: false, ), ); }); @@ -84,6 +118,7 @@ class ChatRoomCubit extends Cubit { chatRoom: (state as ChatRoomStateLoaded).chatRoom, chatMessages: (state as ChatRoomStateLoaded).chatMessages, isTyping: true, + isLoading: false, ), ); EasyDebounce.debounce( @@ -94,6 +129,7 @@ class ChatRoomCubit extends Cubit { chatRoom: (state as ChatRoomStateLoaded).chatRoom, chatMessages: (state as ChatRoomStateLoaded).chatMessages, isTyping: false, + isLoading: false, ), ), ); diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart index dbf8238..24113e6 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart @@ -1,4 +1,4 @@ -import 'package:eatvio_app/features/chat/models/chat_messages_model.dart'; +import 'package:eatvio_app/features/chat/models/chat_message_model.dart'; import 'package:eatvio_app/features/chat/models/chat_room_model.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; @@ -12,8 +12,9 @@ abstract class ChatRoomState with _$ChatRoomState { const factory ChatRoomState.loaded({ required ChatRoomModel chatRoom, - required ChatMessagesModel chatMessages, + required List chatMessages, required bool isTyping, + required bool isLoading, }) = ChatRoomStateLoaded; const factory ChatRoomState.error({ diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart index 4831ccc..43bf9df 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart @@ -21,7 +21,7 @@ mixin _$ChatRoomState { TResult Function() $default, { required TResult Function() loading, required TResult Function(ChatRoomModel chatRoom, - ChatMessagesModel chatMessages, bool isTyping) + List chatMessages, bool isTyping, bool isLoading) loaded, required TResult Function(String errorMessage) error, }) => @@ -30,8 +30,8 @@ mixin _$ChatRoomState { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, - bool isTyping)? + TResult? Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? loaded, TResult? Function(String errorMessage)? error, }) => @@ -40,8 +40,8 @@ mixin _$ChatRoomState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, - bool isTyping)? + TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), @@ -133,7 +133,7 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult Function() $default, { required TResult Function() loading, required TResult Function(ChatRoomModel chatRoom, - ChatMessagesModel chatMessages, bool isTyping) + List chatMessages, bool isTyping, bool isLoading) loaded, required TResult Function(String errorMessage) error, }) { @@ -145,8 +145,8 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, - bool isTyping)? + TResult? Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? loaded, TResult? Function(String errorMessage)? error, }) { @@ -158,8 +158,8 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, - bool isTyping)? + TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), @@ -254,7 +254,7 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult Function() $default, { required TResult Function() loading, required TResult Function(ChatRoomModel chatRoom, - ChatMessagesModel chatMessages, bool isTyping) + List chatMessages, bool isTyping, bool isLoading) loaded, required TResult Function(String errorMessage) error, }) { @@ -266,8 +266,8 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, - bool isTyping)? + TResult? Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? loaded, TResult? Function(String errorMessage)? error, }) { @@ -279,8 +279,8 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, - bool isTyping)? + TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), @@ -340,10 +340,12 @@ abstract class _$$ChatRoomStateLoadedImplCopyWith<$Res> { __$$ChatRoomStateLoadedImplCopyWithImpl<$Res>; @useResult $Res call( - {ChatRoomModel chatRoom, ChatMessagesModel chatMessages, bool isTyping}); + {ChatRoomModel chatRoom, + List chatMessages, + bool isTyping, + bool isLoading}); $ChatRoomModelCopyWith<$Res> get chatRoom; - $ChatMessagesModelCopyWith<$Res> get chatMessages; } /// @nodoc @@ -360,6 +362,7 @@ class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> Object? chatRoom = null, Object? chatMessages = null, Object? isTyping = null, + Object? isLoading = null, }) { return _then(_$ChatRoomStateLoadedImpl( chatRoom: null == chatRoom @@ -367,13 +370,17 @@ class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> : chatRoom // ignore: cast_nullable_to_non_nullable as ChatRoomModel, chatMessages: null == chatMessages - ? _value.chatMessages + ? _value._chatMessages : chatMessages // ignore: cast_nullable_to_non_nullable - as ChatMessagesModel, + as List, isTyping: null == isTyping ? _value.isTyping : isTyping // ignore: cast_nullable_to_non_nullable as bool, + isLoading: null == isLoading + ? _value.isLoading + : isLoading // ignore: cast_nullable_to_non_nullable + as bool, )); } @@ -384,14 +391,6 @@ class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> return _then(_value.copyWith(chatRoom: value)); }); } - - @override - @pragma('vm:prefer-inline') - $ChatMessagesModelCopyWith<$Res> get chatMessages { - return $ChatMessagesModelCopyWith<$Res>(_value.chatMessages, (value) { - return _then(_value.copyWith(chatMessages: value)); - }); - } } /// @nodoc @@ -399,19 +398,29 @@ class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { const _$ChatRoomStateLoadedImpl( {required this.chatRoom, - required this.chatMessages, - required this.isTyping}); + required final List chatMessages, + required this.isTyping, + required this.isLoading}) + : _chatMessages = chatMessages; @override final ChatRoomModel chatRoom; + final List _chatMessages; @override - final ChatMessagesModel chatMessages; + List get chatMessages { + if (_chatMessages is EqualUnmodifiableListView) return _chatMessages; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_chatMessages); + } + @override final bool isTyping; + @override + final bool isLoading; @override String toString() { - return 'ChatRoomState.loaded(chatRoom: $chatRoom, chatMessages: $chatMessages, isTyping: $isTyping)'; + return 'ChatRoomState.loaded(chatRoom: $chatRoom, chatMessages: $chatMessages, isTyping: $isTyping, isLoading: $isLoading)'; } @override @@ -421,15 +430,17 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { other is _$ChatRoomStateLoadedImpl && (identical(other.chatRoom, chatRoom) || other.chatRoom == chatRoom) && - (identical(other.chatMessages, chatMessages) || - other.chatMessages == chatMessages) && + const DeepCollectionEquality() + .equals(other._chatMessages, _chatMessages) && (identical(other.isTyping, isTyping) || - other.isTyping == isTyping)); + other.isTyping == isTyping) && + (identical(other.isLoading, isLoading) || + other.isLoading == isLoading)); } @override - int get hashCode => - Object.hash(runtimeType, chatRoom, chatMessages, isTyping); + int get hashCode => Object.hash(runtimeType, chatRoom, + const DeepCollectionEquality().hash(_chatMessages), isTyping, isLoading); @JsonKey(ignore: true) @override @@ -444,11 +455,11 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { TResult Function() $default, { required TResult Function() loading, required TResult Function(ChatRoomModel chatRoom, - ChatMessagesModel chatMessages, bool isTyping) + List chatMessages, bool isTyping, bool isLoading) loaded, required TResult Function(String errorMessage) error, }) { - return loaded(chatRoom, chatMessages, isTyping); + return loaded(chatRoom, chatMessages, isTyping, isLoading); } @override @@ -456,12 +467,12 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, - bool isTyping)? + TResult? Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? loaded, TResult? Function(String errorMessage)? error, }) { - return loaded?.call(chatRoom, chatMessages, isTyping); + return loaded?.call(chatRoom, chatMessages, isTyping, isLoading); } @override @@ -469,14 +480,14 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, - bool isTyping)? + TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { if (loaded != null) { - return loaded(chatRoom, chatMessages, isTyping); + return loaded(chatRoom, chatMessages, isTyping, isLoading); } return orElse(); } @@ -522,12 +533,14 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { abstract class ChatRoomStateLoaded implements ChatRoomState { const factory ChatRoomStateLoaded( {required final ChatRoomModel chatRoom, - required final ChatMessagesModel chatMessages, - required final bool isTyping}) = _$ChatRoomStateLoadedImpl; + required final List chatMessages, + required final bool isTyping, + required final bool isLoading}) = _$ChatRoomStateLoadedImpl; ChatRoomModel get chatRoom; - ChatMessagesModel get chatMessages; + List get chatMessages; bool get isTyping; + bool get isLoading; @JsonKey(ignore: true) _$$ChatRoomStateLoadedImplCopyWith<_$ChatRoomStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; @@ -602,7 +615,7 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { TResult Function() $default, { required TResult Function() loading, required TResult Function(ChatRoomModel chatRoom, - ChatMessagesModel chatMessages, bool isTyping) + List chatMessages, bool isTyping, bool isLoading) loaded, required TResult Function(String errorMessage) error, }) { @@ -614,8 +627,8 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, - bool isTyping)? + TResult? Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? loaded, TResult? Function(String errorMessage)? error, }) { @@ -627,8 +640,8 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, ChatMessagesModel chatMessages, - bool isTyping)? + TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), diff --git a/lib/features/chat/presentation/pages/chat_screen.dart b/lib/features/chat/presentation/pages/chat_screen.dart index b25be66..7d9528f 100644 --- a/lib/features/chat/presentation/pages/chat_screen.dart +++ b/lib/features/chat/presentation/pages/chat_screen.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + 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'; @@ -20,19 +22,15 @@ class ChatScreen extends StatefulWidget { class _ChatScreenState extends State { final scrollController = ScrollController(); + bool isLoading = false; Widget build(BuildContext context) { return BlocProvider( create: (BuildContext context) => sl()..initChat(widget.chatId), child: BlocBuilder( builder: (context, state) { - if (state is ChatRoomStateLoading) { - return Scaffold( - body: Center( - child: CupertinoActivityIndicator(), - ), - ); - } else if (state is ChatRoomStateLoaded) { + setupScrollController(context); + if (state is ChatRoomStateLoaded) { return _buildChat(context, state); } else if (state is ChatRoomStateError) { return Scaffold( @@ -55,16 +53,16 @@ class _ChatScreenState extends State { void setupScrollController(BuildContext context) { scrollController.addListener(() { + /// todo change rule for request new page if (scrollController.position.atEdge) { if (scrollController.position.pixels != 0) { - context.read(); + context.read().loadNextPage(widget.chatId); } } }); } _buildChat(BuildContext context, ChatRoomStateLoaded state) { - mediaQueryData = MediaQuery.of(context); return Scaffold( resizeToAvoidBottomInset: true, backgroundColor: PrimaryColors().gray50, @@ -136,12 +134,24 @@ class _ChatScreenState extends State { padding: EdgeInsets.symmetric(vertical: 16), sliver: SliverList( delegate: SliverChildBuilderDelegate( - (context, index) => ChatBubbleWidget( - text: state.chatMessages.messagesList[index].data.trim(), - isCurrentUser: state.chatRoom.users['to_chat_user']!.id != state.chatMessages.messagesList[index].authorId, - mediaData: state.chatMessages.messagesList[index].mediaData ?? [], - ), - childCount: state.chatMessages.messagesList.length, + (context, index) { + if (index < state.chatMessages.length) { + return ChatBubbleWidget( + text: state.chatMessages[index].data.trim(), + isCurrentUser: state.chatRoom.users['to_chat_user']!.id != state.chatMessages[index].authorId, + mediaData: state.chatMessages[index].mediaData ?? [], + ); + } else { + Timer(const Duration(milliseconds: 30), () { + scrollController.jumpTo(scrollController.position.maxScrollExtent); + }); + return Padding( + padding: const EdgeInsets.all(8), + child: Center(child: CupertinoActivityIndicator()), + ); + } + }, + childCount: state.chatMessages.length + (state.isLoading ? 1 : 0), ), ), ), diff --git a/lib/features/chat/repositories/chat_repository.dart b/lib/features/chat/repositories/chat_repository.dart index 38383f2..dbc6760 100644 --- a/lib/features/chat/repositories/chat_repository.dart +++ b/lib/features/chat/repositories/chat_repository.dart @@ -19,9 +19,9 @@ class ChatRepository { } } - Future getChatMessages(String chatId) async { + Future getChatMessages(String chatId, int page) async { try { - return (await chatService.getChatMessages(chatId)); + return (await chatService.getChatMessages(chatId, page)); } catch (e) { print(e); rethrow; diff --git a/lib/features/chat/services/chat_service.dart b/lib/features/chat/services/chat_service.dart index 3dd4a12..fa81a00 100644 --- a/lib/features/chat/services/chat_service.dart +++ b/lib/features/chat/services/chat_service.dart @@ -13,8 +13,8 @@ abstract class ChatService { @GET('/chat/show/{id}') Future> getChatRoom(@Path() String id); - @GET('/chat/show/{id}/messages') - Future getChatMessages(@Path() String id); + @GET('/chat/show/{id}/messages?page={page}') + Future getChatMessages(@Path() String id, @Path() int page); @GET('/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 f4f04d1..be6ed45 100644 --- a/lib/features/chat/services/chat_service.g.dart +++ b/lib/features/chat/services/chat_service.g.dart @@ -47,7 +47,10 @@ class _ChatService implements ChatService { } @override - Future getChatMessages(String id) async { + Future getChatMessages( + String id, + int page, + ) async { final _extra = {}; final queryParameters = {}; final _headers = {}; @@ -60,7 +63,7 @@ class _ChatService implements ChatService { ) .compose( _dio.options, - '/chat/show/${id}/messages', + '/chat/show/${id}/messages?page=${page}', queryParameters: queryParameters, data: _data, ) -- 2.49.1 From 5f88f49c71891574b9f5cc63c8cb8952e976469e Mon Sep 17 00:00:00 2001 From: alex Date: Fri, 5 Jul 2024 22:28:03 +0300 Subject: [PATCH 034/110] feat(chat): add chat lazy loading, send message and websocket init for notifications and new chat messages --- lib/app_router.dart | 3 + .../initialization_cubit.dart | 36 ++++++++ .../bloc/chat_room_cubit/chat_room_cubit.dart | 52 ++++++----- .../chat/presentation/pages/chat_screen.dart | 91 ++++++++++--------- .../bloc/chat_select_bloc.dart | 21 +++-- .../chat/repositories/chat_repository.dart | 23 ++++- lib/features/chat/services/chat_service.dart | 18 +++- .../chat/services/chat_service.g.dart | 53 ++++++++++- lib/locator_service.dart | 2 +- lib/main.dart | 2 +- pubspec.yaml | 28 +----- 11 files changed, 216 insertions(+), 113 deletions(-) diff --git a/lib/app_router.dart b/lib/app_router.dart index 30cda0b..b8f7008 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -1,3 +1,4 @@ +import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.dart'; import 'package:eatvio_app/core/token_storage.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'; @@ -32,6 +33,7 @@ import 'package:eatvio_app/presentation/registration/weight_screen/weight_screen import 'package:eatvio_app/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'; class AppRouter { @@ -46,6 +48,7 @@ class AppRouter { name: 'authScreen', redirect: (context, state) async { if (await TokenStorage.haveTokenInStorage()) { + await context.read().runInitialization(); return '/my-profile-screen'; } return null; diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index 4db6546..89b6794 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -9,6 +9,38 @@ class InitializationCubit extends Cubit { InitializationCubit({required this.chatRepository}) : super(const InitializationState.loading()); + Future subscribeNotifications(int userId, PusherChannelsClient client) async { + final privateNotificationChannel = await client.privateChannel( + 'private-message-events.$userId', + authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( + authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), + headers: { + 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', + }, + ), + ); + + privateNotificationChannel.subscribe(); + + privateNotificationChannel.bindToAll().listen((event) {}); + } + + Future subscribeChatMessages(int userId, PusherChannelsClient client) async { + final privateMessagesChannel = await client.privateChannel( + 'private-new-chat-messages.$userId', + authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( + authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), + headers: { + 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', + }, + ), + ); + + privateMessagesChannel.subscribe(); + + privateMessagesChannel.bindToAll().listen((event) {}); + } + Future runInitialization() async { try { await TokenStorage.haveTokenInStorage(); @@ -40,6 +72,10 @@ class InitializationCubit extends Cubit { ), ); await client.connect(); + + await subscribeNotifications(wsUrl.userId, client); + await subscribeChatMessages(wsUrl.userId, client); + emit(InitializationState.success( client: client, )); diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart index 712adf0..96e2bd2 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart @@ -1,4 +1,5 @@ import 'dart:convert'; +import 'dart:io'; import 'package:dart_pusher_channels/dart_pusher_channels.dart'; import 'package:easy_debounce/easy_debounce.dart'; @@ -8,43 +9,47 @@ import 'package:eatvio_app/core/token_storage.dart'; import 'package:eatvio_app/features/chat/models/chat_message_model.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; -import 'package:eatvio_app/locator_service.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class ChatRoomCubit extends Cubit { final ChatRepository chatRepository; + final InitializationCubit initializationCubit; int currentPage = 1; late final int lastPage; + bool isLoading = false; late final PusherChannelsClient client; - late final PrivateChannel privateChannel; + late final PrivateChannel privateChatChannel; ChatRoomCubit({ required this.chatRepository, + required this.initializationCubit, }) : super(ChatRoomState.loading()); loadNextPage(String chatId) async { - if (currentPage < lastPage) { + if (currentPage < lastPage && !isLoading) { + isLoading = true; + emit(ChatRoomState.loaded( chatRoom: (state as ChatRoomStateLoaded).chatRoom, chatMessages: (state as ChatRoomStateLoaded).chatMessages, isTyping: (state as ChatRoomStateLoaded).isTyping, - isLoading: true, + isLoading: isLoading, )); try { final chatMessages = await chatRepository.getChatMessages(chatId, currentPage + 1); + isLoading = false; emit(ChatRoomState.loaded( chatRoom: (state as ChatRoomStateLoaded).chatRoom, chatMessages: [...(state as ChatRoomStateLoaded).chatMessages, ...chatMessages.messagesList], isTyping: (state as ChatRoomStateLoaded).isTyping, - isLoading: false, + isLoading: isLoading, )); currentPage++; - } catch (e) { print(e); emit(ChatRoomState.error(errorMessage: 'Ошибка получеия данных')); @@ -59,20 +64,13 @@ class ChatRoomCubit extends Cubit { final chatMessages = await chatRepository.getChatMessages(chatId, currentPage); lastPage = chatMessages.meta.lastPage; - final initCubit = sl(); - - if (initCubit.state is InitializationStateSuccess) { - await subscribeToChatChannel(initCubit: initCubit, chatId: chatId); - } else { - await initCubit.runInitialization(); - await subscribeToChatChannel(initCubit: initCubit, chatId: chatId); - } + await subscribeToChatChannel(initCubit: initializationCubit, chatId: chatId); emit(ChatRoomState.loaded( chatRoom: chatRoom, chatMessages: chatMessages.messagesList, isTyping: false, - isLoading: false, + isLoading: isLoading, )); } catch (e) { emit(ChatRoomState.error(errorMessage: 'Ошибка получеия данных')); @@ -85,7 +83,7 @@ class ChatRoomCubit extends Cubit { }) async { client = (initCubit.state as InitializationStateSuccess).client; - privateChannel = await client.privateChannel( + privateChatChannel = await client.privateChannel( 'private-direct-chat.$chatId', authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), @@ -95,9 +93,9 @@ class ChatRoomCubit extends Cubit { ), ); - privateChannel.subscribe(); + privateChatChannel.subscribe(); - privateChannel.bind('App\\Events\\ChatMessageUpdated').listen((event) { + privateChatChannel.bind('App\\Events\\ChatMessageUpdated').listen((event) { List messagesList = [ ChatMessageModel.fromJson(jsonDecode(event.data)['message']), ...(state as ChatRoomStateLoaded).chatMessages, @@ -107,18 +105,18 @@ class ChatRoomCubit extends Cubit { chatRoom: (state as ChatRoomStateLoaded).chatRoom, chatMessages: messagesList, isTyping: (state as ChatRoomStateLoaded).isTyping, - isLoading: false, + isLoading: isLoading, ), ); }); - privateChannel.bind('client-typing').listen((event) { + privateChatChannel.bind('client-typing').listen((event) { emit( ChatRoomState.loaded( chatRoom: (state as ChatRoomStateLoaded).chatRoom, chatMessages: (state as ChatRoomStateLoaded).chatMessages, isTyping: true, - isLoading: false, + isLoading: isLoading, ), ); EasyDebounce.debounce( @@ -129,16 +127,24 @@ class ChatRoomCubit extends Cubit { chatRoom: (state as ChatRoomStateLoaded).chatRoom, chatMessages: (state as ChatRoomStateLoaded).chatMessages, isTyping: false, - isLoading: false, + isLoading: isLoading, ), ), ); }); } + sendMessage({ + required String chatId, + required String data, + required List filesList, + }) async { + await chatRepository.sendMessage(chatId: chatId, data: data); + } + @override Future close() async { - privateChannel.unsubscribe(); + privateChatChannel.unsubscribe(); super.close(); } } diff --git a/lib/features/chat/presentation/pages/chat_screen.dart b/lib/features/chat/presentation/pages/chat_screen.dart index 7d9528f..258b731 100644 --- a/lib/features/chat/presentation/pages/chat_screen.dart +++ b/lib/features/chat/presentation/pages/chat_screen.dart @@ -1,5 +1,3 @@ -import 'dart:async'; - 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'; @@ -7,6 +5,7 @@ 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'; class ChatScreen extends StatefulWidget { final String chatId; @@ -22,14 +21,13 @@ class ChatScreen extends StatefulWidget { class _ChatScreenState extends State { final scrollController = ScrollController(); - bool isLoading = false; + final TextEditingController textEditingController = TextEditingController(); Widget build(BuildContext context) { return BlocProvider( create: (BuildContext context) => sl()..initChat(widget.chatId), child: BlocBuilder( builder: (context, state) { - setupScrollController(context); if (state is ChatRoomStateLoaded) { return _buildChat(context, state); } else if (state is ChatRoomStateError) { @@ -51,17 +49,6 @@ class _ChatScreenState extends State { ); } - void setupScrollController(BuildContext context) { - scrollController.addListener(() { - /// todo change rule for request new page - if (scrollController.position.atEdge) { - if (scrollController.position.pixels != 0) { - context.read().loadNextPage(widget.chatId); - } - } - }); - } - _buildChat(BuildContext context, ChatRoomStateLoaded state) { return Scaffold( resizeToAvoidBottomInset: true, @@ -125,37 +112,39 @@ class _ChatScreenState extends State { child: Container( color: Color(0xFFF0F2F5), width: double.maxFinite, - child: CustomScrollView( - physics: BouncingScrollPhysics(), - controller: scrollController, - reverse: true, - slivers: [ - SliverPadding( - padding: EdgeInsets.symmetric(vertical: 16), - sliver: SliverList( - delegate: SliverChildBuilderDelegate( - (context, index) { - if (index < state.chatMessages.length) { - return ChatBubbleWidget( - text: state.chatMessages[index].data.trim(), - isCurrentUser: state.chatRoom.users['to_chat_user']!.id != state.chatMessages[index].authorId, - mediaData: state.chatMessages[index].mediaData ?? [], - ); - } else { - Timer(const Duration(milliseconds: 30), () { - scrollController.jumpTo(scrollController.position.maxScrollExtent); - }); - return Padding( - padding: const EdgeInsets.all(8), - child: Center(child: CupertinoActivityIndicator()), - ); - } - }, - childCount: state.chatMessages.length + (state.isLoading ? 1 : 0), + child: LazyLoadScrollView( + onEndOfPage: () => context.read().loadNextPage(widget.chatId), + isLoading: state.isLoading, + scrollOffset: MediaQuery.of(context).size.height.toInt(), + child: CustomScrollView( + physics: BouncingScrollPhysics(), + controller: scrollController, + reverse: true, + slivers: [ + SliverPadding( + padding: EdgeInsets.symmetric(vertical: 16), + sliver: SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) { + if (index < state.chatMessages.length) { + return ChatBubbleWidget( + text: state.chatMessages[index].data.trim(), + isCurrentUser: state.chatRoom.users['to_chat_user']!.id != state.chatMessages[index].authorId, + mediaData: state.chatMessages[index].mediaData ?? [], + ); + } else { + return Padding( + padding: const EdgeInsets.all(8), + child: Center(child: CupertinoActivityIndicator()), + ); + } + }, + childCount: state.chatMessages.length + (state.isLoading ? 1 : 0), + ), ), ), - ), - ], + ], + ), ), ), ), @@ -182,6 +171,7 @@ class _ChatScreenState extends State { SizedBox( width: mediaQueryData.size.width - 96, child: TextFormField( + controller: textEditingController, maxLines: 5, minLines: 1, keyboardType: TextInputType.multiline, @@ -228,7 +218,18 @@ class _ChatScreenState extends State { SizedBox(width: 8), InkWell( borderRadius: BorderRadiusStyle.circleBorder17, - onTap: () {}, + onTap: () { + if (textEditingController.text.isNotEmpty) { + context.read().sendMessage( + chatId: widget.chatId, + data: textEditingController.text.trim(), + filesList: [], + ); + setState(() { + textEditingController.clear(); + }); + } + }, child: Ink( height: 32, width: 32, 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 9bd2845..a055b5e 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 @@ -13,6 +13,7 @@ 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. @@ -68,15 +69,19 @@ class ChatSelectBloc extends Bloc { if (data is Map && data.containsKey('chatRooms')) { if (state is ChatSelectLoadedState) { var currentState = state as ChatSelectLoadedState; - emit(currentState.copyWith( - chatSelectModelObj: currentState.chatSelectModelObj, - chatRooms: currentState.chatRooms, - ),); + emit( + currentState.copyWith( + chatSelectModelObj: currentState.chatSelectModelObj, + chatRooms: currentState.chatRooms, + ), + ); } else { - emit(ChatSelectLoadedState( - chatRooms: fillChatEntryList(data['chatRooms']), - //chatRooms: [], - ),); + emit( + ChatSelectLoadedState( + chatRooms: fillChatEntryList(data['chatRooms']), + //chatRooms: [], + ), + ); } } else { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку diff --git a/lib/features/chat/repositories/chat_repository.dart b/lib/features/chat/repositories/chat_repository.dart index dbc6760..c35847f 100644 --- a/lib/features/chat/repositories/chat_repository.dart +++ b/lib/features/chat/repositories/chat_repository.dart @@ -1,3 +1,5 @@ +import 'dart:io'; + import 'package:eatvio_app/features/chat/models/chat_messages_model.dart'; import 'package:eatvio_app/features/chat/models/chat_room_model.dart'; import 'package:eatvio_app/features/chat/models/websocket_info_model.dart'; @@ -10,9 +12,26 @@ class ChatRepository { required this.chatService, }); + Future sendMessage({ + required String chatId, + String? data, + List? filesList, + }) async { + try { + await chatService.sendMessage( + id: chatId, + data: data, + filesList: filesList, + ); + } catch (e) { + print(e); + rethrow; + } + } + Future getChatRoom(String chatId) async { try { - return (await chatService.getChatRoom(chatId))['chatRoom']!; + return (await chatService.getChatRoom(id: chatId))['chatRoom']!; } catch (e) { print(e); rethrow; @@ -21,7 +40,7 @@ class ChatRepository { Future getChatMessages(String chatId, int page) async { try { - return (await chatService.getChatMessages(chatId, page)); + return (await chatService.getChatMessages(id: chatId, page: page)); } catch (e) { print(e); rethrow; diff --git a/lib/features/chat/services/chat_service.dart b/lib/features/chat/services/chat_service.dart index fa81a00..675d680 100644 --- a/lib/features/chat/services/chat_service.dart +++ b/lib/features/chat/services/chat_service.dart @@ -1,3 +1,5 @@ +import 'dart:io'; + 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'; @@ -11,10 +13,22 @@ abstract class ChatService { factory ChatService(Dio dio, {String baseUrl}) = _ChatService; @GET('/chat/show/{id}') - Future> getChatRoom(@Path() String id); + Future> getChatRoom({ + @Path() required String id, + }); + + @POST('/chat/{id}/message/send') + Future sendMessage({ + @Path() required String id, + @Part() String? data, + @Part() List? filesList, + }); @GET('/chat/show/{id}/messages?page={page}') - Future getChatMessages(@Path() String id, @Path() int page); + Future getChatMessages({ + @Path() required String id, + @Path() required int page, + }); @GET('/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 be6ed45..65eb7c5 100644 --- a/lib/features/chat/services/chat_service.g.dart +++ b/lib/features/chat/services/chat_service.g.dart @@ -19,7 +19,7 @@ class _ChatService implements ChatService { String? baseUrl; @override - Future> getChatRoom(String id) async { + Future> getChatRoom({required String id}) async { final _extra = {}; final queryParameters = {}; final _headers = {}; @@ -47,10 +47,53 @@ class _ChatService implements ChatService { } @override - Future getChatMessages( - String id, - int page, - ) async { + Future sendMessage({ + required String id, + String? data, + List? filesList, + }) async { + final _extra = {}; + final queryParameters = {}; + queryParameters.removeWhere((k, v) => v == null); + final _headers = {}; + final _data = FormData(); + if (data != null) { + _data.fields.add(MapEntry( + 'data', + data, + )); + } + if (filesList != null) { + _data.files.addAll(filesList.map((i) => MapEntry( + 'filesList', + MultipartFile.fromFileSync( + i.path, + filename: i.path.split(Platform.pathSeparator).last, + )))); + } + await _dio.fetch(_setStreamType(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/chat/${id}/message/send', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + } + + @override + Future getChatMessages({ + required String id, + required int page, + }) async { final _extra = {}; final queryParameters = {}; final _headers = {}; diff --git a/lib/locator_service.dart b/lib/locator_service.dart index fb2637e..5a924d2 100644 --- a/lib/locator_service.dart +++ b/lib/locator_service.dart @@ -18,7 +18,7 @@ Future init() async { // BLoC / Cubit sl.registerLazySingleton(() => InitializationCubit(chatRepository: sl())); - sl.registerFactory(() => ChatRoomCubit(chatRepository: sl())); + sl.registerFactory(() => ChatRoomCubit(chatRepository: sl(), initializationCubit: sl())); sl.registerFactory(() => FeedCubit(feedRepository: sl())); sl.registerFactory(() => BlogPostCubit(blogPostRepository: sl())); diff --git a/lib/main.dart b/lib/main.dart index 684e227..3f285ad 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -42,7 +42,7 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MultiBlocProvider( providers: [ - BlocProvider(create: (context) => InitializationCubit(chatRepository: 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/pubspec.yaml b/pubspec.yaml index 256f892..87ed29e 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -13,61 +13,37 @@ dependencies: flutter_localizations: sdk: flutter - # BLoC flutter_bloc: ^8.1.6 - # local storage shared_preferences: ^2.2.3 hive: ^2.2.3 hive_flutter: ^1.1.0 - # cached_network_image: ^3.3.1 - # flutter_svg: ^2.0.10 - # equatable: ^2.0.5 - # freezed_annotation: ^2.4.2 - # json_annotation: ^4.9.0 - # validators: ^3.0.0 - # isar_flutter_libs: ^3.1.0 - # 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 - # flutter_typeahead: ^5.2.0 - # navigation go_router: ^14.2.0 - # keyboard_dismisser: ^3.0.0 - # service generator retrofit: ^4.1.0 - # di get_it: ^7.7.0 - # http request dio: ^5.5.0 - # pusher dart_pusher_channels: ^1.2.2 - # photo gallery viewer + dismissible page photo_view: ^0.15.0 dismissible_page: ^1.0.2 - # url launcher url_launcher: ^6.3.0 - # debounce easy_debounce: ^2.0.3 + lazy_load_scrollview: ^1.3.0 + badges: ^3.1.2 dev_dependencies: build_runner: ^2.4.11 -- 2.49.1 From f79b9f03ae9e4343f78cb93f506a5f60093d072d Mon Sep 17 00:00:00 2001 From: alex Date: Tue, 9 Jul 2024 11:17:32 +0300 Subject: [PATCH 035/110] feat(chat): add badges --- lib/app_router.dart | 2 +- .../initialization_cubit.dart | 11 +- .../new_messages_cubit.dart | 13 + .../new_messages_state.dart | 18 + .../new_messages_state.freezed.dart | 616 +++++++++++++++++ .../notifications_cubit.dart | 13 + .../notifications_state.dart | 18 + .../notifications_state.freezed.dart | 621 ++++++++++++++++++ .../widgets/bottom_navigation_bar_widget.dart | 77 ++- .../chat/presentation/pages/chat_screen.dart | 4 +- lib/locator_service.dart | 4 + lib/main.dart | 5 + 12 files changed, 1372 insertions(+), 30 deletions(-) create mode 100644 lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart create mode 100644 lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.dart create mode 100644 lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart create mode 100644 lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_cubit.dart create mode 100644 lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.dart create mode 100644 lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart rename lib/{ => features/bottom_navigation_bar/presentation}/widgets/bottom_navigation_bar_widget.dart (60%) diff --git a/lib/app_router.dart b/lib/app_router.dart index b8f7008..02c517f 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -30,7 +30,7 @@ import 'package:eatvio_app/presentation/registration/language_select_screen/lang 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/widgets/bottom_navigation_bar_widget.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'; diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index 89b6794..a7034e2 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -2,7 +2,10 @@ import 'package:dart_pusher_channels/dart_pusher_channels.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_state.dart'; import 'package:eatvio_app/core/token_storage.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/notifications_cubit/notifications_cubit.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; +import 'package:eatvio_app/locator_service.dart'; class InitializationCubit extends Cubit { final ChatRepository chatRepository; @@ -22,7 +25,9 @@ class InitializationCubit extends Cubit { privateNotificationChannel.subscribe(); - privateNotificationChannel.bindToAll().listen((event) {}); + privateNotificationChannel.bindToAll().listen((event) { + sl().incrementCounter(); + }); } Future subscribeChatMessages(int userId, PusherChannelsClient client) async { @@ -38,7 +43,9 @@ class InitializationCubit extends Cubit { privateMessagesChannel.subscribe(); - privateMessagesChannel.bindToAll().listen((event) {}); + privateMessagesChannel.bindToAll().listen((event) { + sl().incrementCounter(); + }); } Future runInitialization() async { diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart new file mode 100644 index 0000000..8b2a0f5 --- /dev/null +++ b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart @@ -0,0 +1,13 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.dart'; + +class NewMessagesCubit extends Cubit { + int _messagesCount = 0; + + NewMessagesCubit() : super(const NewMessagesState.empty()); + + incrementCounter() { + _messagesCount++; + emit(NewMessagesState.loaded(messagesCount: _messagesCount)); + } +} diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.dart b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.dart new file mode 100644 index 0000000..4ed4856 --- /dev/null +++ b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.dart @@ -0,0 +1,18 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'new_messages_state.freezed.dart'; + +@freezed +abstract class NewMessagesState with _$NewMessagesState { + const factory NewMessagesState() = _NewMessagesState; + + const factory NewMessagesState.empty() = NewMessagesStateEmpty; + + const factory NewMessagesState.loaded({ + required int messagesCount, + }) = NewMessagesStateLoaded; + + const factory NewMessagesState.error({ + required String errorMessage, + }) = NewMessagesStateError; +} diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart new file mode 100644 index 0000000..02a1c4b --- /dev/null +++ b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart @@ -0,0 +1,616 @@ +// 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 'new_messages_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 _$NewMessagesState { + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() empty, + required TResult Function(int messagesCount) loaded, + required TResult Function(String errorMessage) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? empty, + TResult? Function(int messagesCount)? loaded, + TResult? Function(String errorMessage)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? empty, + TResult Function(int messagesCount)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map( + TResult Function(_NewMessagesState value) $default, { + required TResult Function(NewMessagesStateEmpty value) empty, + required TResult Function(NewMessagesStateLoaded value) loaded, + required TResult Function(NewMessagesStateError value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_NewMessagesState value)? $default, { + TResult? Function(NewMessagesStateEmpty value)? empty, + TResult? Function(NewMessagesStateLoaded value)? loaded, + TResult? Function(NewMessagesStateError value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap( + TResult Function(_NewMessagesState value)? $default, { + TResult Function(NewMessagesStateEmpty value)? empty, + TResult Function(NewMessagesStateLoaded value)? loaded, + TResult Function(NewMessagesStateError value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $NewMessagesStateCopyWith<$Res> { + factory $NewMessagesStateCopyWith( + NewMessagesState value, $Res Function(NewMessagesState) then) = + _$NewMessagesStateCopyWithImpl<$Res, NewMessagesState>; +} + +/// @nodoc +class _$NewMessagesStateCopyWithImpl<$Res, $Val extends NewMessagesState> + implements $NewMessagesStateCopyWith<$Res> { + _$NewMessagesStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; +} + +/// @nodoc +abstract class _$$NewMessagesStateImplCopyWith<$Res> { + factory _$$NewMessagesStateImplCopyWith(_$NewMessagesStateImpl value, + $Res Function(_$NewMessagesStateImpl) then) = + __$$NewMessagesStateImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$NewMessagesStateImplCopyWithImpl<$Res> + extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateImpl> + implements _$$NewMessagesStateImplCopyWith<$Res> { + __$$NewMessagesStateImplCopyWithImpl(_$NewMessagesStateImpl _value, + $Res Function(_$NewMessagesStateImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$NewMessagesStateImpl implements _NewMessagesState { + const _$NewMessagesStateImpl(); + + @override + String toString() { + return 'NewMessagesState()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$NewMessagesStateImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() empty, + required TResult Function(int messagesCount) loaded, + required TResult Function(String errorMessage) error, + }) { + return $default(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? empty, + TResult? Function(int messagesCount)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return $default?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? empty, + TResult Function(int messagesCount)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_NewMessagesState value) $default, { + required TResult Function(NewMessagesStateEmpty value) empty, + required TResult Function(NewMessagesStateLoaded value) loaded, + required TResult Function(NewMessagesStateError value) error, + }) { + return $default(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_NewMessagesState value)? $default, { + TResult? Function(NewMessagesStateEmpty value)? empty, + TResult? Function(NewMessagesStateLoaded value)? loaded, + TResult? Function(NewMessagesStateError value)? error, + }) { + return $default?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_NewMessagesState value)? $default, { + TResult Function(NewMessagesStateEmpty value)? empty, + TResult Function(NewMessagesStateLoaded value)? loaded, + TResult Function(NewMessagesStateError value)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(this); + } + return orElse(); + } +} + +abstract class _NewMessagesState implements NewMessagesState { + const factory _NewMessagesState() = _$NewMessagesStateImpl; +} + +/// @nodoc +abstract class _$$NewMessagesStateEmptyImplCopyWith<$Res> { + factory _$$NewMessagesStateEmptyImplCopyWith( + _$NewMessagesStateEmptyImpl value, + $Res Function(_$NewMessagesStateEmptyImpl) then) = + __$$NewMessagesStateEmptyImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$NewMessagesStateEmptyImplCopyWithImpl<$Res> + extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateEmptyImpl> + implements _$$NewMessagesStateEmptyImplCopyWith<$Res> { + __$$NewMessagesStateEmptyImplCopyWithImpl(_$NewMessagesStateEmptyImpl _value, + $Res Function(_$NewMessagesStateEmptyImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$NewMessagesStateEmptyImpl implements NewMessagesStateEmpty { + const _$NewMessagesStateEmptyImpl(); + + @override + String toString() { + return 'NewMessagesState.empty()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$NewMessagesStateEmptyImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() empty, + required TResult Function(int messagesCount) loaded, + required TResult Function(String errorMessage) error, + }) { + return empty(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? empty, + TResult? Function(int messagesCount)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return empty?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? empty, + TResult Function(int messagesCount)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (empty != null) { + return empty(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_NewMessagesState value) $default, { + required TResult Function(NewMessagesStateEmpty value) empty, + required TResult Function(NewMessagesStateLoaded value) loaded, + required TResult Function(NewMessagesStateError value) error, + }) { + return empty(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_NewMessagesState value)? $default, { + TResult? Function(NewMessagesStateEmpty value)? empty, + TResult? Function(NewMessagesStateLoaded value)? loaded, + TResult? Function(NewMessagesStateError value)? error, + }) { + return empty?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_NewMessagesState value)? $default, { + TResult Function(NewMessagesStateEmpty value)? empty, + TResult Function(NewMessagesStateLoaded value)? loaded, + TResult Function(NewMessagesStateError value)? error, + required TResult orElse(), + }) { + if (empty != null) { + return empty(this); + } + return orElse(); + } +} + +abstract class NewMessagesStateEmpty implements NewMessagesState { + const factory NewMessagesStateEmpty() = _$NewMessagesStateEmptyImpl; +} + +/// @nodoc +abstract class _$$NewMessagesStateLoadedImplCopyWith<$Res> { + factory _$$NewMessagesStateLoadedImplCopyWith( + _$NewMessagesStateLoadedImpl value, + $Res Function(_$NewMessagesStateLoadedImpl) then) = + __$$NewMessagesStateLoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({int messagesCount}); +} + +/// @nodoc +class __$$NewMessagesStateLoadedImplCopyWithImpl<$Res> + extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateLoadedImpl> + implements _$$NewMessagesStateLoadedImplCopyWith<$Res> { + __$$NewMessagesStateLoadedImplCopyWithImpl( + _$NewMessagesStateLoadedImpl _value, + $Res Function(_$NewMessagesStateLoadedImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? messagesCount = null, + }) { + return _then(_$NewMessagesStateLoadedImpl( + messagesCount: null == messagesCount + ? _value.messagesCount + : messagesCount // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class _$NewMessagesStateLoadedImpl implements NewMessagesStateLoaded { + const _$NewMessagesStateLoadedImpl({required this.messagesCount}); + + @override + final int messagesCount; + + @override + String toString() { + return 'NewMessagesState.loaded(messagesCount: $messagesCount)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$NewMessagesStateLoadedImpl && + (identical(other.messagesCount, messagesCount) || + other.messagesCount == messagesCount)); + } + + @override + int get hashCode => Object.hash(runtimeType, messagesCount); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> + get copyWith => __$$NewMessagesStateLoadedImplCopyWithImpl< + _$NewMessagesStateLoadedImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() empty, + required TResult Function(int messagesCount) loaded, + required TResult Function(String errorMessage) error, + }) { + return loaded(messagesCount); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? empty, + TResult? Function(int messagesCount)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return loaded?.call(messagesCount); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? empty, + TResult Function(int messagesCount)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(messagesCount); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_NewMessagesState value) $default, { + required TResult Function(NewMessagesStateEmpty value) empty, + required TResult Function(NewMessagesStateLoaded value) loaded, + required TResult Function(NewMessagesStateError value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_NewMessagesState value)? $default, { + TResult? Function(NewMessagesStateEmpty value)? empty, + TResult? Function(NewMessagesStateLoaded value)? loaded, + TResult? Function(NewMessagesStateError value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_NewMessagesState value)? $default, { + TResult Function(NewMessagesStateEmpty value)? empty, + TResult Function(NewMessagesStateLoaded value)? loaded, + TResult Function(NewMessagesStateError value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class NewMessagesStateLoaded implements NewMessagesState { + const factory NewMessagesStateLoaded({required final int messagesCount}) = + _$NewMessagesStateLoadedImpl; + + int get messagesCount; + @JsonKey(ignore: true) + _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> + get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$NewMessagesStateErrorImplCopyWith<$Res> { + factory _$$NewMessagesStateErrorImplCopyWith( + _$NewMessagesStateErrorImpl value, + $Res Function(_$NewMessagesStateErrorImpl) then) = + __$$NewMessagesStateErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String errorMessage}); +} + +/// @nodoc +class __$$NewMessagesStateErrorImplCopyWithImpl<$Res> + extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateErrorImpl> + implements _$$NewMessagesStateErrorImplCopyWith<$Res> { + __$$NewMessagesStateErrorImplCopyWithImpl(_$NewMessagesStateErrorImpl _value, + $Res Function(_$NewMessagesStateErrorImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? errorMessage = null, + }) { + return _then(_$NewMessagesStateErrorImpl( + errorMessage: null == errorMessage + ? _value.errorMessage + : errorMessage // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$NewMessagesStateErrorImpl implements NewMessagesStateError { + const _$NewMessagesStateErrorImpl({required this.errorMessage}); + + @override + final String errorMessage; + + @override + String toString() { + return 'NewMessagesState.error(errorMessage: $errorMessage)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$NewMessagesStateErrorImpl && + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); + } + + @override + int get hashCode => Object.hash(runtimeType, errorMessage); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> + get copyWith => __$$NewMessagesStateErrorImplCopyWithImpl< + _$NewMessagesStateErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() empty, + required TResult Function(int messagesCount) loaded, + required TResult Function(String errorMessage) error, + }) { + return error(errorMessage); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? empty, + TResult? Function(int messagesCount)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return error?.call(errorMessage); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? empty, + TResult Function(int messagesCount)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(errorMessage); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_NewMessagesState value) $default, { + required TResult Function(NewMessagesStateEmpty value) empty, + required TResult Function(NewMessagesStateLoaded value) loaded, + required TResult Function(NewMessagesStateError value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_NewMessagesState value)? $default, { + TResult? Function(NewMessagesStateEmpty value)? empty, + TResult? Function(NewMessagesStateLoaded value)? loaded, + TResult? Function(NewMessagesStateError value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_NewMessagesState value)? $default, { + TResult Function(NewMessagesStateEmpty value)? empty, + TResult Function(NewMessagesStateLoaded value)? loaded, + TResult Function(NewMessagesStateError value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class NewMessagesStateError implements NewMessagesState { + const factory NewMessagesStateError({required final String errorMessage}) = + _$NewMessagesStateErrorImpl; + + String get errorMessage; + @JsonKey(ignore: true) + _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> + get copyWith => throw _privateConstructorUsedError; +} diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_cubit.dart b/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_cubit.dart new file mode 100644 index 0000000..ba5634c --- /dev/null +++ b/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_cubit.dart @@ -0,0 +1,13 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.dart'; + +class NotificationsCubit extends Cubit { + int _notificationsCount = 0; + + NotificationsCubit() : super(const NotificationsState.empty()); + + incrementCounter() { + _notificationsCount++; + emit(NotificationsState.loaded(notificationsCount: _notificationsCount)); + } +} diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.dart b/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.dart new file mode 100644 index 0000000..0f20a05 --- /dev/null +++ b/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.dart @@ -0,0 +1,18 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'notifications_state.freezed.dart'; + +@freezed +abstract class NotificationsState with _$NotificationsState { + const factory NotificationsState() = _NotificationsState; + + const factory NotificationsState.empty() = NotificationsStateEmpty; + + const factory NotificationsState.loaded({ + required int notificationsCount, + }) = NotificationsStateLoaded; + + const factory NotificationsState.error({ + required String errorMessage, + }) = NotificationsStateError; +} diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart b/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart new file mode 100644 index 0000000..0deeebb --- /dev/null +++ b/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart @@ -0,0 +1,621 @@ +// 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 'notifications_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 _$NotificationsState { + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() empty, + required TResult Function(int notificationsCount) loaded, + required TResult Function(String errorMessage) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? empty, + TResult? Function(int notificationsCount)? loaded, + TResult? Function(String errorMessage)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? empty, + TResult Function(int notificationsCount)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map( + TResult Function(_NotificationsState value) $default, { + required TResult Function(NotificationsStateEmpty value) empty, + required TResult Function(NotificationsStateLoaded value) loaded, + required TResult Function(NotificationsStateError value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_NotificationsState value)? $default, { + TResult? Function(NotificationsStateEmpty value)? empty, + TResult? Function(NotificationsStateLoaded value)? loaded, + TResult? Function(NotificationsStateError value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap( + TResult Function(_NotificationsState value)? $default, { + TResult Function(NotificationsStateEmpty value)? empty, + TResult Function(NotificationsStateLoaded value)? loaded, + TResult Function(NotificationsStateError value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $NotificationsStateCopyWith<$Res> { + factory $NotificationsStateCopyWith( + NotificationsState value, $Res Function(NotificationsState) then) = + _$NotificationsStateCopyWithImpl<$Res, NotificationsState>; +} + +/// @nodoc +class _$NotificationsStateCopyWithImpl<$Res, $Val extends NotificationsState> + implements $NotificationsStateCopyWith<$Res> { + _$NotificationsStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; +} + +/// @nodoc +abstract class _$$NotificationsStateImplCopyWith<$Res> { + factory _$$NotificationsStateImplCopyWith(_$NotificationsStateImpl value, + $Res Function(_$NotificationsStateImpl) then) = + __$$NotificationsStateImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$NotificationsStateImplCopyWithImpl<$Res> + extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateImpl> + implements _$$NotificationsStateImplCopyWith<$Res> { + __$$NotificationsStateImplCopyWithImpl(_$NotificationsStateImpl _value, + $Res Function(_$NotificationsStateImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$NotificationsStateImpl implements _NotificationsState { + const _$NotificationsStateImpl(); + + @override + String toString() { + return 'NotificationsState()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$NotificationsStateImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() empty, + required TResult Function(int notificationsCount) loaded, + required TResult Function(String errorMessage) error, + }) { + return $default(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? empty, + TResult? Function(int notificationsCount)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return $default?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? empty, + TResult Function(int notificationsCount)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_NotificationsState value) $default, { + required TResult Function(NotificationsStateEmpty value) empty, + required TResult Function(NotificationsStateLoaded value) loaded, + required TResult Function(NotificationsStateError value) error, + }) { + return $default(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_NotificationsState value)? $default, { + TResult? Function(NotificationsStateEmpty value)? empty, + TResult? Function(NotificationsStateLoaded value)? loaded, + TResult? Function(NotificationsStateError value)? error, + }) { + return $default?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_NotificationsState value)? $default, { + TResult Function(NotificationsStateEmpty value)? empty, + TResult Function(NotificationsStateLoaded value)? loaded, + TResult Function(NotificationsStateError value)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(this); + } + return orElse(); + } +} + +abstract class _NotificationsState implements NotificationsState { + const factory _NotificationsState() = _$NotificationsStateImpl; +} + +/// @nodoc +abstract class _$$NotificationsStateEmptyImplCopyWith<$Res> { + factory _$$NotificationsStateEmptyImplCopyWith( + _$NotificationsStateEmptyImpl value, + $Res Function(_$NotificationsStateEmptyImpl) then) = + __$$NotificationsStateEmptyImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$NotificationsStateEmptyImplCopyWithImpl<$Res> + extends _$NotificationsStateCopyWithImpl<$Res, + _$NotificationsStateEmptyImpl> + implements _$$NotificationsStateEmptyImplCopyWith<$Res> { + __$$NotificationsStateEmptyImplCopyWithImpl( + _$NotificationsStateEmptyImpl _value, + $Res Function(_$NotificationsStateEmptyImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$NotificationsStateEmptyImpl implements NotificationsStateEmpty { + const _$NotificationsStateEmptyImpl(); + + @override + String toString() { + return 'NotificationsState.empty()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$NotificationsStateEmptyImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() empty, + required TResult Function(int notificationsCount) loaded, + required TResult Function(String errorMessage) error, + }) { + return empty(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? empty, + TResult? Function(int notificationsCount)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return empty?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? empty, + TResult Function(int notificationsCount)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (empty != null) { + return empty(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_NotificationsState value) $default, { + required TResult Function(NotificationsStateEmpty value) empty, + required TResult Function(NotificationsStateLoaded value) loaded, + required TResult Function(NotificationsStateError value) error, + }) { + return empty(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_NotificationsState value)? $default, { + TResult? Function(NotificationsStateEmpty value)? empty, + TResult? Function(NotificationsStateLoaded value)? loaded, + TResult? Function(NotificationsStateError value)? error, + }) { + return empty?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_NotificationsState value)? $default, { + TResult Function(NotificationsStateEmpty value)? empty, + TResult Function(NotificationsStateLoaded value)? loaded, + TResult Function(NotificationsStateError value)? error, + required TResult orElse(), + }) { + if (empty != null) { + return empty(this); + } + return orElse(); + } +} + +abstract class NotificationsStateEmpty implements NotificationsState { + const factory NotificationsStateEmpty() = _$NotificationsStateEmptyImpl; +} + +/// @nodoc +abstract class _$$NotificationsStateLoadedImplCopyWith<$Res> { + factory _$$NotificationsStateLoadedImplCopyWith( + _$NotificationsStateLoadedImpl value, + $Res Function(_$NotificationsStateLoadedImpl) then) = + __$$NotificationsStateLoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({int notificationsCount}); +} + +/// @nodoc +class __$$NotificationsStateLoadedImplCopyWithImpl<$Res> + extends _$NotificationsStateCopyWithImpl<$Res, + _$NotificationsStateLoadedImpl> + implements _$$NotificationsStateLoadedImplCopyWith<$Res> { + __$$NotificationsStateLoadedImplCopyWithImpl( + _$NotificationsStateLoadedImpl _value, + $Res Function(_$NotificationsStateLoadedImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? notificationsCount = null, + }) { + return _then(_$NotificationsStateLoadedImpl( + notificationsCount: null == notificationsCount + ? _value.notificationsCount + : notificationsCount // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class _$NotificationsStateLoadedImpl implements NotificationsStateLoaded { + const _$NotificationsStateLoadedImpl({required this.notificationsCount}); + + @override + final int notificationsCount; + + @override + String toString() { + return 'NotificationsState.loaded(notificationsCount: $notificationsCount)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$NotificationsStateLoadedImpl && + (identical(other.notificationsCount, notificationsCount) || + other.notificationsCount == notificationsCount)); + } + + @override + int get hashCode => Object.hash(runtimeType, notificationsCount); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> + get copyWith => __$$NotificationsStateLoadedImplCopyWithImpl< + _$NotificationsStateLoadedImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() empty, + required TResult Function(int notificationsCount) loaded, + required TResult Function(String errorMessage) error, + }) { + return loaded(notificationsCount); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? empty, + TResult? Function(int notificationsCount)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return loaded?.call(notificationsCount); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? empty, + TResult Function(int notificationsCount)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(notificationsCount); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_NotificationsState value) $default, { + required TResult Function(NotificationsStateEmpty value) empty, + required TResult Function(NotificationsStateLoaded value) loaded, + required TResult Function(NotificationsStateError value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_NotificationsState value)? $default, { + TResult? Function(NotificationsStateEmpty value)? empty, + TResult? Function(NotificationsStateLoaded value)? loaded, + TResult? Function(NotificationsStateError value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_NotificationsState value)? $default, { + TResult Function(NotificationsStateEmpty value)? empty, + TResult Function(NotificationsStateLoaded value)? loaded, + TResult Function(NotificationsStateError value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class NotificationsStateLoaded implements NotificationsState { + const factory NotificationsStateLoaded( + {required final int notificationsCount}) = _$NotificationsStateLoadedImpl; + + int get notificationsCount; + @JsonKey(ignore: true) + _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> + get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$NotificationsStateErrorImplCopyWith<$Res> { + factory _$$NotificationsStateErrorImplCopyWith( + _$NotificationsStateErrorImpl value, + $Res Function(_$NotificationsStateErrorImpl) then) = + __$$NotificationsStateErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String errorMessage}); +} + +/// @nodoc +class __$$NotificationsStateErrorImplCopyWithImpl<$Res> + extends _$NotificationsStateCopyWithImpl<$Res, + _$NotificationsStateErrorImpl> + implements _$$NotificationsStateErrorImplCopyWith<$Res> { + __$$NotificationsStateErrorImplCopyWithImpl( + _$NotificationsStateErrorImpl _value, + $Res Function(_$NotificationsStateErrorImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? errorMessage = null, + }) { + return _then(_$NotificationsStateErrorImpl( + errorMessage: null == errorMessage + ? _value.errorMessage + : errorMessage // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$NotificationsStateErrorImpl implements NotificationsStateError { + const _$NotificationsStateErrorImpl({required this.errorMessage}); + + @override + final String errorMessage; + + @override + String toString() { + return 'NotificationsState.error(errorMessage: $errorMessage)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$NotificationsStateErrorImpl && + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); + } + + @override + int get hashCode => Object.hash(runtimeType, errorMessage); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> + get copyWith => __$$NotificationsStateErrorImplCopyWithImpl< + _$NotificationsStateErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() empty, + required TResult Function(int notificationsCount) loaded, + required TResult Function(String errorMessage) error, + }) { + return error(errorMessage); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? empty, + TResult? Function(int notificationsCount)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return error?.call(errorMessage); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? empty, + TResult Function(int notificationsCount)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(errorMessage); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_NotificationsState value) $default, { + required TResult Function(NotificationsStateEmpty value) empty, + required TResult Function(NotificationsStateLoaded value) loaded, + required TResult Function(NotificationsStateError value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_NotificationsState value)? $default, { + TResult? Function(NotificationsStateEmpty value)? empty, + TResult? Function(NotificationsStateLoaded value)? loaded, + TResult? Function(NotificationsStateError value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_NotificationsState value)? $default, { + TResult Function(NotificationsStateEmpty value)? empty, + TResult Function(NotificationsStateLoaded value)? loaded, + TResult Function(NotificationsStateError value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class NotificationsStateError implements NotificationsState { + const factory NotificationsStateError({required final String errorMessage}) = + _$NotificationsStateErrorImpl; + + String get errorMessage; + @JsonKey(ignore: true) + _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> + get copyWith => throw _privateConstructorUsedError; +} diff --git a/lib/widgets/bottom_navigation_bar_widget.dart b/lib/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart similarity index 60% rename from lib/widgets/bottom_navigation_bar_widget.dart rename to lib/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart index 51fd3e9..9865221 100644 --- a/lib/widgets/bottom_navigation_bar_widget.dart +++ b/lib/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart @@ -1,8 +1,13 @@ 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_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; +import 'package:badges/badges.dart' as badges; int currentBottomNavBarIndex = 0; @@ -113,36 +118,56 @@ class _BottomNavigationBarWidgetState extends State { ), BottomNavigationBarItem( label: "chat".tr, - icon: SvgPicture.asset( - ImageConstant.imgChat, - width: 24, - height: 24, - ), - activeIcon: SvgPicture.asset( - ImageConstant.imgChat, - width: 24, - height: 24, - colorFilter: ColorFilter.mode( - appTheme.blueA400, - BlendMode.srcIn, - ), + icon: BlocBuilder( + builder: (BuildContext context, NewMessagesState state) { + return badges.Badge( + position: badges.BadgePosition.topEnd(), + badgeContent: Text( + (state is NewMessagesStateLoaded) ? state.messagesCount.toString() : '0', + style: TextStyle( + color: Colors.white, + ), + ), + child: SvgPicture.asset( + ImageConstant.imgChat, + width: 24, + height: 24, + colorFilter: currentBottomNavBarIndex == 3 + ? ColorFilter.mode( + appTheme.blueA400, + BlendMode.srcIn, + ) + : null, + ), + ); + }, ), ), BottomNavigationBarItem( label: '', - icon: SvgPicture.asset( - ImageConstant.imgBell, - width: 24, - height: 24, - ), - activeIcon: SvgPicture.asset( - ImageConstant.imgBell, - width: 24, - height: 24, - colorFilter: ColorFilter.mode( - appTheme.blueA400, - BlendMode.srcIn, - ), + icon: BlocBuilder( + builder: (BuildContext context, NotificationsState state) { + return badges.Badge( + position: badges.BadgePosition.topEnd(), + badgeContent: Text( + (state is NotificationsStateLoaded) ? state.notificationsCount.toString() : '0', + style: TextStyle( + color: Colors.white, + ), + ), + child: SvgPicture.asset( + ImageConstant.imgBell, + colorFilter: currentBottomNavBarIndex == 4 + ? ColorFilter.mode( + appTheme.blueA400, + BlendMode.srcIn, + ) + : null, + width: 24, + height: 24, + ), + ); + }, ), ), BottomNavigationBarItem( diff --git a/lib/features/chat/presentation/pages/chat_screen.dart b/lib/features/chat/presentation/pages/chat_screen.dart index 258b731..d3ecef8 100644 --- a/lib/features/chat/presentation/pages/chat_screen.dart +++ b/lib/features/chat/presentation/pages/chat_screen.dart @@ -155,7 +155,9 @@ class _ChatScreenState extends State { children: [ SizedBox(width: 8), InkWell( - onTap: () {}, + onTap: () { + + }, borderRadius: BorderRadiusStyle.circleBorder17, child: Ink( height: 32, diff --git a/lib/locator_service.dart b/lib/locator_service.dart index 5a924d2..dfd6198 100644 --- a/lib/locator_service.dart +++ b/lib/locator_service.dart @@ -3,6 +3,8 @@ 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'; import 'package:eatvio_app/features/blog_post/services/blog_post_service.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/notifications_cubit/notifications_cubit.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; import 'package:eatvio_app/features/chat/services/chat_service.dart'; @@ -17,6 +19,8 @@ final sl = GetIt.instance; Future init() async { // BLoC / Cubit sl.registerLazySingleton(() => InitializationCubit(chatRepository: sl())); + sl.registerLazySingleton(() => NewMessagesCubit()); + sl.registerLazySingleton(() => NotificationsCubit()); sl.registerFactory(() => ChatRoomCubit(chatRepository: sl(), initializationCubit: sl())); sl.registerFactory(() => FeedCubit(feedRepository: sl())); diff --git a/lib/main.dart b/lib/main.dart index 3f285ad..e73bd42 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,6 +1,8 @@ import 'package:eatvio_app/app_router.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_state.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/notifications_cubit/notifications_cubit.dart'; 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'; @@ -43,6 +45,9 @@ class MyApp extends StatelessWidget { return MultiBlocProvider( providers: [ 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())), -- 2.49.1 From e180ff16b60cb91222ea35a1fde020c7632f9ffb Mon Sep 17 00:00:00 2001 From: alex Date: Tue, 9 Jul 2024 17:50:32 +0300 Subject: [PATCH 036/110] refactor(all): refactor --- lib/app_router.dart | 41 +- .../initialization_cubit.dart | 84 ++-- .../chat/presentation/pages/chat_screen.dart | 2 - .../chat_select_screen.dart | 30 +- .../models/feed_blog_post_settings_model.dart | 15 + ...feed_blog_post_settings_model.freezed.dart | 175 ++++++++ .../feed_blog_post_settings_model.g.dart | 21 + .../feed/repositories/feed_repository.dart | 2 +- lib/features/feed/services/feed_service.dart | 6 +- .../feed/services/feed_service.g.dart | 9 +- lib/main.dart | 1 - .../auth/auth_screen/auth_screen.dart | 2 +- .../bloc/my_profile_bloc.dart | 28 +- .../my_profile_screen/my_profile_screen.dart | 382 ++++++++++-------- .../bloc/recipe_edit_bloc.dart | 42 +- .../bloc/recipe_select_bloc.dart | 26 +- .../bloc/recipe_select_state.dart | 6 +- .../recipe_select_screen.dart | 1 + .../bloc/recipe_show_bloc.dart | 49 ++- .../additional_information_screen.dart | 166 +++++--- .../allergies_screen/allergies_screen.dart | 116 +++--- .../blood_pressure_screen.dart | 255 +++++++----- .../body_circumferences_screen.dart | 137 ++++--- .../city_of_living_screen.dart | 124 +++--- .../credentials_screen.dart | 143 ++++--- .../date_of_birth_screen.dart | 94 +++-- .../favorite_foods_screen.dart | 151 ++++--- .../favorite_sports_screen.dart | 124 +++--- .../gender_screen/gender_screen.dart | 70 ++-- .../height_screen/height_screen.dart | 42 +- .../language_select_screen.dart | 45 ++- .../medicine_intake_screen.dart | 136 ++++--- .../registration/name_screen/name_screen.dart | 125 +++--- .../weight_screen/weight_screen.dart | 42 +- lib/theme/theme_helper.dart | 113 +++--- lib/widgets/custom_navigation_menu_item.dart | 8 +- pubspec.yaml | 16 +- 37 files changed, 1706 insertions(+), 1123 deletions(-) create mode 100644 lib/features/feed/models/feed_blog_post_settings_model.dart create mode 100644 lib/features/feed/models/feed_blog_post_settings_model.freezed.dart create mode 100644 lib/features/feed/models/feed_blog_post_settings_model.g.dart diff --git a/lib/app_router.dart b/lib/app_router.dart index 02c517f..20905a6 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -48,7 +48,6 @@ class AppRouter { name: 'authScreen', redirect: (context, state) async { if (await TokenStorage.haveTokenInStorage()) { - await context.read().runInitialization(); return '/my-profile-screen'; } return null; @@ -106,29 +105,31 @@ class AppRouter { builder: (context, state) => BloodPressureScreen.builder(context, state.extra), routes: [ GoRoute( - path: 'favorite-sports-screen', - name: 'favoriteSportsScreen', - builder: (context, state) => FavoriteSportsScreen.builder(context, state.extra), + name: 'allergiesScreen', + path: 'allergiesScreen', + builder: (context, state) => AllergiesScreen.builder(context, state.extra), routes: [ GoRoute( - name: 'allergiesScreen', - path: 'allergiesScreen', - builder: (context, state) => AllergiesScreen.builder(context, state.extra), + name: 'medicineIntakeScreen', + path: 'medicine-intake-screen', + builder: (context, state) => MedicineIntakeScreen.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), + path: 'favorite-sports-screen', + name: 'favoriteSportsScreen', + builder: (context, state) => FavoriteSportsScreen.builder(context, state.extra), routes: [ GoRoute( - path: 'additional-information-screen', - name: 'additionalInformationScreen', - builder: (context, state) => AdditionalInformationScreen.builder(context, state.extra), + 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), + ), + ], ), ], ), @@ -166,6 +167,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/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index a7034e2..2052a25 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/features/chat/presentation/pages/chat_screen.dart b/lib/features/chat/presentation/pages/chat_screen.dart index d3ecef8..208ff96 100644 --- a/lib/features/chat/presentation/pages/chat_screen.dart +++ b/lib/features/chat/presentation/pages/chat_screen.dart @@ -179,7 +179,6 @@ class _ChatScreenState extends State { keyboardType: TextInputType.multiline, style: TextStyle( fontSize: 16, - fontFamily: 'Mulish', fontWeight: FontWeight.w400, color: Colors.black, ), @@ -188,7 +187,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/chat_select_screen.dart b/lib/features/chat/presentation/pages/chat_select_screen/chat_select_screen.dart index d98ea7f..dc3f3d2 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 @@ -42,18 +42,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/feed/models/feed_blog_post_settings_model.dart b/lib/features/feed/models/feed_blog_post_settings_model.dart new file mode 100644 index 0000000..fa72e97 --- /dev/null +++ b/lib/features/feed/models/feed_blog_post_settings_model.dart @@ -0,0 +1,15 @@ +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 0000000..7fd8a12 --- /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 0000000..3f48be1 --- /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/repositories/feed_repository.dart b/lib/features/feed/repositories/feed_repository.dart index 50799a0..319ac32 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 d4f728f..a961037 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('/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 03aa238..2ef8381 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', + '/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/main.dart b/lib/main.dart index e73bd42..7faced2 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -47,7 +47,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 4a74ba3..c435f2d 100644 --- a/lib/presentation/auth/auth_screen/auth_screen.dart +++ b/lib/presentation/auth/auth_screen/auth_screen.dart @@ -107,7 +107,7 @@ class AuthScreen extends StatelessWidget { 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( 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 806768c..af1c558 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 @@ -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,6 +273,7 @@ class MyProfileBloc extends Bloc { var currentState = state as MyProfileLoadedState; await uploadImageToServer(event.image.path, currentState.token); + this.add(MyProfileInitialEvent()); } } 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 8df3294..9aeb496 100644 --- a/lib/presentation/profile/my_profile_screen/my_profile_screen.dart +++ b/lib/presentation/profile/my_profile_screen/my_profile_screen.dart @@ -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), ], ), @@ -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( + 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), + ), + ), + ], + ), + ); + }, + ), + ), + ], + ), + ), + ], + ), + ), + ], + ), + ); } 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, @@ -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, 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 00dbfcd..0fbc048 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 @@ -37,7 +37,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(dotenv.env['SERVER_ROOT']! + '/recipes/show/$recipeID'), headers: { 'Authorization': 'Bearer $token', }, @@ -47,7 +47,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 +57,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 +78,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 { // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку @@ -195,7 +200,7 @@ class RecipeEditBloc extends Bloc { } final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipe/getTags/$id'), + Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipes/getTags/$id'), headers: { 'Authorization': 'Bearer $token', }, @@ -213,7 +218,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 +228,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_select_screen/bloc/recipe_select_bloc.dart b/lib/presentation/recipe/recipe_select_screen/bloc/recipe_select_bloc.dart index 6f5bdfd..ab26247 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,6 +1,8 @@ import 'dart:async'; +import 'package:dio/dio.dart'; import 'package:eatvio_app/app_router.dart'; +import 'package:eatvio_app/locator_service.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import '/core/app_export.dart'; @@ -31,27 +33,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(dotenv.env['SERVER_ROOT']! + '/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 feb87b2..d320f90 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 fa0a950..33b59af 100644 --- a/lib/presentation/recipe/recipe_select_screen/recipe_select_screen.dart +++ b/lib/presentation/recipe/recipe_select_screen/recipe_select_screen.dart @@ -112,6 +112,7 @@ 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) { 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 ed9b6ef..e8ef6e3 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 @@ -37,7 +37,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(dotenv.env['SERVER_ROOT']! + '/recipes/show/$recipeID'), headers: { 'Authorization': 'Bearer $token', }, @@ -47,23 +47,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 +93,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(dotenv.env['SERVER_ROOT']! + '/recipes/delete/$id'), headers: { 'Authorization': 'Bearer $token', }, @@ -125,7 +131,7 @@ class RecipeBloc extends Bloc { } final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipe/getAuthor/$id'), + Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipes/getAuthor/$id'), headers: { 'Authorization': 'Bearer $token', }, @@ -141,7 +147,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(dotenv.env['SERVER_ROOT']! + '/recipes/getComments/$id'), headers: { 'Authorization': 'Bearer $token', }, @@ -159,7 +165,7 @@ class RecipeBloc extends Bloc { } final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipe/getTags/$id'), + Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipes/getTags/$id'), headers: { 'Authorization': 'Bearer $token', }, @@ -171,30 +177,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 = dotenv.env['SERVER_ROOT']! + '/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/registration/additional_information_screen/additional_information_screen.dart b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart index 1ade582..1543cd5 100644 --- a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart +++ b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart @@ -20,45 +20,59 @@ class AdditionalInformationScreen extends StatelessWidget { static Widget builder(BuildContext context, sheet) { return BlocProvider( - create: (context) => - AdditionalInformationBloc(AdditionalInformationState(additionalInformationModelObj: AdditionalInformationModel(userRegistrationSheet: sheet))) - ..add(AdditionalInformationInitialEvent()), - child: AdditionalInformationScreen(),); + 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) { + 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: (14 / 15).toDouble(), + 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),); - },), - ],),),); + 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) { @@ -66,8 +80,12 @@ class AdditionalInformationScreen extends StatelessWidget { 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,); + 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) { @@ -84,11 +102,12 @@ class AdditionalInformationScreen extends StatelessWidget { /// 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),); + 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) { @@ -100,29 +119,45 @@ class AdditionalInformationScreen extends StatelessWidget { /// Section Widget _buildTextFormField(BuildContext context) { return SizedBox( - height: 315.v, - width: 343.h, - child: Stack(alignment: Alignment.center, children: [ + height: 315.v, + width: 343.h, + child: Stack( + alignment: Alignment.center, + children: [ Align( - alignment: Alignment.center, - child: Column(mainAxisSize: MainAxisSize.min, children: [ + 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,),), + 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,); - },), - ],),), - ],),); + selector: (state) => state.editTextController, + builder: (context, editTextController) { + return CustomTextFormField( + controller: editTextController, + hintText: "У меня крепкое здоровье, но последнее время часто утомляюсь, однако, это мне не мешает радоваться жизни", + textInputAction: TextInputAction.done, + maxLines: 8, + ); + }, + ), + ], + ), + ), + ], + ), + ); } /// Navigates to the previous screen. @@ -134,12 +169,13 @@ class AdditionalInformationScreen extends StatelessWidget { /// 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'))], - ),); + context: context, + builder: (_) => AlertDialog( + title: const Text('Ошибка'), + content: Text(text), + actions: [TextButton(onPressed: onTapOk(context), child: const Text('Ok'))], + ), + ); } onTapOk(BuildContext context) { diff --git a/lib/presentation/registration/allergies_screen/allergies_screen.dart b/lib/presentation/registration/allergies_screen/allergies_screen.dart index 30e218c..0c5fac4 100644 --- a/lib/presentation/registration/allergies_screen/allergies_screen.dart +++ b/lib/presentation/registration/allergies_screen/allergies_screen.dart @@ -16,8 +16,9 @@ class AllergiesScreen extends StatefulWidget { static Widget builder(BuildContext context, sheet) { return BlocProvider( - create: (context) => AllergiesBloc(AllergiesState(allergiesModelObj: AllergiesModel(userRegistrationSheet: sheet)))..add(AllergiesInitialEvent()), - child: AllergiesScreen(),); + create: (context) => AllergiesBloc(AllergiesState(allergiesModelObj: AllergiesModel(userRegistrationSheet: sheet)))..add(AllergiesInitialEvent()), + child: AllergiesScreen(), + ); } @override @@ -28,43 +29,58 @@ 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) { + 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: (10 / 15).toDouble(), + 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) { + 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) { @@ -85,11 +101,12 @@ class _AllergiesScreenState extends State { /// 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),); + 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) { @@ -100,16 +117,23 @@ class _AllergiesScreenState extends State { /// Section Widget _buildTextFormField(BuildContext context) { - return Column(children: [ - Text("fill_in_information".tr, style: CustomTextStyles.titleMediumSegoeUI), - SizedBox(height: 2.v), - BlocSelector( + 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,); - },), - ],); + controller: enterInformationController, + hintText: "enter_information".tr, + textInputAction: TextInputAction.done, + maxLines: 8, + ); + }, + ), + ], + ); } /// Navigates to the previous screen. diff --git a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart b/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart index 1aabdbd..afce1b8 100644 --- a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart +++ b/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart @@ -19,9 +19,10 @@ class BloodPressureScreen extends StatefulWidget { static Widget builder(BuildContext context, sheet) { return BlocProvider( - create: (context) => - BloodPressureBloc(BloodPressureState(bloodPressureModelObj: BloodPressureModel(userRegistrationSheet: sheet)))..add(BloodPressureInitialEvent()), - child: BloodPressureScreen(),); + create: (context) => + BloodPressureBloc(BloodPressureState(bloodPressureModelObj: BloodPressureModel(userRegistrationSheet: sheet)))..add(BloodPressureInitialEvent()), + child: BloodPressureScreen(), + ); } @override @@ -33,115 +34,146 @@ class _BloodPressureScreenState extends State { 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), - ), + 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, ), ), - 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) { + child: ClipRRect( + borderRadius: BorderRadius.circular(8.h), + child: LinearProgressIndicator( + value: (9 / 15).toDouble(), + 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) { + 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) { @@ -158,7 +190,7 @@ class _BloodPressureScreenState extends State { UserRegistrationSheet sheet = state.bloodPressureModelObj!.userRegistrationSheet; sheet.bloodPressureUp = state.upPressureController!.text; sheet.bloodPressureDown = state.downPressureController!.text; - AppRouter.navigatorKey.currentContext?.goNamed('favoriteSportsScreen', extra: sheet); + AppRouter.navigatorKey.currentContext?.goNamed('allergiesScreen', extra: sheet); } else { String errorMessage = ''; @@ -204,11 +236,12 @@ class _BloodPressureScreenState extends State { /// 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),); + 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) { diff --git a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart b/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart index 3326d45..b4b696d 100644 --- a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart +++ b/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart @@ -28,62 +28,84 @@ class BodyCircumferencesScreen extends StatelessWidget { 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: [ + 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: (6 / 15).toDouble(), + 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) { + 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),); - },), - ],),),); + 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) { @@ -129,11 +151,12 @@ class BodyCircumferencesScreen extends StatelessWidget { /// 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),); + 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) { 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 index 82da493..cd862cd 100644 --- 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 @@ -1144,45 +1144,57 @@ class CityOfLivingScreen extends StatelessWidget { "Ясный", "Яхрома", ]; + 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) { + 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: (5 / 15).toDouble(), + 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()); @@ -1228,16 +1240,23 @@ class CityOfLivingScreen extends StatelessWidget { ); }, ); - },), - Spacer(flex: 65), - BlocBuilder(builder: (context, state) { + }, + ), + 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),); - },), - ],),),); + 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) { @@ -1256,11 +1275,12 @@ class CityOfLivingScreen extends StatelessWidget { /// 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),); + 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) { diff --git a/lib/presentation/registration/credentials_screen/credentials_screen.dart b/lib/presentation/registration/credentials_screen/credentials_screen.dart index cbf3171..23517a0 100644 --- a/lib/presentation/registration/credentials_screen/credentials_screen.dart +++ b/lib/presentation/registration/credentials_screen/credentials_screen.dart @@ -27,70 +27,87 @@ class CredentialsScreen extends StatelessWidget { 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) { + 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 / 15).toDouble(), + 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),); - },), - ],),),); + 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) { 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 index a6b2da0..e6a223f 100644 --- 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 @@ -36,38 +36,53 @@ class _DateOfBirthScreenState extends State { @override Widget build(BuildContext context) { mediaQueryData = MediaQuery.of(context); - return BlocBuilder(builder: (context, state) { - return Scaffold( + 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: [ + 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),),),), + 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: (4 / 15).toDouble(), + 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( + 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),); - },), - ],),),); - },); + onPressed: onTapContinue(state, context), + ); + }, + ), + ], + ), + ), + ); + }, + ); } onTapContinue(DateOfBirthState state, BuildContext context) { @@ -81,11 +96,12 @@ class _DateOfBirthScreenState extends State { /// 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),); + 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) { @@ -97,19 +113,27 @@ class _DateOfBirthScreenState extends State { /// 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: [ + 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),),), + 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) { diff --git a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart b/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart index ea90d98..7660118 100644 --- a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart +++ b/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart @@ -16,9 +16,10 @@ class FavoriteFoodsScreen extends StatefulWidget { static Widget builder(BuildContext context, sheet) { return BlocProvider( - create: (context) => - FavoriteFoodsBloc(FavoriteFoodsState(favoriteFoodsModelObj: FavoriteFoodsModel(userRegistrationSheet: sheet)))..add(FavoriteFoodsInitialEvent()), - child: FavoriteFoodsScreen(),); + create: (context) => + FavoriteFoodsBloc(FavoriteFoodsState(favoriteFoodsModelObj: FavoriteFoodsModel(userRegistrationSheet: sheet)))..add(FavoriteFoodsInitialEvent()), + child: FavoriteFoodsScreen(), + ); } @override @@ -29,49 +30,70 @@ 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) { + 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: (13 / 15).toDouble(), + 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) { + 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) { @@ -93,11 +115,12 @@ class _FavoriteFoodsScreenState extends State { /// 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),); + 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) { @@ -108,29 +131,39 @@ class _FavoriteFoodsScreenState extends State { /// Section Widget _buildTextFormFieldFav(BuildContext context) { - return Column(children: [ - Text("favorite_foods".tr, style: CustomTextStyles.titleMediumSegoeUI), - SizedBox(height: 2.v), - BlocSelector( + 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( + 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,); - },), - ],); + controller: unfavoriteFoodsController, + hintText: "enter_information".tr, + textInputAction: TextInputAction.done, + maxLines: 7, + ); + }, + ), + ], + ); } /// Navigates to the previous screen. diff --git a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart b/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart index 498b24c..187a284 100644 --- a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart +++ b/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart @@ -16,9 +16,10 @@ class FavoriteSportsScreen extends StatefulWidget { static Widget builder(BuildContext context, sheet) { return BlocProvider( - create: (context) => FavoriteSportsBloc(FavoriteSportsState(favoriteSportsModelObj: FavoriteSportsModel(userRegistrationSheet: sheet))) - ..add(FavoriteSportsInitialEvent()), - child: FavoriteSportsScreen(),); + create: (context) => + FavoriteSportsBloc(FavoriteSportsState(favoriteSportsModelObj: FavoriteSportsModel(userRegistrationSheet: sheet)))..add(FavoriteSportsInitialEvent()), + child: FavoriteSportsScreen(), + ); } @override @@ -29,43 +30,59 @@ 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) { + 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: (12 / 15).toDouble(), + 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) { + 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) { @@ -85,11 +102,12 @@ class _FavoriteSportsScreenState extends State { _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),); + 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) { @@ -100,20 +118,24 @@ class _FavoriteSportsScreenState extends State { /// Section Widget _buildTextFormFieldSection(BuildContext context) { - return Column(children: [ - Text("fill_in_information".tr, style: CustomTextStyles.titleMediumSegoeUI), - SizedBox(height: 2.v), - BlocSelector( + 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,); - },), - ],); + controller: enterinformationController, + hintText: + "Я занимаюсь плаванием , почти каждый вечер прогулки на свежем воздухе, пару раз в месяц играю в волейбол. Стараюсь не сидеть на месте!", + textInputAction: TextInputAction.done, + maxLines: 8, + ); + }, + ), + ], + ); } onTapArrowLeft(BuildContext context) { diff --git a/lib/presentation/registration/gender_screen/gender_screen.dart b/lib/presentation/registration/gender_screen/gender_screen.dart index d6a9b63..8fc7d23 100644 --- a/lib/presentation/registration/gender_screen/gender_screen.dart +++ b/lib/presentation/registration/gender_screen/gender_screen.dart @@ -15,12 +15,13 @@ class GenderScreen extends StatefulWidget { static Widget builder(BuildContext context, sheet) { return BlocProvider( - create: (context) => GenderBloc( - GenderState( - genderModelObj: GenderModel(userRegistrationSheet: sheet), - ), - )..add(GenderInitialEvent()), - child: GenderScreen(),); + create: (context) => GenderBloc( + GenderState( + genderModelObj: GenderModel(userRegistrationSheet: sheet), + ), + )..add(GenderInitialEvent()), + child: GenderScreen(), + ); } @override @@ -31,25 +32,33 @@ class _GenderScreenState extends State { @override Widget build(BuildContext context) { mediaQueryData = MediaQuery.of(context); - return BlocBuilder(builder: (context, state) { - return Scaffold( + 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: [ + 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),),),), + 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: (3 / 15).toDouble(), + backgroundColor: theme.colorScheme.onPrimary, + valueColor: AlwaysStoppedAnimation(appTheme.blueA400), + ), + ), + ), SizedBox(height: 36.v), Text("your_gender".tr, style: theme.textTheme.headlineSmall), RadioListTile( @@ -75,15 +84,22 @@ class _GenderScreenState extends State { ), ), Spacer(flex: 66), - BlocBuilder(builder: (context, state) { - return NextStepButton( + 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),); - },), - ],),),); - },); + onPressed: onTapNext(state, context), + ); + }, + ), + ], + ), + ), + ); + }, + ); } onTapNext(GenderState state, BuildContext context) { diff --git a/lib/presentation/registration/height_screen/height_screen.dart b/lib/presentation/registration/height_screen/height_screen.dart index 22ada6c..c990dc9 100644 --- a/lib/presentation/registration/height_screen/height_screen.dart +++ b/lib/presentation/registration/height_screen/height_screen.dart @@ -17,8 +17,9 @@ class HeightScreen extends StatelessWidget { static Widget builder(BuildContext context, sheet) { return BlocProvider( - create: (context) => HeightBloc(HeightState(heightModelObj: HeightModel(userRegistrationSheet: sheet)))..add(HeightInitialEvent()), - child: HeightScreen(),); + create: (context) => HeightBloc(HeightState(heightModelObj: HeightModel(userRegistrationSheet: sheet)))..add(HeightInitialEvent()), + child: HeightScreen(), + ); } @override @@ -46,7 +47,7 @@ class HeightScreen extends StatelessWidget { child: ClipRRect( borderRadius: BorderRadius.circular(8.h), child: LinearProgressIndicator( - value: 0.55, + value: (8 / 15).toDouble(), backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation( appTheme.blueA400, @@ -69,17 +70,19 @@ class HeightScreen extends StatelessWidget { 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, - ], - ); - },), + BlocBuilder( + builder: (context, state) { + return CustomTextFormField( + width: 150.h, + textInputAction: TextInputAction.done, + controller: state.heightController, + keyboardType: TextInputType.number, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, + ], + ); + }, + ), ], ), ], @@ -115,11 +118,12 @@ class HeightScreen extends StatelessWidget { /// 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),); + 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) { diff --git a/lib/presentation/registration/language_select_screen/language_select_screen.dart b/lib/presentation/registration/language_select_screen/language_select_screen.dart index a682d9d..884281f 100644 --- a/lib/presentation/registration/language_select_screen/language_select_screen.dart +++ b/lib/presentation/registration/language_select_screen/language_select_screen.dart @@ -46,7 +46,7 @@ class LanguageSelectScreen extends StatelessWidget { child: ClipRRect( borderRadius: BorderRadius.circular(8.h), child: LinearProgressIndicator( - value: 0, + value: (0 / 15).toDouble(), backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation(appTheme.blueA400), ), @@ -66,28 +66,29 @@ class LanguageSelectScreen extends StatelessWidget { ), 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, - ), + 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), ), - hintText: "Не выбрано".tr, - items: languageSelectModelObj?.dropdownItemList ?? [], - onChanged: (value) => _onDropDownChanged(context, value), - ); - },), + child: CustomImageView( + imagePath: ImageConstant.imgFavorite, + height: 12.adaptSize, + width: 12.adaptSize, + ), + ), + hintText: "Не выбрано".tr, + items: languageSelectModelObj?.dropdownItemList ?? [], + onChanged: (value) => _onDropDownChanged(context, value), + ); + }, + ), Spacer(flex: 63), ], ), diff --git a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart b/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart index bce9049..2a55586 100644 --- a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart +++ b/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart @@ -16,9 +16,10 @@ class MedicineIntakeScreen extends StatefulWidget { static Widget builder(BuildContext context, sheet) { return BlocProvider( - create: (context) => MedicineIntakeBloc(MedicineIntakeState(medicineIntakeModelObj: MedicineIntakeModel(userRegistrationSheet: sheet))) - ..add(MedicineIntakeInitialEvent()), - child: MedicineIntakeScreen(),); + create: (context) => + MedicineIntakeBloc(MedicineIntakeState(medicineIntakeModelObj: MedicineIntakeModel(userRegistrationSheet: sheet)))..add(MedicineIntakeInitialEvent()), + child: MedicineIntakeScreen(), + ); } @override @@ -30,54 +31,75 @@ class _MedicineIntakeScreenState extends State { 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) { + 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: (11 / 15).toDouble(), + 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) { + 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', + 'favoriteSportsScreen', extra: sheet, ); }; @@ -88,7 +110,7 @@ class _MedicineIntakeScreenState extends State { UserRegistrationSheet sheet = state.medicineIntakeModelObj!.userRegistrationSheet; sheet.aboutTakingPils = state.enterInformationController!.text; GoRouter.of(context).goNamed( - 'bloodPressureScreen', + 'favoriteSportsScreen', extra: sheet, ); }; @@ -97,11 +119,12 @@ class _MedicineIntakeScreenState extends State { /// 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),); + 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) { @@ -112,16 +135,23 @@ class _MedicineIntakeScreenState extends State { /// Section Widget _buildTextFormField(BuildContext context) { - return Column(children: [ - Text("fill_in_information".tr, style: CustomTextStyles.titleMediumSegoeUI), - SizedBox(height: 2.v), - BlocSelector( + 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,); - },), - ],); + controller: enterInformationController, + hintText: "enter_information".tr, + textInputAction: TextInputAction.done, + maxLines: 8, + ); + }, + ), + ], + ); } /// Navigates to the previous screen. diff --git a/lib/presentation/registration/name_screen/name_screen.dart b/lib/presentation/registration/name_screen/name_screen.dart index 880c3ae..4fb599d 100644 --- a/lib/presentation/registration/name_screen/name_screen.dart +++ b/lib/presentation/registration/name_screen/name_screen.dart @@ -17,76 +17,95 @@ class NameScreen extends StatelessWidget { static Widget builder(BuildContext context, sheet) { return BlocProvider( - create: (context) => NameBloc( - NameState( - nameModelObj: NameModel(userRegistrationSheet: sheet), - ), - )..add(NameInitialEvent()), - child: NameScreen(),); + 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) { + 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: (2 / 15).toDouble(), + 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),); + 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. diff --git a/lib/presentation/registration/weight_screen/weight_screen.dart b/lib/presentation/registration/weight_screen/weight_screen.dart index 5d47e8d..caad9e7 100644 --- a/lib/presentation/registration/weight_screen/weight_screen.dart +++ b/lib/presentation/registration/weight_screen/weight_screen.dart @@ -17,8 +17,9 @@ class WeightScreen extends StatelessWidget { static Widget builder(BuildContext context, sheet) { return BlocProvider( - create: (context) => WeightBloc(WeightState(weightModelObj: WeightModel(userRegistrationSheet: sheet)))..add(WeightInitialEvent()), - child: WeightScreen(),); + create: (context) => WeightBloc(WeightState(weightModelObj: WeightModel(userRegistrationSheet: sheet)))..add(WeightInitialEvent()), + child: WeightScreen(), + ); } @override @@ -45,7 +46,7 @@ class WeightScreen extends StatelessWidget { child: ClipRRect( borderRadius: BorderRadius.circular(8.h), child: LinearProgressIndicator( - value: 0.55, + value: (7 / 15).toDouble(), backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation( appTheme.blueA400, @@ -68,17 +69,19 @@ class WeightScreen extends StatelessWidget { 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, - ], - ); - },), + BlocBuilder( + builder: (context, state) { + return CustomTextFormField( + width: 150.h, + textInputAction: TextInputAction.done, + controller: state.weightController, + keyboardType: TextInputType.number, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, + ], + ); + }, + ), ], ), ], @@ -114,11 +117,12 @@ class WeightScreen extends StatelessWidget { /// 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),); + 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) { diff --git a/lib/theme/theme_helper.dart b/lib/theme/theme_helper.dart index c912cb2..f9f64aa 100644 --- a/lib/theme/theme_helper.dart +++ b/lib/theme/theme_helper.dart @@ -1,5 +1,6 @@ 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 +23,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 +36,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 +88,6 @@ class ThemeHelper { ), visualDensity: VisualDensity.standard, colorScheme: colorScheme, - textTheme: TextThemes.textTheme(colorScheme), scaffoldBackgroundColor: colorScheme.onPrimary, appBarTheme: AppBarTheme( systemOverlayStyle: SystemUiOverlayStyle( @@ -85,54 +123,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 +139,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 +152,9 @@ class PrimaryColors { // BlueGray Color get blueGray300 => Color(0XFF9AA5B1); + Color get blueGray800 => Color(0XFF323F4B); + Color get blueGray900 => Color(0XFF2A2F4C); // DeepOrange @@ -168,22 +162,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 +196,7 @@ class PrimaryColors { // Teal Color get teal100 => Color(0XFFA6CEE3); + Color get teal900 => Color(0XFF0B3F56); // White @@ -200,4 +206,5 @@ class PrimaryColors { } PrimaryColors get appTheme => ThemeHelper().themeColor(); + ThemeData get theme => ThemeHelper().themeData(); diff --git a/lib/widgets/custom_navigation_menu_item.dart b/lib/widgets/custom_navigation_menu_item.dart index 2ee47a8..9d7d161 100644 --- a/lib/widgets/custom_navigation_menu_item.dart +++ b/lib/widgets/custom_navigation_menu_item.dart @@ -1,3 +1,4 @@ +import 'package:eatvio_app/core/app_export.dart'; import 'package:flutter/material.dart'; import 'package:eatvio_app/widgets/custom_image_view.dart'; @@ -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/pubspec.yaml b/pubspec.yaml index 87ed29e..36031fc 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -44,6 +44,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 @@ -59,17 +60,4 @@ flutter: 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 + - .env \ No newline at end of file -- 2.49.1 From c3f7853d0ec0baa283883abb1e0ede3c5d39e376 Mon Sep 17 00:00:00 2001 From: alex Date: Tue, 9 Jul 2024 17:51:05 +0300 Subject: [PATCH 037/110] refactor(all): refactor fix --- .../recipe/recipe_select_screen/bloc/recipe_select_bloc.dart | 2 -- 1 file changed, 2 deletions(-) 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 ab26247..08f57b4 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 @@ -7,8 +7,6 @@ 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'; -- 2.49.1 From e4cde31d7696c93447a05949357bfba5c1a2c229 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 11 Jul 2024 14:35:29 +0300 Subject: [PATCH 038/110] refatcor(diary): Refactored (doesn't work yet though) --- lib/app_router.dart | 104 +- .../blog_post_create_credentials_model.dart | 2 + .../pages/blog_post_create_screen.dart | 2 + .../repositories/blog_repository.dart | 2 + .../services/blog_service.dart | 2 + .../services/blog_service.g.dart | 78 -- lib/features/diary/models/diary_model.dart | 81 +- .../diary/models/diary_model.freezed.dart | 20 +- lib/features/diary/models/diary_model.g.dart | 2 +- .../diary/presentation/bloc/diary_bloc.dart | 845 +++++++++++++ .../diary/presentation/bloc/diary_cubit.dart | 20 - .../diary/presentation/bloc/diary_event.dart} | 66 +- .../diary/presentation/bloc/diary_state.dart | 28 + .../bloc/diary_state.freezed.dart | 930 +++++++++++++- .../presentation/pages/diary_screen.dart | 227 ++-- .../diary/repositories/diary_repository.dart | 2 +- .../diary/services/diary_service.dart | 36 +- .../diary/services/diary_service.g.dart | 155 ++- lib/locator_service.dart | 22 +- lib/main.dart | 26 +- .../bloc/diary_edit_bloc.dart | 1078 ----------------- .../bloc/diary_edit_state.dart | 4 +- .../diary_edit_screen/diary_edit_screen.dart | 3 +- ...post_create_credentials_model.freezed.dart | 235 ---- .../blog_post_create_credentials_model.g.dart | 25 - .../feed/feed_screen/models/feed_model.dart | 16 - test/diary_test.dart | 5 +- 27 files changed, 2304 insertions(+), 1712 deletions(-) delete mode 100644 lib/features/blog_post_create/services/blog_service.g.dart create mode 100644 lib/features/diary/presentation/bloc/diary_bloc.dart delete mode 100644 lib/features/diary/presentation/bloc/diary_cubit.dart rename lib/{presentation/diary/diary_edit_screen/bloc/diary_edit_event.dart => features/diary/presentation/bloc/diary_event.dart} (64%) delete mode 100644 lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart delete mode 100644 lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.freezed.dart delete mode 100644 lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.g.dart delete mode 100644 lib/presentation/feed/feed_screen/models/feed_model.dart diff --git a/lib/app_router.dart b/lib/app_router.dart index 30cda0b..50f7968 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -1,11 +1,10 @@ import 'package:eatvio_app/core/token_storage.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/diary/presentation/pages/diary_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'; @@ -60,72 +59,120 @@ class AppRouter { GoRoute( path: 'credentials-screen', name: 'credentialsScreen', - builder: (context, state) => CredentialsScreen.builder(context, state.extra), + builder: (context, state) => + CredentialsScreen.builder(context, state.extra), routes: [ GoRoute( path: 'name-screen', name: 'nameScreen', - builder: (context, state) => NameScreen.builder(context, state.extra), + builder: (context, state) => + NameScreen.builder(context, state.extra), routes: [ GoRoute( path: 'gender-screen', name: 'genderScreen', - builder: (context, state) => GenderScreen.builder(context, state.extra), + 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), + 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), + builder: (context, state) => + CityOfLivingScreen.builder( + context, state.extra), routes: [ GoRoute( path: 'body-circumferences-screen', name: 'bodyCircumferencesScreen', - builder: (context, state) => BodyCircumferencesScreen.builder(context, state.extra), + builder: (context, state) => + BodyCircumferencesScreen.builder( + context, state.extra), routes: [ GoRoute( path: 'weight-screen', name: 'weightScreen', - builder: (context, state) => WeightScreen.builder(context, state.extra), + builder: (context, state) => + WeightScreen.builder( + context, state.extra), routes: [ GoRoute( path: 'height-screen', name: 'heightScreen', - builder: (context, state) => HeightScreen.builder(context, state.extra), + builder: (context, state) => + HeightScreen.builder( + context, state.extra), routes: [ GoRoute( path: 'blood-pressure-screen', name: 'bloodPressureScreen', - builder: (context, state) => BloodPressureScreen.builder(context, state.extra), + builder: (context, state) => + BloodPressureScreen.builder( + context, state.extra), routes: [ GoRoute( - path: 'favorite-sports-screen', - name: 'favoriteSportsScreen', - builder: (context, state) => FavoriteSportsScreen.builder(context, state.extra), + 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), + builder: (context, + state) => + AllergiesScreen + .builder( + context, + state + .extra), routes: [ GoRoute( - name: 'medicineIntakeScreen', - path: 'medicine-intake-screen', - builder: (context, state) => MedicineIntakeScreen.builder(context, state.extra), + 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), + 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: + 'additional-information-screen', + name: + 'additionalInformationScreen', + builder: (context, + state) => + AdditionalInformationScreen.builder( + context, + state + .extra), ), ], ), @@ -170,15 +217,16 @@ class AppRouter { name: 'feedScreen', builder: (context, state) => FeedScreen(), routes: [ - GoRoute( + /*GoRoute( path: 'blog-post-create-screen', name: 'blogPostCreateScreen', builder: (context, state) => BlogPostCreateScreen.builder(context), - ), + ),*/ GoRoute( path: 'blog-post-screen', name: 'blogPostScreen', - builder: (context, state) => BlogPostScreen(blogPostID: state.extra as String), + builder: (context, state) => + BlogPostScreen(blogPostID: state.extra as String), routes: [ GoRoute( path: 'blog-post-edit-screen', @@ -195,7 +243,7 @@ class AppRouter { GoRoute( path: '/diary-screen', name: 'diaryScreen', - builder: (context, state) => DiaryEditScreen(), + builder: (context, state) => DiaryScreen(), ), GoRoute( path: '/chat-select-screen', 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 e961471..957990d 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,3 +1,4 @@ +/* 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'; @@ -13,3 +14,4 @@ class BlogPostCreateCredentialsModel with _$BlogPostCreateCredentialsModel { factory BlogPostCreateCredentialsModel.fromJson(Map json) => _$BlogPostCreateCredentialsModelFromJson(json); } +*/ 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 4bedcf5..b49b45c 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,3 +1,4 @@ +/* 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 'package:eatvio_app/core/app_export.dart'; @@ -237,3 +238,4 @@ bool _isValidUrl(String url) { new RegExp(r"^(http|https):\/\/([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$"); return urlRegExp.hasMatch(url); } +*/ \ No newline at end of file diff --git a/lib/features/blog_post_create/repositories/blog_repository.dart b/lib/features/blog_post_create/repositories/blog_repository.dart index e11bce9..104b1cd 100644 --- a/lib/features/blog_post_create/repositories/blog_repository.dart +++ b/lib/features/blog_post_create/repositories/blog_repository.dart @@ -1,3 +1,4 @@ +/* import 'package:eatvio_app/features/blog_post_create/models/blog_post_create_credentials_model.dart'; import 'package:eatvio_app/features/blog_post_create/services/blog_service.dart'; @@ -18,3 +19,4 @@ class BlogRepository { } } } +*/ \ No newline at end of file diff --git a/lib/features/blog_post_create/services/blog_service.dart b/lib/features/blog_post_create/services/blog_service.dart index 1291c9a..d8e9449 100644 --- a/lib/features/blog_post_create/services/blog_service.dart +++ b/lib/features/blog_post_create/services/blog_service.dart @@ -1,3 +1,4 @@ +/* import 'package:eatvio_app/features/blog_post_create/models/blog_post_create_credentials_model.dart'; import 'package:dio/dio.dart'; import 'package:retrofit/retrofit.dart'; @@ -12,3 +13,4 @@ abstract class BlogService { Future createBlogPost( BlogPostCreateCredentialsModel model); } +*/ \ No newline at end of file diff --git a/lib/features/blog_post_create/services/blog_service.g.dart b/lib/features/blog_post_create/services/blog_service.g.dart deleted file mode 100644 index 71ca211..0000000 --- a/lib/features/blog_post_create/services/blog_service.g.dart +++ /dev/null @@ -1,78 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'blog_service.dart'; - -// ************************************************************************** -// RetrofitGenerator -// ************************************************************************** - -// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers,unused_element - -class _BlogService implements BlogService { - _BlogService( - this._dio, { - this.baseUrl, - }); - - final Dio _dio; - - String? baseUrl; - - @override - Future createBlogPost( - BlogPostCreateCredentialsModel model) async { - final _extra = {}; - final queryParameters = {}; - final _headers = {}; - const Map? _data = null; - final _result = await _dio.fetch>( - _setStreamType(Options( - method: 'POST', - headers: _headers, - extra: _extra, - ) - .compose( - _dio.options, - '/blog_post/create', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - final _value = BlogPostCreateCredentialsModel.fromJson(_result.data!); - 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/features/diary/models/diary_model.dart b/lib/features/diary/models/diary_model.dart index 84832f1..fe7d6a2 100644 --- a/lib/features/diary/models/diary_model.dart +++ b/lib/features/diary/models/diary_model.dart @@ -12,25 +12,33 @@ class DiaryModel with _$DiaryModel { required DateTime retire, required int closed, required String comment, - required List meals}) = _DiaryModel; + required List meals}) = _DiaryModel; - factory DiaryModel.fromJson(Map json) => _$DiaryModelFromJson(json); + factory DiaryModel.fromJson(Map json) => + _$DiaryModelFromJson(json); } -class Meals { - int? id; - String? time; - int? type; - int? satiety; - int? mood; - List? portions; - List? photos; +class Meal { + late int id; + late String time; + late int type; + late int satiety; + late int mood; + List? portions; + List? photos; - Meals({this.id, this.time, this.type, this.satiety, this.mood, this.portions, this.photos}); + Meal( + {required this.id, + required this.time, + required this.type, + required this.satiety, + required this.mood, + this.portions, + this.photos}); - Meals.fromJson(Map json) { - List portions = []; - List photos = []; + Meal.fromJson(Map json) { + List portions = []; + List photos = []; id = json['id']; time = json['time']; type = json['type']; @@ -38,12 +46,12 @@ class Meals { mood = json['mood']; if (json['portions'] != null) { json['portions'].forEach((v) { - portions.add(new Portions.fromJson(v)); + portions.add(new Portion.fromJson(v)); }); } if (json['photos'] != null) { json['photos'].forEach((v) { - photos.add(new Photos.fromJson(v)); + photos.add(new Photo.fromJson(v)); }); } } @@ -65,20 +73,19 @@ class Meals { } } -class Portions { - int? id; - String? productName; - int? quantity; - String? portion; +class Portion { + late int id; + late String productName; + late int quantity; + late String portion; - Portions({this.id, this.productName, this.quantity, this.portion}); + Portion( + {required this.id, + required this.productName, + required this.quantity, + required this.portion}); - Portions.fromJson(Map json) { - id = json['id']; - productName = json['product_name']; - quantity = json['quantity']; - portion = json['portion']; - } + Portion.fromJson(v); Map toJson() { final Map data = new Map(); @@ -90,15 +97,19 @@ class Portions { } } -class Photos { - int? id; - String? originalName; - String? path; - int? size; +class Photo { + late int id; + late String originalName; + late String path; + late int size; - Photos({this.id, this.originalName, this.path, this.size}); + Photo( + {required this.id, + required this.originalName, + required this.path, + required this.size}); - Photos.fromJson(Map json) { + Photo.fromJson(Map json) { id = json['id']; originalName = json['original_name']; path = json['path']; diff --git a/lib/features/diary/models/diary_model.freezed.dart b/lib/features/diary/models/diary_model.freezed.dart index 5ede010..6705ecf 100644 --- a/lib/features/diary/models/diary_model.freezed.dart +++ b/lib/features/diary/models/diary_model.freezed.dart @@ -26,7 +26,7 @@ mixin _$DiaryModel { DateTime get retire => throw _privateConstructorUsedError; int get closed => throw _privateConstructorUsedError; String get comment => throw _privateConstructorUsedError; - List get meals => throw _privateConstructorUsedError; + List get meals => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -47,7 +47,7 @@ abstract class $DiaryModelCopyWith<$Res> { DateTime retire, int closed, String comment, - List meals}); + List meals}); } /// @nodoc @@ -99,7 +99,7 @@ class _$DiaryModelCopyWithImpl<$Res, $Val extends DiaryModel> meals: null == meals ? _value.meals : meals // ignore: cast_nullable_to_non_nullable - as List, + as List, ) as $Val); } } @@ -119,7 +119,7 @@ abstract class _$$DiaryModelImplCopyWith<$Res> DateTime retire, int closed, String comment, - List meals}); + List meals}); } /// @nodoc @@ -169,7 +169,7 @@ class __$$DiaryModelImplCopyWithImpl<$Res> meals: null == meals ? _value._meals : meals // ignore: cast_nullable_to_non_nullable - as List, + as List, )); } } @@ -184,7 +184,7 @@ class _$DiaryModelImpl implements _DiaryModel { required this.retire, required this.closed, required this.comment, - required final List meals}) + required final List meals}) : _meals = meals; factory _$DiaryModelImpl.fromJson(Map json) => @@ -202,9 +202,9 @@ class _$DiaryModelImpl implements _DiaryModel { final int closed; @override final String comment; - final List _meals; + final List _meals; @override - List get meals { + List get meals { if (_meals is EqualUnmodifiableListView) return _meals; // ignore: implicit_dynamic_type return EqualUnmodifiableListView(_meals); @@ -256,7 +256,7 @@ abstract class _DiaryModel implements DiaryModel { required final DateTime retire, required final int closed, required final String comment, - required final List meals}) = _$DiaryModelImpl; + required final List meals}) = _$DiaryModelImpl; factory _DiaryModel.fromJson(Map json) = _$DiaryModelImpl.fromJson; @@ -274,7 +274,7 @@ abstract class _DiaryModel implements DiaryModel { @override String get comment; @override - List get meals; + List get meals; @override @JsonKey(ignore: true) _$$DiaryModelImplCopyWith<_$DiaryModelImpl> get copyWith => diff --git a/lib/features/diary/models/diary_model.g.dart b/lib/features/diary/models/diary_model.g.dart index cab25b6..9fabca8 100644 --- a/lib/features/diary/models/diary_model.g.dart +++ b/lib/features/diary/models/diary_model.g.dart @@ -15,7 +15,7 @@ _$DiaryModelImpl _$$DiaryModelImplFromJson(Map json) => closed: (json['closed'] as num).toInt(), comment: json['comment'] as String, meals: (json['meals'] as List) - .map((e) => Meals.fromJson(e as Map)) + .map((e) => Meal.fromJson(e as Map)) .toList(), ); diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart new file mode 100644 index 0000000..efc7b26 --- /dev/null +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -0,0 +1,845 @@ +import 'dart:async'; +import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; +import 'package:intl/intl.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/features/diary/presentation/bloc/diary_state.dart'; +import 'package:http/http.dart' as http; +import 'dart:convert'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; + +part 'diary_event.dart'; + +/// A bloc that manages the state of a Diary according to the event that is dispatched to it. +class DiaryBloc extends Bloc { + final DiaryRepository diaryRepository; + + DiaryBloc({required this.diaryRepository}) + : super(const DiaryState.loading()) { + on(loadDiary); + on(_changeSatiety); // пользователь нажимает на шкалу сытости + on(_changeMood); // пользователь нажимает на шкалу настроения + on(_changeMealTime); // пользовательяет времяа пиши + on(_changeMeal); + on(_changePortion); + on(_changeWakeup); // пользователь выбирает время пробуждения + on(_changeRetire); // пользователь выбирает время отхода ко сну + on(_toggleMood); + on(_toggleWakeup); + on(_addPortion); //пользователь нажимает "Добавить продукт" + on(_removePortion); + on( + _removeImage, + ); // пользователь нажимает на крестик около продукта + on(_uploadImages); //пользователь нажимает "Добавить фото" + on(_addComment); //пользователь нажимает "Добавить комментарий" + on( + _inputProduct, + ); + on(_finishDay); + on(_sendModeration); + on( + reloadScreen, + ); + on(_clearInput); + } + + loadDiary( + LoadDiary event, + Emitter emit, + ) async { + emit(const DiaryState.loading()); + try { + final diary = + await diaryRepository.getDiary(await diaryRepository.getDiaryID()); + emit(DiaryState.loaded( + diary: diary, + commentController: TextEditingController(), + productNameController: TextEditingController(), + productQuantityController: TextEditingController(), + caloriesController: TextEditingController(), + fatsController: TextEditingController(), + proteinsController: TextEditingController(), + carbsController: TextEditingController(), + wakeupExpanded: false, + moderationExpanded: false, + moodExpanded: false, + isLoading: false, + isAdded: false, + recommendedChartValues: [0, 0, 0, 0], + consumedChartValues: [0, 0, 0, 0])); + } catch (e) { + emit(DiaryState.error(errorMessage: e.toString())); + print(e); + } + } + + fetchChartValues( + String token, + int diaryID, + Emitter emit, + ) async { + final responseChart = await http.get( + Uri.parse( + dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/dailyNutritionData/', + ), + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer $token', + }, + ); + + if (responseChart.statusCode == 200) { + final responseBody = jsonDecode(responseChart.body); + + final recommendedChartValues = + responseBody['dailyNutritionRecommendation'] + .values + .map((value) => convertToInt(value)) + .toList(); + + final consumedChartValues = responseBody['dailyNutritionIntake'] + .values + .map((value) => convertToInt(value)) + .toList(); + + print([recommendedChartValues, consumedChartValues]); + return [recommendedChartValues, consumedChartValues]; + } else { + emit(DiaryStateError( + errorMessage: 'Ошибка при декодировании данных КБЖУ')); + print('fail'); + return [[], []]; // Return empty lists instead of -1 + } + } + + refreshScreen( + int mealID, + DiaryEvent event, + Emitter emit, + ) async { + await reloadScreen(event, emit); + } + + reloadScreen( + DiaryEvent event, + Emitter emit, + ) async { + print("Reloading..."); + } + + Future _changeSatiety( + ChangeSatiety event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + var updatedState = + currentState.copyWith(selectedMood: event.selectedElement); + + // Отправляем данные по HTTP маршруту и ждем ответ + var response = await sendSatietyData( + event.selectedElement, + currentState.currentMeal?.id, + currentState.diary.id, + ); + + if (response.statusCode == 200) { + print( + 'Satiety change success! meal_id: ${currentState.currentMeal?.id}, mood: ${event.selectedElement}', + ); + emit(updatedState); // Передаем обновленное состояние в emit + } + } + } + + Future sendSatietyData( + int selectedSatiety, + int? mealID, + int diaryID, + ) async { + String url = dotenv.env['SERVER_ROOT']! + + '/diary/$diaryID/meal/$mealID/satiety/fill'; + final Map credentials = { + 'satiety': selectedSatiety, + }; + var response = await http.post( + Uri.parse(url), + headers: { + 'Content-Type': 'application/json', + }, + body: json.encode(credentials), + encoding: utf8, + ); + return response; + } + + Future _changeMood( + ChangeMood event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + var updatedState = + currentState.copyWith(selectedMood: event.selectedElement); + + // Отправляем данные по HTTP маршруту и ждем ответ + var response = await sendMoodData( + event.selectedElement, + currentState.currentMeal?.id, + currentState.diary.id, + ); + + if (response.statusCode == 200) { + print( + 'Mood change success! meal_id: ${currentState.currentMeal?.id}, mood: ${event.selectedElement}', + ); + emit(updatedState); // Передаем обновленное состояние в emit + } + } + } + + Future sendMoodData( + int selectedMood, + int? mealID, + int diaryID, + ) async { + String url = + dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/meal/$mealID/mood/fill'; + final Map credentials = { + 'mood': selectedMood, + }; + + var response = await http.post( + Uri.parse(url), + headers: { + 'Content-Type': 'application/json', + }, + body: json.encode(credentials), + encoding: utf8, + ); + + return response; + } + + FutureOr _changeWakeup( + WakeupEvent event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + var response = await sendWakeupData( + event.selectedTime, + currentState.diary.id, + ); + if (response.statusCode == 200) { + await reloadScreen(event, emit); + var updatedState = + currentState.copyWith(wakeupController: event.selectedTime); + print("Wakeup time changed to ${event.selectedTime}"); + emit(updatedState); // Передаем обновленное состояние в emit + } else + print("Wakeup time change error"); + } + } + + FutureOr _changeRetire( + RetireEvent event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + var response = await sendRetireData( + event.selectedTime, + currentState.diary.id, + ); + if (response.statusCode == 200) { + await reloadScreen(event, emit); + var updatedState = + currentState.copyWith(retireController: event.selectedTime); + print("Retire time changed to ${event.selectedTime}"); + emit(updatedState); // Передаем обновленное состояние в emit + } else + print("Retire time change error"); + } + } + + Future sendWakeupData( + TimeOfDay wakeup, + int diaryID, + ) async { + String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/wakeUp/fill'; + final formatter = DateFormat('HH:mm'); + final wakeupString = + formatter.format(DateTime(2022, 1, 1, wakeup.hour, wakeup.minute)); + final Map credentials = { + 'wakeUp': wakeupString, + }; + + var response = await http.post( + Uri.parse(url), + headers: { + 'Content-Type': 'application/json', + }, + body: json.encode(credentials), + encoding: utf8, + ); + + return response; + } + + Future sendRetireData( + TimeOfDay retire, + int diaryID, + ) async { + String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill'; + final formatter = DateFormat('HH:mm'); + final retireString = + formatter.format(DateTime(2022, 1, 1, retire.hour, retire.minute)); + final Map credentials = { + 'retire': retireString, + }; + + var response = await http.post( + Uri.parse(url), + headers: { + 'Content-Type': 'application/json', + }, + body: json.encode(credentials), + encoding: utf8, + ); + + return response; + } + + FutureOr _changeMealTime( + ChangeMealTime event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + var updatedState = currentState.copyWith(mealTimeController: event.time); + + emit(updatedState); + } + } + + Future sendMealTimeData( + String? token, + TimeOfDay mealTime, + int? mealID, + int diaryID, + ) async { + String url = dotenv.env['SERVER_ROOT']! + '/diary/???'; + final Map credentials = { + 'time': mealTime, + 'meal_id': mealID, + 'diary_id': diaryID, + }; + + var response = await http.post( + Uri.parse(url), + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer $token', + }, + body: json.encode(credentials), + encoding: utf8, + ); + + return response; + } + + FutureOr _changeMeal( + ChangeMeal event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + Meal? meal = + currentState.diary.meals.firstWhere((meal) => meal.id == event.value); + + DiaryStateLoaded updatedState = currentState.copyWith( + currentMeal: event.value, + portions: meal.portions, + photos: meal.photos, + mealTimeController: toTime(meal.time), + selectedMood: meal.mood, + selectedSatiety: meal.satiety, + ); + emit(updatedState); + } + } + + FutureOr _clearInput( + ClearInput event, + Emitter emit, + ) { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + DiaryStateLoaded updatedState = currentState.copyWith(); + emit(updatedState); + } + } + + FutureOr _changePortion( + ChangePortion event, + Emitter emit, + ) { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + DiaryStateLoaded updatedState = currentState.copyWith( + portionController: event.value, + ); + emit(updatedState); + } + } + + FutureOr _toggleMood( + ToggleMoodExpandedEvent event, + Emitter emit, + ) { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + + emit(currentState.copyWith(moodExpanded: !currentState.moodExpanded)); + } + } + + FutureOr _toggleWakeup( + ToggleWakeupExpandedEvent event, + Emitter emit, + ) { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + + emit(currentState.copyWith(wakeupExpanded: !currentState.wakeupExpanded)); + } + } + + FutureOr _addPortion( + AddPortionEvent event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + + var response = await sendPortionData( + currentState.productNameController?.text, + currentState.portionController?.id == 0 ? 'pcs' : 'gr', + int.parse(currentState.productQuantityController!.text), + currentState.currentMeal!.id, + currentState.diary.id, + ); + + if (response.statusCode == 200) { + emit(currentState.copyWith(isAdded: true)); + await reloadScreen(event, emit); + } else { + print( + 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}', + ); + } + } + } + + FutureOr sendPortionData( + String? name, + String portion, + int? quantity, + int? mealID, + int diaryID, + ) async { + String url = + '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/create'; + + final Map credentials = { + 'product_name': name, + 'portion': portion, + 'quantity': quantity, + }; + + var response = await http.post( + Uri.parse(url), + headers: { + 'Content-Type': 'application/json', + }, + body: json.encode(credentials), + encoding: utf8, + ); + + return response; + } + + Future _inputProduct( + ProductInput event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + + final Map credentials = {'name': event.input}; + final uri = Uri.parse( + '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/filter?${Uri(queryParameters: credentials).query}', + ); + + final response = await http.get( + uri, + headers: { + 'Content-Type': 'application/json', + }, + ); + + final productNutritionalValues = + jsonDecode(response.body)['product_nutritional_value']; + + if (productNutritionalValues is List) { + // Create a new controller with the input text and update the autocomplete list + var updatedState = currentState.copyWith( + productNameController: TextEditingController(text: event.input), + autocompleteList: productNutritionalValues + .map((product) => product['name']) + .toList(), + ); + if (event.input.length > 3) { + updatedState = updatedState.copyWith(moderationExpanded: true); + } else { + updatedState = updatedState.copyWith(moderationExpanded: false); + } + + emit(updatedState); // Emit the updated state + } + } + } + + Future _removePortion( + RemovePortionEvent event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + + int? mealId = + currentState.currentMeal?.id; // Rename id to mealId for clarity + + var response = await sendRemovePortion( + event.portionId, + mealId, + currentState.diary.id, + ); + + if (response.statusCode == 204) { + await reloadScreen(event, emit); + } else { + print( + 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}', + ); + } + } + } + + Future sendRemovePortion( + int? portionID, + int? mealID, + int diaryID, + ) async { + String url = + '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete'; + + var response = await http.delete( + Uri.parse(url), + headers: { + 'Content-Type': 'application/json', + }, + encoding: utf8, + ); + + return response; + } + + FutureOr _removeImage( + RemoveImageEvent event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + + var response = await sendRemovePhoto( + event.path, + event.photoID, + currentState.currentMeal?.id, + currentState.diary.id, + ); + print(response.statusCode); + if (response.statusCode == 204) { + await reloadScreen(event, emit); + } else { + print( + 'Failed to remove photo. Status Code: ${response.statusCode} ${response.body}', + ); + } + } + } + + Future sendRemovePhoto( + String? path, + String? photoID, + int? mealID, + int diaryID, + ) async { + String url = + '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete'; + final Map credentials = { + 'id': photoID, + 'path': path, + }; + var response = await http.delete( + Uri.parse(url), + headers: { + 'Content-Type': 'application/json', + }, + body: json.encode(credentials), + encoding: utf8, + ); + + return response; + } + + Future _finishDay(FinishDay event, Emitter emit) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + + var response = await sendFinishDay( + currentState.diary.id, + currentState.wakeupController, + currentState.retireController, + currentState.commentController?.text, + ); + + if (response.statusCode == 200) { + await reloadScreen(event, emit); + } + } + } + + Future sendFinishDay( + int diaryID, + TimeOfDay? wakeup, + TimeOfDay? retire, + String? comment, + ) async { + final formatter = DateFormat('HH:mm'); + final wakeupString = + formatter.format(DateTime(2022, 1, 1, wakeup!.hour, wakeup.minute)); + final retireString = + formatter.format(DateTime(2022, 1, 1, retire!.hour, retire.minute)); + + final Map credentials = { + 'wakeup': wakeupString, + 'retire': retireString, + 'comment': comment ?? " ", + }; + + String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/finishDay'; + + var response = await http.post( + Uri.parse(url), + headers: { + 'Content-Type': 'application/json', + }, + body: json.encode(credentials), + encoding: utf8, + ); + + return response; + } + + Future _uploadImages( + UploadImages event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + + emit(currentState.copyWith(isLoading: true)); + await uploadImageToServer( + event.image.path, + currentState.diary.id, + currentState.currentMeal!.id, + ); + await reloadScreen(event, emit); + } + } + + Future uploadImageToServer( + String imagePath, + int diaryID, + int mealId, + ) async { + String url = + '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload'; + + var request = http.MultipartRequest('POST', Uri.parse(url)); + + request.files.add(await http.MultipartFile.fromPath('photo', imagePath)); + + var client = http.Client(); + var streamedResponse = await client.send(request); + + if (streamedResponse.statusCode == 200) { + var response = await http.Response.fromStream(streamedResponse); + var imageUrl = response.body; + print('Image successfully uploaded'); + return imageUrl; + } else { + throw Exception( + 'Failed to upload image. Status code: ${streamedResponse.statusCode}}', + ); + } + } + + FutureOr _sendModeration( + SendModeration event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + final response = await _sendModerationData( + event.name, + event.energyOn100gr, + event.proteinsOn100gr, + event.fatsOn100gr, + event.carbohydratesOn100gr, + ); + + if (response.statusCode == 200) + print("Moderation success"); + else + print("Moderation error"); + } + } + + Future _sendModerationData( + String name, + String energy_on_100gr, + String proteins_on_100gr, + String fats_on_100gr, + String carbohydrates_on_100gr, + ) async { + final Uri url = Uri.parse( + '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/sendToModeration', + ); + final Uri serverURL = Uri.parse('${dotenv.env['SERVER_ROOT']!}'); + String host = serverURL.host; + final Map credentials = { + 'name': name, + 'energy_on_100gr': energy_on_100gr, + 'proteins_on_100gr': proteins_on_100gr, + 'fats_on_100gr': fats_on_100gr, + 'carbohydrates_on_100gr': carbohydrates_on_100gr, + }; + + var headers = { + //'Content-Length': bodyBytes, + 'Host': host, + }; + + var response = await http.post( + url, + headers: headers, + body: credentials, + encoding: utf8, + ); + + if (response.statusCode == 200) { + return response; + } else { + throw Exception( + 'Failed to send a product for moderation ${response.statusCode}', + ); + } + } + + FutureOr _addComment( + AddComment event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + var updatedState = currentState.copyWith( + commentController: TextEditingController(text: event.comment), + ); + + // Отправляем данные по HTTP маршруту и ждем ответ + var response = await sendCommentData( + event.comment, + currentState.diary.id, + ); + + if (response.statusCode == 200) { + emit(updatedState); // Передаем обновленное состояние в emit + } + } + } + + Future sendCommentData( + String comment, + int diaryID, + ) async { + String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill'; + final Map credentials = { + 'comment': comment, + }; + + var response = await http.post( + Uri.parse(url), + headers: { + 'Content-Type': 'application/json', + }, + body: json.encode(credentials), + encoding: utf8, + ); + + return response; + } + + TimeOfDay toTime(String timeStr) { + List timeParts = timeStr.split(":"); + int hour = int.parse(timeParts[0]); + int minute = int.parse(timeParts[1]); + + TimeOfDay timeOfDay = TimeOfDay(hour: hour, minute: minute); + return timeOfDay; + } + + List fillMealList(List meals) { + meals.sort(compareTypes); + return meals.map((meal) { + String title = "Прием пищи ${meal['type']}"; + return SelectionPopupModel(id: meal['id'], title: title); + }).toList(); + } + + int compareTypes(a, b) { + return a['type'].compareTo(b['type']); + } + + List fillPortion() { + return [ + SelectionPopupModel(id: 0, title: "порций", isSelected: true), + SelectionPopupModel(id: 1, title: "грамм"), + ]; + } +} + +int convertToInt(dynamic value) { + if (value is int) { + return value; + } else if (value is double) { + return value.toInt(); + } else { + throw FormatException('Unexpected value type: ${value.runtimeType}'); + } +} diff --git a/lib/features/diary/presentation/bloc/diary_cubit.dart b/lib/features/diary/presentation/bloc/diary_cubit.dart deleted file mode 100644 index 26092c1..0000000 --- a/lib/features/diary/presentation/bloc/diary_cubit.dart +++ /dev/null @@ -1,20 +0,0 @@ -import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; -import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; - -class DiaryCubit extends Cubit { - final DiaryRepository diaryRepository; - - DiaryCubit({required this.diaryRepository}) : super(const DiaryState.loading()); - - loadDiary(String diaryID) async { - emit(const DiaryState.loading()); - try { - final diary = await diaryRepository.getDiary(await diaryRepository.getDiaryID().toString()); - emit(DiaryState.loaded(diary: diary)); - } catch (e) { - emit(DiaryState.error(errorMessage: e.toString())); - print(e); - } - } -} diff --git a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_event.dart b/lib/features/diary/presentation/bloc/diary_event.dart similarity index 64% rename from lib/presentation/diary/diary_edit_screen/bloc/diary_edit_event.dart rename to lib/features/diary/presentation/bloc/diary_event.dart index c2c5dad..6568873 100644 --- a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_event.dart +++ b/lib/features/diary/presentation/bloc/diary_event.dart @@ -1,21 +1,21 @@ // ignore_for_file: must_be_immutable -part of 'diary_edit_bloc.dart'; +part of 'diary_bloc.dart'; /// Abstract class for all events that can be dispatched from the -///DiaryEdit widget. +///Diary widget. /// /// Events must be immutable and implement the [Equatable] interface. @immutable -abstract class DiaryEditEvent extends Equatable {} +abstract class DiaryEvent extends Equatable {} -/// Event that is dispatched when the DiaryEdit widget is first created. -class DiaryEditInitialEvent extends DiaryEditEvent { +/// Event that is dispatched when the Diary widget is first created. +class LoadDiary extends DiaryEvent { @override List get props => []; } -class ChangeSatiety extends DiaryEditEvent { +class ChangeSatiety extends DiaryEvent { ChangeSatiety( this.selectedElement, ); @@ -25,7 +25,7 @@ class ChangeSatiety extends DiaryEditEvent { List get props => [selectedElement]; } -class ChangeMood extends DiaryEditEvent { +class ChangeMood extends DiaryEvent { ChangeMood( this.selectedElement, ); @@ -35,7 +35,7 @@ class ChangeMood extends DiaryEditEvent { List get props => [selectedElement]; } -class ChangeMealTime extends DiaryEditEvent { +class ChangeMealTime extends DiaryEvent { ChangeMealTime(this.time); final TimeOfDay time; @@ -43,7 +43,7 @@ class ChangeMealTime extends DiaryEditEvent { List get props => [time]; } -class AddComment extends DiaryEditEvent { +class AddComment extends DiaryEvent { AddComment(this.diaryId, this.comment); final String comment; final int diaryId; @@ -52,7 +52,7 @@ class AddComment extends DiaryEditEvent { List get props => [comment, diaryId]; } -class WakeupEvent extends DiaryEditEvent { +class WakeupEvent extends DiaryEvent { WakeupEvent(this.selectedTime); final TimeOfDay selectedTime; @@ -60,7 +60,7 @@ class WakeupEvent extends DiaryEditEvent { List get props => [selectedTime]; } -class RetireEvent extends DiaryEditEvent { +class RetireEvent extends DiaryEvent { RetireEvent(this.selectedTime); final TimeOfDay selectedTime; @@ -68,37 +68,37 @@ class RetireEvent extends DiaryEditEvent { List get props => [selectedTime]; } -class ToggleMoodExpandedEvent extends DiaryEditEvent { +class ToggleMoodExpandedEvent extends DiaryEvent { @override List get props => []; } -class ToggleWakeupExpandedEvent extends DiaryEditEvent { +class ToggleWakeupExpandedEvent extends DiaryEvent { @override List get props => []; } -class AddPortionEvent extends DiaryEditEvent { +class AddPortionEvent extends DiaryEvent { AddPortionEvent(); @override List get props => []; } -class RemovePortionEvent extends DiaryEditEvent { +class RemovePortionEvent extends DiaryEvent { RemovePortionEvent(this.portionId); final int portionId; @override List get props => [portionId]; } -class UploadImages extends DiaryEditEvent { +class UploadImages extends DiaryEvent { UploadImages(this.image); final XFile image; @override List get props => [image]; } -class RemoveImageEvent extends DiaryEditEvent { +class RemoveImageEvent extends DiaryEvent { RemoveImageEvent(this.photoID, this.path); final String photoID; final String path; @@ -106,24 +106,23 @@ class RemoveImageEvent extends DiaryEditEvent { List get props => [photoID, path]; } -class ProductInput extends DiaryEditEvent { +class ProductInput extends DiaryEvent { ProductInput(this.input); final String input; @override List get props => [input]; } -class ChangeMeal extends DiaryEditEvent { +class ChangeMeal extends DiaryEvent { ChangeMeal({required this.value, required this.meals}); - SelectionPopupModel value; - List? meals; + Meal value; + List? meals; @override List get props => [value, meals]; } - -class ClearInput extends DiaryEditEvent { +class ClearInput extends DiaryEvent { ClearInput({required this.value}); TextEditingController value; @@ -131,7 +130,7 @@ class ClearInput extends DiaryEditEvent { List get props => [value]; } -class ChangePortion extends DiaryEditEvent { +class ChangePortion extends DiaryEvent { ChangePortion({required this.value}); SelectionPopupModel value; @@ -139,27 +138,28 @@ class ChangePortion extends DiaryEditEvent { List get props => [value]; } -class FinishDay extends DiaryEditEvent { +class FinishDay extends DiaryEvent { FinishDay(); @override List get props => []; } -class RefreshEvent extends DiaryEditEvent { +class RefreshEvent extends DiaryEvent { RefreshEvent(); @override List get props => []; } -class SendModeration extends DiaryEditEvent { - SendModeration( - {required this.name, - required this.energyOn100gr, - required this.proteinsOn100gr, - required this.fatsOn100gr, - required this.carbohydratesOn100gr,}); +class SendModeration extends DiaryEvent { + SendModeration({ + required this.name, + required this.energyOn100gr, + required this.proteinsOn100gr, + required this.fatsOn100gr, + required this.carbohydratesOn100gr, + }); String name; String energyOn100gr; String proteinsOn100gr; diff --git a/lib/features/diary/presentation/bloc/diary_state.dart b/lib/features/diary/presentation/bloc/diary_state.dart index c673faf..d1c2c60 100644 --- a/lib/features/diary/presentation/bloc/diary_state.dart +++ b/lib/features/diary/presentation/bloc/diary_state.dart @@ -1,6 +1,9 @@ import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:flutter/material.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; +import '../../../../data/models/selectionPopupModel/selection_popup_model.dart'; + part 'diary_state.freezed.dart'; @freezed @@ -11,6 +14,31 @@ abstract class DiaryState with _$DiaryState { const factory DiaryState.loaded({ required DiaryModel diary, + String? diaryDate, + List? autocompleteList, + required List recommendedChartValues, + required List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + required TextEditingController? commentController, + required TextEditingController? productNameController, + required TextEditingController? productQuantityController, + required TextEditingController? caloriesController, + required TextEditingController? fatsController, + required TextEditingController? proteinsController, + required TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + required bool wakeupExpanded, + required bool moderationExpanded, + required bool moodExpanded, + required bool isLoading, + required bool isAdded, }) = DiaryStateLoaded; const factory DiaryState.error({ diff --git a/lib/features/diary/presentation/bloc/diary_state.freezed.dart b/lib/features/diary/presentation/bloc/diary_state.freezed.dart index 04256ba..d5d614a 100644 --- a/lib/features/diary/presentation/bloc/diary_state.freezed.dart +++ b/lib/features/diary/presentation/bloc/diary_state.freezed.dart @@ -20,7 +20,34 @@ mixin _$DiaryState { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(DiaryModel diary) loaded, + required TResult Function( + DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded) + loaded, required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; @@ -28,7 +55,34 @@ mixin _$DiaryState { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(DiaryModel diary)? loaded, + TResult? Function( + DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded)? + loaded, TResult? Function(String errorMessage)? error, }) => throw _privateConstructorUsedError; @@ -36,7 +90,34 @@ mixin _$DiaryState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(DiaryModel diary)? loaded, + TResult Function( + DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) => @@ -126,7 +207,34 @@ class _$DiaryStateImpl implements _DiaryState { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(DiaryModel diary) loaded, + required TResult Function( + DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded) + loaded, required TResult Function(String errorMessage) error, }) { return $default(); @@ -137,7 +245,34 @@ class _$DiaryStateImpl implements _DiaryState { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(DiaryModel diary)? loaded, + TResult? Function( + DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded)? + loaded, TResult? Function(String errorMessage)? error, }) { return $default?.call(); @@ -148,7 +283,34 @@ class _$DiaryStateImpl implements _DiaryState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(DiaryModel diary)? loaded, + TResult Function( + DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -240,7 +402,34 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(DiaryModel diary) loaded, + required TResult Function( + DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded) + loaded, required TResult Function(String errorMessage) error, }) { return loading(); @@ -251,7 +440,34 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(DiaryModel diary)? loaded, + TResult? Function( + DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded)? + loaded, TResult? Function(String errorMessage)? error, }) { return loading?.call(); @@ -262,7 +478,34 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(DiaryModel diary)? loaded, + TResult Function( + DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -320,7 +563,33 @@ abstract class _$$DiaryStateLoadedImplCopyWith<$Res> { $Res Function(_$DiaryStateLoadedImpl) then) = __$$DiaryStateLoadedImplCopyWithImpl<$Res>; @useResult - $Res call({DiaryModel diary}); + $Res call( + {DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded}); $DiaryModelCopyWith<$Res> get diary; } @@ -337,12 +606,137 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> @override $Res call({ Object? diary = null, + Object? diaryDate = freezed, + Object? autocompleteList = freezed, + Object? recommendedChartValues = null, + Object? consumedChartValues = null, + Object? portions = freezed, + Object? photos = freezed, + Object? currentMeal = freezed, + Object? portionController = freezed, + Object? wakeupController = freezed, + Object? retireController = freezed, + Object? mealTimeController = freezed, + Object? commentController = freezed, + Object? productNameController = freezed, + Object? productQuantityController = freezed, + Object? caloriesController = freezed, + Object? fatsController = freezed, + Object? proteinsController = freezed, + Object? carbsController = freezed, + Object? selectedMood = freezed, + Object? selectedSatiety = freezed, + Object? wakeupExpanded = null, + Object? moderationExpanded = null, + Object? moodExpanded = null, + Object? isLoading = null, + Object? isAdded = null, }) { return _then(_$DiaryStateLoadedImpl( diary: null == diary ? _value.diary : diary // ignore: cast_nullable_to_non_nullable as DiaryModel, + diaryDate: freezed == diaryDate + ? _value.diaryDate + : diaryDate // ignore: cast_nullable_to_non_nullable + as String?, + autocompleteList: freezed == autocompleteList + ? _value._autocompleteList + : autocompleteList // ignore: cast_nullable_to_non_nullable + as List?, + recommendedChartValues: null == recommendedChartValues + ? _value._recommendedChartValues + : recommendedChartValues // ignore: cast_nullable_to_non_nullable + as List, + consumedChartValues: null == consumedChartValues + ? _value._consumedChartValues + : consumedChartValues // ignore: cast_nullable_to_non_nullable + as List, + portions: freezed == portions + ? _value._portions + : portions // ignore: cast_nullable_to_non_nullable + as List?, + photos: freezed == photos + ? _value._photos + : photos // ignore: cast_nullable_to_non_nullable + as List?, + currentMeal: freezed == currentMeal + ? _value.currentMeal + : currentMeal // ignore: cast_nullable_to_non_nullable + as Meal?, + portionController: freezed == portionController + ? _value.portionController + : portionController // ignore: cast_nullable_to_non_nullable + as SelectionPopupModel?, + wakeupController: freezed == wakeupController + ? _value.wakeupController + : wakeupController // ignore: cast_nullable_to_non_nullable + as TimeOfDay?, + retireController: freezed == retireController + ? _value.retireController + : retireController // ignore: cast_nullable_to_non_nullable + as TimeOfDay?, + mealTimeController: freezed == mealTimeController + ? _value.mealTimeController + : mealTimeController // ignore: cast_nullable_to_non_nullable + as TimeOfDay?, + commentController: freezed == commentController + ? _value.commentController + : commentController // ignore: cast_nullable_to_non_nullable + as TextEditingController?, + productNameController: freezed == productNameController + ? _value.productNameController + : productNameController // ignore: cast_nullable_to_non_nullable + as TextEditingController?, + productQuantityController: freezed == productQuantityController + ? _value.productQuantityController + : productQuantityController // ignore: cast_nullable_to_non_nullable + as TextEditingController?, + caloriesController: freezed == caloriesController + ? _value.caloriesController + : caloriesController // ignore: cast_nullable_to_non_nullable + as TextEditingController?, + fatsController: freezed == fatsController + ? _value.fatsController + : fatsController // ignore: cast_nullable_to_non_nullable + as TextEditingController?, + proteinsController: freezed == proteinsController + ? _value.proteinsController + : proteinsController // ignore: cast_nullable_to_non_nullable + as TextEditingController?, + carbsController: freezed == carbsController + ? _value.carbsController + : carbsController // ignore: cast_nullable_to_non_nullable + as TextEditingController?, + selectedMood: freezed == selectedMood + ? _value.selectedMood + : selectedMood // ignore: cast_nullable_to_non_nullable + as int?, + selectedSatiety: freezed == selectedSatiety + ? _value.selectedSatiety + : selectedSatiety // ignore: cast_nullable_to_non_nullable + as int?, + wakeupExpanded: null == wakeupExpanded + ? _value.wakeupExpanded + : wakeupExpanded // ignore: cast_nullable_to_non_nullable + as bool, + moderationExpanded: null == moderationExpanded + ? _value.moderationExpanded + : moderationExpanded // ignore: cast_nullable_to_non_nullable + as bool, + moodExpanded: null == moodExpanded + ? _value.moodExpanded + : moodExpanded // ignore: cast_nullable_to_non_nullable + as bool, + isLoading: null == isLoading + ? _value.isLoading + : isLoading // ignore: cast_nullable_to_non_nullable + as bool, + isAdded: null == isAdded + ? _value.isAdded + : isAdded // ignore: cast_nullable_to_non_nullable + as bool, )); } @@ -358,14 +752,134 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> /// @nodoc class _$DiaryStateLoadedImpl implements DiaryStateLoaded { - const _$DiaryStateLoadedImpl({required this.diary}); + const _$DiaryStateLoadedImpl( + {required this.diary, + this.diaryDate, + final List? autocompleteList, + required final List recommendedChartValues, + required final List consumedChartValues, + final List? portions, + final List? photos, + this.currentMeal, + this.portionController, + this.wakeupController, + this.retireController, + this.mealTimeController, + required this.commentController, + required this.productNameController, + required this.productQuantityController, + required this.caloriesController, + required this.fatsController, + required this.proteinsController, + required this.carbsController, + this.selectedMood, + this.selectedSatiety, + required this.wakeupExpanded, + required this.moderationExpanded, + required this.moodExpanded, + required this.isLoading, + required this.isAdded}) + : _autocompleteList = autocompleteList, + _recommendedChartValues = recommendedChartValues, + _consumedChartValues = consumedChartValues, + _portions = portions, + _photos = photos; @override final DiaryModel diary; + @override + final String? diaryDate; + final List? _autocompleteList; + @override + List? get autocompleteList { + final value = _autocompleteList; + if (value == null) return null; + if (_autocompleteList is EqualUnmodifiableListView) + return _autocompleteList; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + final List _recommendedChartValues; + @override + List get recommendedChartValues { + if (_recommendedChartValues is EqualUnmodifiableListView) + return _recommendedChartValues; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_recommendedChartValues); + } + + final List _consumedChartValues; + @override + List get consumedChartValues { + if (_consumedChartValues is EqualUnmodifiableListView) + return _consumedChartValues; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_consumedChartValues); + } + + final List? _portions; + @override + List? get portions { + final value = _portions; + if (value == null) return null; + if (_portions is EqualUnmodifiableListView) return _portions; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + final List? _photos; + @override + List? get photos { + final value = _photos; + if (value == null) return null; + if (_photos is EqualUnmodifiableListView) return _photos; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + final Meal? currentMeal; + @override + final SelectionPopupModel? portionController; + @override + final TimeOfDay? wakeupController; + @override + final TimeOfDay? retireController; + @override + final TimeOfDay? mealTimeController; + @override + final TextEditingController? commentController; + @override + final TextEditingController? productNameController; + @override + final TextEditingController? productQuantityController; + @override + final TextEditingController? caloriesController; + @override + final TextEditingController? fatsController; + @override + final TextEditingController? proteinsController; + @override + final TextEditingController? carbsController; + @override + final int? selectedMood; + @override + final int? selectedSatiety; + @override + final bool wakeupExpanded; + @override + final bool moderationExpanded; + @override + final bool moodExpanded; + @override + final bool isLoading; + @override + final bool isAdded; @override String toString() { - return 'DiaryState.loaded(diary: $diary)'; + return 'DiaryState.loaded(diary: $diary, diaryDate: $diaryDate, autocompleteList: $autocompleteList, recommendedChartValues: $recommendedChartValues, consumedChartValues: $consumedChartValues, portions: $portions, photos: $photos, currentMeal: $currentMeal, portionController: $portionController, wakeupController: $wakeupController, retireController: $retireController, mealTimeController: $mealTimeController, commentController: $commentController, productNameController: $productNameController, productQuantityController: $productQuantityController, caloriesController: $caloriesController, fatsController: $fatsController, proteinsController: $proteinsController, carbsController: $carbsController, selectedMood: $selectedMood, selectedSatiety: $selectedSatiety, wakeupExpanded: $wakeupExpanded, moderationExpanded: $moderationExpanded, moodExpanded: $moodExpanded, isLoading: $isLoading, isAdded: $isAdded)'; } @override @@ -373,11 +887,87 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$DiaryStateLoadedImpl && - (identical(other.diary, diary) || other.diary == diary)); + (identical(other.diary, diary) || other.diary == diary) && + (identical(other.diaryDate, diaryDate) || + other.diaryDate == diaryDate) && + const DeepCollectionEquality() + .equals(other._autocompleteList, _autocompleteList) && + const DeepCollectionEquality().equals( + other._recommendedChartValues, _recommendedChartValues) && + const DeepCollectionEquality() + .equals(other._consumedChartValues, _consumedChartValues) && + const DeepCollectionEquality().equals(other._portions, _portions) && + const DeepCollectionEquality().equals(other._photos, _photos) && + (identical(other.currentMeal, currentMeal) || + other.currentMeal == currentMeal) && + (identical(other.portionController, portionController) || + other.portionController == portionController) && + (identical(other.wakeupController, wakeupController) || + other.wakeupController == wakeupController) && + (identical(other.retireController, retireController) || + other.retireController == retireController) && + (identical(other.mealTimeController, mealTimeController) || + other.mealTimeController == mealTimeController) && + (identical(other.commentController, commentController) || + other.commentController == commentController) && + (identical(other.productNameController, productNameController) || + other.productNameController == productNameController) && + (identical(other.productQuantityController, + productQuantityController) || + other.productQuantityController == productQuantityController) && + (identical(other.caloriesController, caloriesController) || + other.caloriesController == caloriesController) && + (identical(other.fatsController, fatsController) || + other.fatsController == fatsController) && + (identical(other.proteinsController, proteinsController) || + other.proteinsController == proteinsController) && + (identical(other.carbsController, carbsController) || + other.carbsController == carbsController) && + (identical(other.selectedMood, selectedMood) || + other.selectedMood == selectedMood) && + (identical(other.selectedSatiety, selectedSatiety) || + other.selectedSatiety == selectedSatiety) && + (identical(other.wakeupExpanded, wakeupExpanded) || + other.wakeupExpanded == wakeupExpanded) && + (identical(other.moderationExpanded, moderationExpanded) || + other.moderationExpanded == moderationExpanded) && + (identical(other.moodExpanded, moodExpanded) || + other.moodExpanded == moodExpanded) && + (identical(other.isLoading, isLoading) || + other.isLoading == isLoading) && + (identical(other.isAdded, isAdded) || other.isAdded == isAdded)); } @override - int get hashCode => Object.hash(runtimeType, diary); + int get hashCode => Object.hashAll([ + runtimeType, + diary, + diaryDate, + const DeepCollectionEquality().hash(_autocompleteList), + const DeepCollectionEquality().hash(_recommendedChartValues), + const DeepCollectionEquality().hash(_consumedChartValues), + const DeepCollectionEquality().hash(_portions), + const DeepCollectionEquality().hash(_photos), + currentMeal, + portionController, + wakeupController, + retireController, + mealTimeController, + commentController, + productNameController, + productQuantityController, + caloriesController, + fatsController, + proteinsController, + carbsController, + selectedMood, + selectedSatiety, + wakeupExpanded, + moderationExpanded, + moodExpanded, + isLoading, + isAdded + ]); @JsonKey(ignore: true) @override @@ -391,10 +981,63 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(DiaryModel diary) loaded, + required TResult Function( + DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded) + loaded, required TResult Function(String errorMessage) error, }) { - return loaded(diary); + return loaded( + diary, + diaryDate, + autocompleteList, + recommendedChartValues, + consumedChartValues, + portions, + photos, + currentMeal, + portionController, + wakeupController, + retireController, + mealTimeController, + commentController, + productNameController, + productQuantityController, + caloriesController, + fatsController, + proteinsController, + carbsController, + selectedMood, + selectedSatiety, + wakeupExpanded, + moderationExpanded, + moodExpanded, + isLoading, + isAdded); } @override @@ -402,10 +1045,63 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(DiaryModel diary)? loaded, + TResult? Function( + DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded)? + loaded, TResult? Function(String errorMessage)? error, }) { - return loaded?.call(diary); + return loaded?.call( + diary, + diaryDate, + autocompleteList, + recommendedChartValues, + consumedChartValues, + portions, + photos, + currentMeal, + portionController, + wakeupController, + retireController, + mealTimeController, + commentController, + productNameController, + productQuantityController, + caloriesController, + fatsController, + proteinsController, + carbsController, + selectedMood, + selectedSatiety, + wakeupExpanded, + moderationExpanded, + moodExpanded, + isLoading, + isAdded); } @override @@ -413,12 +1109,65 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(DiaryModel diary)? loaded, + TResult Function( + DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { if (loaded != null) { - return loaded(diary); + return loaded( + diary, + diaryDate, + autocompleteList, + recommendedChartValues, + consumedChartValues, + portions, + photos, + currentMeal, + portionController, + wakeupController, + retireController, + mealTimeController, + commentController, + productNameController, + productQuantityController, + caloriesController, + fatsController, + proteinsController, + carbsController, + selectedMood, + selectedSatiety, + wakeupExpanded, + moderationExpanded, + moodExpanded, + isLoading, + isAdded); } return orElse(); } @@ -462,10 +1211,60 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { } abstract class DiaryStateLoaded implements DiaryState { - const factory DiaryStateLoaded({required final DiaryModel diary}) = - _$DiaryStateLoadedImpl; + const factory DiaryStateLoaded( + {required final DiaryModel diary, + final String? diaryDate, + final List? autocompleteList, + required final List recommendedChartValues, + required final List consumedChartValues, + final List? portions, + final List? photos, + final Meal? currentMeal, + final SelectionPopupModel? portionController, + final TimeOfDay? wakeupController, + final TimeOfDay? retireController, + final TimeOfDay? mealTimeController, + required final TextEditingController? commentController, + required final TextEditingController? productNameController, + required final TextEditingController? productQuantityController, + required final TextEditingController? caloriesController, + required final TextEditingController? fatsController, + required final TextEditingController? proteinsController, + required final TextEditingController? carbsController, + final int? selectedMood, + final int? selectedSatiety, + required final bool wakeupExpanded, + required final bool moderationExpanded, + required final bool moodExpanded, + required final bool isLoading, + required final bool isAdded}) = _$DiaryStateLoadedImpl; DiaryModel get diary; + String? get diaryDate; + List? get autocompleteList; + List get recommendedChartValues; + List get consumedChartValues; + List? get portions; + List? get photos; + Meal? get currentMeal; + SelectionPopupModel? get portionController; + TimeOfDay? get wakeupController; + TimeOfDay? get retireController; + TimeOfDay? get mealTimeController; + TextEditingController? get commentController; + TextEditingController? get productNameController; + TextEditingController? get productQuantityController; + TextEditingController? get caloriesController; + TextEditingController? get fatsController; + TextEditingController? get proteinsController; + TextEditingController? get carbsController; + int? get selectedMood; + int? get selectedSatiety; + bool get wakeupExpanded; + bool get moderationExpanded; + bool get moodExpanded; + bool get isLoading; + bool get isAdded; @JsonKey(ignore: true) _$$DiaryStateLoadedImplCopyWith<_$DiaryStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; @@ -539,7 +1338,34 @@ class _$DiaryStateErrorImpl implements DiaryStateError { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(DiaryModel diary) loaded, + required TResult Function( + DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded) + loaded, required TResult Function(String errorMessage) error, }) { return error(errorMessage); @@ -550,7 +1376,34 @@ class _$DiaryStateErrorImpl implements DiaryStateError { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(DiaryModel diary)? loaded, + TResult? Function( + DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded)? + loaded, TResult? Function(String errorMessage)? error, }) { return error?.call(errorMessage); @@ -561,7 +1414,34 @@ class _$DiaryStateErrorImpl implements DiaryStateError { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(DiaryModel diary)? loaded, + TResult Function( + DiaryModel diary, + String? diaryDate, + List? autocompleteList, + List recommendedChartValues, + List consumedChartValues, + List? portions, + List? photos, + Meal? currentMeal, + SelectionPopupModel? portionController, + TimeOfDay? wakeupController, + TimeOfDay? retireController, + TimeOfDay? mealTimeController, + TextEditingController? commentController, + TextEditingController? productNameController, + TextEditingController? productQuantityController, + TextEditingController? caloriesController, + TextEditingController? fatsController, + TextEditingController? proteinsController, + TextEditingController? carbsController, + int? selectedMood, + int? selectedSatiety, + bool wakeupExpanded, + bool moderationExpanded, + bool moodExpanded, + bool isLoading, + bool isAdded)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index 9cbf204..da60981 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -1,7 +1,11 @@ // ignore_for_file: unused_local_variable -/*import 'bloc/diary_edit_bloc.dart'; -import 'models/diary_edit_model.dart'; +import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.dart'; +import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; +import 'package:eatvio_app/locator_service.dart'; +import 'package:flutter/cupertino.dart'; + import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; @@ -16,42 +20,45 @@ import 'package:eatvio_app/widgets/custom_scale_element.dart'; import 'package:carousel_slider/carousel_slider.dart'; // ignore: must_be_immutable -class DiaryEditScreen extends StatelessWidget { - DiaryEditScreen({Key? key}) : super(key: key); - - static Widget builder(BuildContext context) { - return BlocProvider( - create: (context) => - DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel())) - ..add(DiaryEditInitialEvent()), - child: DiaryEditScreen(), - ); - } - +class DiaryScreen extends StatelessWidget { + DiaryScreen({Key? key}) : super(key: key); Widget build(BuildContext context) { - return BlocBuilder( - builder: (context, state) { - if (state is DiaryEditInitialState) { - // Это начальное состояние, данные ещё не загружены. - return Container( - color: Colors.white, - ); - } else if (state is DiaryEditLoadedState) { - // Данные загружены, можно строить экран. - return _buildDiaryEditScreen(context, state); - } else if (state is DiaryEditErrorState) { - // Произошла ошибка при загрузке данных. - return Center(child: Text(state.errorMessage)); - } else { - // Другие состояния, если они есть. - return Container(); // Пустой контейнер для необработанных состояний. - } - }, + return BlocProvider( + create: (context) => sl()..add(LoadDiary()), + child: BlocBuilder( + builder: (context, state) { + if (state is DiaryStateLoaded) { + return _buildDiary(context, state); + } else if (state is DiaryStateLoading) { + return Scaffold( + body: Center( + child: CupertinoActivityIndicator(), + ), + ); + } else if (state is DiaryStateError) { + return Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: Center( + child: Text(state.errorMessage), + ), + ), + ); + } else + return Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: Center( + child: Text("Неопределенная ошибка"), + ), + ), + ); + }, + ), ); } - Widget _buildDiaryEditScreen( - BuildContext context, DiaryEditLoadedState state) { + Widget _buildDiary(BuildContext context, DiaryStateLoaded state) { return RefreshIndicator( onRefresh: refreshPage(context), child: Stack( @@ -121,13 +128,13 @@ class DiaryEditScreen extends StatelessWidget { refreshPage(BuildContext context) { return () async { - context.read().add(RefreshEvent()); + context.read().add(RefreshEvent()); }; } /// Section Widget - _buildHeaderRow(BuildContext context, DiaryEditLoadedState state) { - final day = state.diaryId; + _buildHeaderRow(BuildContext context, DiaryStateLoaded state) { + final day = state.diary.id; return Container( margin: EdgeInsets.symmetric(horizontal: 16.h, vertical: 16.h), padding: EdgeInsets.symmetric( @@ -162,7 +169,7 @@ class DiaryEditScreen extends StatelessWidget { ), SizedBox(height: 2.v), Text( - state.diaryDate.toString(), + state.diary.date.toString(), style: CustomTextStyles.bodyMediumBluegray800, ), ], @@ -174,7 +181,7 @@ class DiaryEditScreen extends StatelessWidget { } /// Section Widget - _buildAddProduct(BuildContext context, DiaryEditLoadedState state) { + _buildAddProduct(BuildContext context, DiaryState state) { return CustomOutlinedButton( text: "Добавить продукт", margin: EdgeInsets.symmetric(horizontal: 10.h), @@ -185,12 +192,12 @@ class DiaryEditScreen extends StatelessWidget { addProduct(BuildContext context) { return () { - context.read().add(AddPortionEvent()); + context.read().add(AddPortionEvent()); }; } /// Section Widget - _buildAddPhoto(BuildContext context, DiaryEditLoadedState state) { + _buildAddPhoto(BuildContext context, DiaryStateLoaded state) { bool isLoading = state.isLoading; return GestureDetector( onTap: addImage(context, isLoading), @@ -258,14 +265,14 @@ class DiaryEditScreen extends StatelessWidget { List? images = await picker.pickMultiImage(); if (images.isNotEmpty) { for (var image in images) { - context.read().add(UploadImages(image)); + context.read().add(UploadImages(image)); } } }; } } - _buildMeal(BuildContext context, DiaryEditLoadedState state) { + _buildMeal(BuildContext context, DiaryStateLoaded state) { final digitsOnly = FilteringTextInputFormatter.digitsOnly; List _options = state.autocompleteList!.map((dynamic item) => item as String).toList(); @@ -329,17 +336,22 @@ class DiaryEditScreen extends StatelessWidget { SizedBox(height: 20.v), Padding( padding: EdgeInsets.symmetric(horizontal: 10.h), - child: BlocSelector( - selector: (state) => state.diaryEditModelObj, - builder: (context, diaryEditModelObj) { + child: BlocSelector( + selector: (state) { + if (state is DiaryStateLoaded) + return state.diary; + else + return null; + }, + builder: (context, diary) { return CustomDropDown( hintText: "Прием пищи", - items: diaryEditModelObj?.mealList, + items: mealsToDropdown(diary!.meals), contentPadding: EdgeInsets.symmetric( horizontal: 10.h, vertical: 9.v, ), - defaultValue: diaryEditModelObj?.mealList[0], + defaultValue: mealsToDropdown(diary.meals)[0], onChanged: changeMeal(context, state), ); }, @@ -424,13 +436,20 @@ class DiaryEditScreen extends StatelessWidget { ), Padding( padding: EdgeInsets.only(left: 30.h), - child: BlocSelector( - selector: (state) => state.diaryEditModelObj, - builder: (context, diaryEditModelObj) { + child: BlocSelector( + selector: (state) { + if (state is DiaryStateLoaded) { + return state.diary; + } else + return null; + }, + builder: (context, diary) { return CustomDropDown( - items: diaryEditModelObj?.portionList, - defaultValue: diaryEditModelObj?.portionList?[0], + items: [ + SelectionPopupModel(title: "gr"), + SelectionPopupModel(title: "pcs") + ], + defaultValue: SelectionPopupModel(title: "gr"), onChanged: changePortion(context, state), ); }, @@ -463,9 +482,9 @@ class DiaryEditScreen extends StatelessWidget { style: CustomTextStyles.bodyMediumBlack900, ), SizedBox(height: 15.v), - BlocBuilder( + BlocBuilder( builder: (context, state) { - if (state is DiaryEditLoadedState) { + if (state is DiaryStateLoaded) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ @@ -505,7 +524,7 @@ class DiaryEditScreen extends StatelessWidget { ], ); } else { - return Container(); // Возвращаем пустой контейнер, если состояние не является DiaryEditLoadedState + return Container(); // Возвращаем пустой контейнер, если состояние не является DiaryState } }, ), @@ -514,7 +533,7 @@ class DiaryEditScreen extends StatelessWidget { ); } - openCaloriesDialog(BuildContext context, DiaryEditLoadedState state) { + openCaloriesDialog(BuildContext context, DiaryStateLoaded state) { showDialog( context: context, builder: (BuildContext dialogContext) { @@ -587,7 +606,7 @@ class DiaryEditScreen extends StatelessWidget { ) { return () { // Call function to send moderation with the entered values - context.read().add( + context.read().add( SendModeration( name: name, energyOn100gr: energyOn100gr, @@ -609,12 +628,12 @@ class DiaryEditScreen extends StatelessWidget { changeSatiety(BuildContext context, int satiety) { return () { - context.read().add(ChangeSatiety(satiety)); + context.read().add(ChangeSatiety(satiety)); }; } selectProduct(AutocompleteOnSelected onSelected, String option, - DiaryEditLoadedState state) { + DiaryStateLoaded state) { state.productNameController?.text = option; return () { onSelected(option); @@ -627,7 +646,7 @@ class DiaryEditScreen extends StatelessWidget { ?.map((dynamic item) => item as String) .toList());*/ if (value.length > 2) { - context.read().add(ProductInput(value)); + context.read().add(ProductInput(value)); } }; } @@ -640,27 +659,27 @@ class DiaryEditScreen extends StatelessWidget { }; } - changeMeal(BuildContext context, DiaryEditLoadedState state) { + changeMeal(BuildContext context, DiaryStateLoaded state) { return (value) { context - .read() - .add(ChangeMeal(meals: state.meals, value: value)); + .read() + .add(ChangeMeal(meals: state.diary.meals, value: value)); }; } - changePortion(BuildContext context, DiaryEditLoadedState state) { + changePortion(BuildContext context, DiaryState state) { return (value) { - context.read().add(ChangePortion(value: value)); + context.read().add(ChangePortion(value: value)); }; } - _buildCarousel(BuildContext context, DiaryEditLoadedState state) { - if (state.photos!.isEmpty) { + _buildCarousel(BuildContext context, DiaryStateLoaded state) { + if (state.currentMeal!.photos!.isEmpty) { return Text("Фото нет"); } else { return CarouselSlider( options: CarouselOptions(height: 340.0), - items: state.photos!.map((photo) { + items: state.currentMeal!.photos!.map((photo) { return _buildPhoto( context, photo); // Assuming photos are stored as strings }).toList(), @@ -668,7 +687,7 @@ class DiaryEditScreen extends StatelessWidget { } } - _buildProduct(BuildContext context, Map portion) { + _buildProduct(BuildContext context, Portion portion) { return Container( margin: EdgeInsets.symmetric(horizontal: 10.h), padding: EdgeInsets.symmetric( @@ -688,9 +707,9 @@ class DiaryEditScreen extends StatelessWidget { top: 5.v, ), child: Text( - portion['product_name'].length > 8 - ? portion['product_name'].substring(0, 8) - : portion['product_name'], + portion.productName.length > 8 + ? portion.productName.substring(0, 8) + : portion.productName, style: CustomTextStyles.titleMedium16, ), ), @@ -701,9 +720,7 @@ class DiaryEditScreen extends StatelessWidget { bottom: 3.v, ), child: Text( - portion['quantity'].toString() + - ' ' + - portion['portion'].toString().tr, + portion.quantity.toString() + ' ' + portion.portion.toString().tr, ), ), Spacer(), @@ -722,7 +739,7 @@ class DiaryEditScreen extends StatelessWidget { ); } - _buildPhoto(BuildContext context, Map photo) { + _buildPhoto(BuildContext context, Photo photo) { return Stack( children: [ Container( @@ -731,7 +748,7 @@ class DiaryEditScreen extends StatelessWidget { borderRadius: BorderRadiusStyle.roundedBorder5, ), child: Image.network( - dotenv.env['STORAGE_URL']! + photo['path'], + dotenv.env['STORAGE_URL']! + photo.path, ), ), Positioned( @@ -756,21 +773,21 @@ class DiaryEditScreen extends StatelessWidget { ); } - removePortion(BuildContext context, Map portion) { + removePortion(BuildContext context, Portion portion) { return () { - context.read().add(RemovePortionEvent(portion['id'])); + context.read().add(RemovePortionEvent(portion.id)); }; } - removePhoto(BuildContext context, Map photo) { + removePhoto(BuildContext context, Photo photo) { return () { context - .read() - .add(RemoveImageEvent(photo['id'].toString(), photo['path'])); + .read() + .add(RemoveImageEvent(photo.id.toString(), photo.path)); }; } - _buildNutritionChart(BuildContext context, DiaryEditLoadedState state) { + _buildNutritionChart(BuildContext context, DiaryStateLoaded state) { final List recommendedValues = state .recommendedChartValues; // Рекомендуемые значения: калории, жиры, белки, углеводы final List consumedValues = state.consumedChartValues; // @@ -992,7 +1009,7 @@ class DiaryEditScreen extends StatelessWidget { } /// Section Widget - _buildComment(BuildContext context, DiaryEditLoadedState state) { + _buildComment(BuildContext context, DiaryStateLoaded state) { return Container( margin: EdgeInsets.symmetric(horizontal: 16.h), padding: EdgeInsets.symmetric( @@ -1036,7 +1053,7 @@ class DiaryEditScreen extends StatelessWidget { ); } - _buildWakupRetire(BuildContext context, DiaryEditLoadedState state) { + _buildWakupRetire(BuildContext context, DiaryStateLoaded state) { return Container( margin: EdgeInsets.symmetric(horizontal: 16.h), padding: EdgeInsets.symmetric( @@ -1112,7 +1129,7 @@ class DiaryEditScreen extends StatelessWidget { toggleWakeup(BuildContext context) { return () { - BlocProvider.of(context).add(ToggleWakeupExpandedEvent()); + BlocProvider.of(context).add(ToggleWakeupExpandedEvent()); }; } @@ -1146,7 +1163,7 @@ class DiaryEditScreen extends StatelessWidget { BuildContext dialogContext, BuildContext context) { return () { closeDialog(dialogContext); - context.read().add(FinishDay()); + context.read().add(FinishDay()); }; } @@ -1156,7 +1173,7 @@ class DiaryEditScreen extends StatelessWidget { }; } - _buildMood(BuildContext context, DiaryEditLoadedState state) { + _buildMood(BuildContext context, DiaryStateLoaded state) { return Container( margin: EdgeInsets.symmetric(horizontal: 16.h), padding: EdgeInsets.symmetric( @@ -1238,49 +1255,46 @@ class DiaryEditScreen extends StatelessWidget { changeMood(BuildContext context, int satiety) { return () { - context.read().add(ChangeMood(satiety)); + context.read().add(ChangeMood(satiety)); }; } toggleMood(BuildContext context) { return () { - BlocProvider.of(context).add(ToggleMoodExpandedEvent()); + BlocProvider.of(context).add(ToggleMoodExpandedEvent()); }; } Future _selectWakeupTime( - BuildContext context, DiaryEditLoadedState state) async { + BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.wakeupController ?? TimeOfDay.now(), ); if (pickedTime != null && pickedTime != state.wakeupController) { - state.wakeupController = pickedTime; - context.read().add(WakeupEvent(pickedTime)); + context.read().add(WakeupEvent(pickedTime)); } } Future _selectRetireTime( - BuildContext context, DiaryEditLoadedState state) async { + BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.retireController ?? TimeOfDay.now(), ); if (pickedTime != null && pickedTime != state.retireController) { - state.retireController = pickedTime; - context.read().add(RetireEvent(pickedTime)); + context.read().add(RetireEvent(pickedTime)); } } Future _selectMealTime( - BuildContext context, DiaryEditLoadedState state) async { + BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.mealTimeController ?? TimeOfDay.now(), ); if (pickedTime != null && pickedTime != state.mealTimeController) { - state.mealTimeController = pickedTime; - context.read().add(ChangeMealTime(pickedTime)); + context.read().add(ChangeMealTime(pickedTime)); } } } @@ -1296,4 +1310,13 @@ bool checkConsumedValues( // Если ни одно потребленное значение не превышает рекомендованное с соответствующим индексом return false; // Возвращаем true } -*/ \ No newline at end of file + +List mealsToDropdown(List meals) { + return meals + .map((meal) => SelectionPopupModel( + id: meal.id, + title: "Прием пищи ${meal.id}", + isSelected: false, + )) + .toList(); +} diff --git a/lib/features/diary/repositories/diary_repository.dart b/lib/features/diary/repositories/diary_repository.dart index c6b1dc4..440f419 100644 --- a/lib/features/diary/repositories/diary_repository.dart +++ b/lib/features/diary/repositories/diary_repository.dart @@ -14,7 +14,7 @@ class DiaryRepository { } } - Future getDiary(String diaryID) async { + Future getDiary(int diaryID) async { try { return await diaryService.getDiary(diaryID); } catch (e) { diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart index bf56e85..dd27f0b 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -1,5 +1,6 @@ import 'package:dio/dio.dart'; import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:flutter/material.dart'; import 'package:retrofit/retrofit.dart'; part 'diary_service.g.dart'; @@ -11,6 +12,37 @@ abstract class DiaryService { @GET('/diary/index') Future getDiaryID(); - @GET('/feed/{id}/show/') - Future getDiary(@Path() String id); + @GET('/diary/{id}/show/') + Future getDiary(@Path() int id); + + @GET('/diary/{id}/dailyNutritionData/') + Future getChart(@Path() String id); + + @POST('/diary/{diaryID}/meal/{mealID}/satiety/fill') + Future sendSatiety( + @Path() String diaryID, + String mealID, + int satiety, + ); + + @POST('/diary/{diaryID}/meal/{mealID}/mood/fill') + Future sendMood( + @Path() String diaryID, + String mealID, + int mood, + ); + + @POST('/diary/{diaryID}/wakeup/fill') + Future sendWakeup( + @Path() String diaryID, + String mealID, + TimeOfDay wakeup, + ); + + @POST('/diary/{diaryID}/retire/fill') + Future sendRetire( + @Path() String diaryID, + String mealID, + TimeOfDay retire, + ); } diff --git a/lib/features/diary/services/diary_service.g.dart b/lib/features/diary/services/diary_service.g.dart index 09ce900..294e4e3 100644 --- a/lib/features/diary/services/diary_service.g.dart +++ b/lib/features/diary/services/diary_service.g.dart @@ -45,7 +45,7 @@ class _DiaryService implements DiaryService { } @override - Future getDiary(String id) async { + Future getDiary(int id) async { final _extra = {}; final queryParameters = {}; final _headers = {}; @@ -58,7 +58,158 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/feed/${id}/show/', + '/diary/${id}/show/', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = DiaryModel.fromJson(_result.data!); + return _value; + } + + @override + Future getChart(String id) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio + .fetch>(_setStreamType(Options( + method: 'GET', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${id}/dailyNutritionData/', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = DiaryModel.fromJson(_result.data!); + return _value; + } + + @override + Future sendSatiety( + String diaryID, + String mealID, + int satiety, + ) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio + .fetch>(_setStreamType(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${diaryID}/meal/{mealID}/satiety/fill', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = DiaryModel.fromJson(_result.data!); + return _value; + } + + @override + Future sendMood( + String diaryID, + String mealID, + int mood, + ) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio + .fetch>(_setStreamType(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${diaryID}/meal/{mealID}/mood/fill', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = DiaryModel.fromJson(_result.data!); + return _value; + } + + @override + Future sendWakeup( + String diaryID, + String mealID, + TimeOfDay wakeup, + ) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio + .fetch>(_setStreamType(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${diaryID}/wakeup/fill', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = DiaryModel.fromJson(_result.data!); + return _value; + } + + @override + Future sendRetire( + String diaryID, + String mealID, + TimeOfDay retire, + ) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio + .fetch>(_setStreamType(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${diaryID}/retire/fill', queryParameters: queryParameters, data: _data, ) diff --git a/lib/locator_service.dart b/lib/locator_service.dart index 0328dc6..7f2caf5 100644 --- a/lib/locator_service.dart +++ b/lib/locator_service.dart @@ -9,7 +9,7 @@ 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:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart'; +import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.dart'; import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; import 'package:eatvio_app/features/diary/services/diary_service.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -19,18 +19,24 @@ final sl = GetIt.instance; Future init() async { // BLoC / Cubit - sl.registerLazySingleton(() => InitializationCubit(chatRepository: sl())); + sl.registerLazySingleton( + () => InitializationCubit(chatRepository: sl())); sl.registerFactory(() => ChatRoomCubit(chatRepository: sl())); sl.registerFactory(() => FeedCubit(feedRepository: sl())); - sl.registerFactory(() => BlogPostCubit(blogPostRepository: sl())); - sl.registerFactory(() => DiaryCubit(diaryRepository: sl())); + sl.registerFactory( + () => BlogPostCubit(blogPostRepository: sl())); + sl.registerFactory(() => DiaryBloc(diaryRepository: sl())); // Repository - sl.registerLazySingleton(() => ChatRepository(chatService: sl())); - sl.registerLazySingleton(() => FeedRepository(feedService: sl())); - sl.registerLazySingleton(() => BlogPostRepository(blogPostService: sl())); - sl.registerLazySingleton(() => DiaryRepository(diaryService: sl())); + sl.registerLazySingleton( + () => ChatRepository(chatService: sl())); + sl.registerLazySingleton( + () => FeedRepository(feedService: sl())); + sl.registerLazySingleton( + () => BlogPostRepository(blogPostService: sl())); + sl.registerLazySingleton( + () => DiaryRepository(diaryService: sl())); // Services sl.registerLazySingleton(() => ChatService(sl())); diff --git a/lib/main.dart b/lib/main.dart index 684e227..bd7e66c 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -5,8 +5,7 @@ import 'package:eatvio_app/features/chat/presentation/pages/chat_select_screen/b 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'; -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'; +import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.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'; import 'package:flutter/material.dart'; @@ -42,13 +41,24 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MultiBlocProvider( providers: [ - BlocProvider(create: (context) => InitializationCubit(chatRepository: sl())), - BlocProvider(create: (context) => ThemeBloc(ThemeState(themeType: PrefUtils().getThemeData()))), - BlocProvider(create: (context) => sl()..loadFeedBlogPostList()), - BlocProvider(create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent())), - BlocProvider(create: (context) => DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel()))..add(DiaryEditInitialEvent())), + BlocProvider( + create: (context) => InitializationCubit(chatRepository: sl())), + BlocProvider( + create: (context) => + ThemeBloc(ThemeState(themeType: PrefUtils().getThemeData()))), + BlocProvider( + create: (context) => sl()..loadFeedBlogPostList()), + BlocProvider( + create: (context) => MyProfileBloc( + MyProfileState(myProfileModelObj: MyProfileModel())) + ..add(MyProfileInitialEvent())), + BlocProvider( + create: (context) => sl()..add(LoadDiary()), + ), BlocProvider( - create: (context) => ChatSelectBloc(ChatSelectState(chatSelectModelObj: ChatSelectModel()))..add(ChatSelectInitialEvent()), + create: (context) => ChatSelectBloc( + ChatSelectState(chatSelectModelObj: ChatSelectModel())) + ..add(ChatSelectInitialEvent()), ), ], child: BlocListener( 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 deleted file mode 100644 index e93f295..0000000 --- a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_bloc.dart +++ /dev/null @@ -1,1078 +0,0 @@ -import 'dart:async'; -import 'package:intl/intl.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'; - -part 'diary_edit_event.dart'; -part 'diary_edit_state.dart'; - -/// A bloc that manages the state of a DiaryEdit according to the event that is dispatched to it. -class DiaryEditBloc extends Bloc { - DiaryEditBloc(DiaryEditState initialState) : super(initialState) { - on(_onInitialize); - on(_changeSatiety); // пользователь нажимает на шкалу сытости - on(_changeMood); // пользователь нажимает на шкалу настроения - on(_changeMealTime); // пользовательяет времяа пиши - on(_changeMeal); - on(_changePortion); - on(_changeWakeup); // пользователь выбирает время пробуждения - on(_changeRetire); // пользователь выбирает время отхода ко сну - on(_toggleMood); - on(_toggleWakeup); - on(_addPortion); //пользователь нажимает "Добавить продукт" - on(_removePortion); - on( - _removeImage, - ); // пользователь нажимает на крестик около продукта - on(_uploadImages); //пользователь нажимает "Добавить фото" - on(_addComment); //пользователь нажимает "Добавить комментарий" - on( - _inputProduct, - ); //пользователь нажимает "Добавить комментарий" - on(_finishDay); //пользователь нажимает "Добавить комментарий" - on(_sendModeration); - on( - reloadScreen, - ); //пользователь нажимает "Добавить комментарий" - on(_clearInput); - } - - Future _onInitialize( - DiaryEditInitialEvent event, - Emitter emit, - ) async { - try { - // final token = - // "9|laravel_sanctum_KFXbccDcWEvTPfJmV99EQv1neAggmpR2TidVGDPN34fa201a"; - final box = await Hive.openBox('token'); - final token = box.get('token'); - //print(await fetchDiaryId(token)); - final int diaryId = await fetchDiaryId(token, emit); - try { - print("Diary ID fetched"); - final diary = await fetchDiaryData(token, diaryId); - print("Screen load success"); - if (diary is Map) { - print(diary); - final String diaryDate = diary['date'] ?? DateTime.now().toString(); - final chartValues = await fetchChartValues(token, diaryId, emit); - if (state is DiaryEditLoadedState) { - // Если текущее состояние уже загружено, обновляем его - var currentState = state as DiaryEditLoadedState; - emit( - (currentState).copyWith( - currentMeal: currentState.currentMeal, - wakeupExpanded: currentState.wakeupExpanded, - moodExpanded: currentState.moodExpanded, - moderationExpanded: currentState.moderationExpanded, - token: currentState.token, - meals: currentState.meals, - portions: currentState.portions, - photos: currentState.photos, - wakeupController: currentState.wakeupController, - retireController: currentState.retireController, - commentController: currentState.commentController, - mealTimeController: currentState.mealTimeController, - productNameController: currentState.productNameController, - caloriesController: currentState.caloriesController, - proteinsController: currentState.proteinsController, - fatsController: currentState.fatsController, - carbsController: currentState.carbsController, - selectedSatiety: currentState.selectedSatiety, - selectedMood: currentState.selectedMood, - diaryDate: currentState.diaryDate, - diaryId: currentState.diaryId, - productQuantityController: currentState.productQuantityController, - recommendedChartValues: currentState.recommendedChartValues, - consumedChartValues: currentState.consumedChartValues, - autocompleteList: currentState.autocompleteList, - diaryEditModelObj: currentState.diaryEditModelObj, - ), - ); - } else { - // Если текущее состояние - начальное, создаем новое загруженное состояние - final List meals = fillMealList(diary['meals']); - emit( - DiaryEditLoadedState( - currentMeal: meals[0], - portionController: SelectionPopupModel( - id: 0, - title: "порций", - isSelected: true, - ), - wakeupExpanded: true, - moodExpanded: true, - moderationExpanded: false, - token: token, - recommendedChartValues: chartValues[0], - consumedChartValues: chartValues[1], - meals: diary['meals'], - portions: diary['meals'][0]['portions'], - photos: diary['meals'][0]['photos'], - wakeupController: toTime(diary['wakeup'] ?? "09:00"), - retireController: toTime(diary['retire'] ?? "23:00"), - mealTimeController: toTime(diary['meals'][0]['time'] ?? "10:00"), - selectedSatiety: diary['meals'][0]['satiety'], - selectedMood: diary['meals'][0]['mood'], - commentController: TextEditingController(text: diary['comment']), - productNameController: TextEditingController(), - productQuantityController: TextEditingController(), - caloriesController: TextEditingController(), - proteinsController: TextEditingController(), - fatsController: TextEditingController(), - carbsController: TextEditingController(), - diaryId: diaryId, - diaryDate: diaryDate, - autocompleteList: [], - diaryEditModelObj: state.diaryEditModelObj?.copyWith(mealList: meals, portionList: fillPortions()), - ), - ); - } - } - } catch (e) { - // Ошибка при получении данных дневника - emit(DiaryEditErrorState('Ошибка при получении данных дневника: $e')); - } - } catch (e) { - // Ошибка при получении данных дневника - emit(DiaryEditErrorState('Ошибка при получении данных о дневнике: $e')); - } - } - - fetchDiaryId(String token, Emitter emit) async { - final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/index'), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - ); - if (response.statusCode == 200) { - final data = jsonDecode(response.body); - if (data is Map && data.containsKey('id')) { - final int diaryId = data['id']; - return diaryId; - } else { - emit(DiaryEditErrorState('Некоторые необходимые данные отсутствуют.')); - print('fail'); - return -1; - } - } else { - emit(DiaryEditErrorState('Ошибка сервера: ${response.statusCode}')); - print('fail'); - return -1; - } - } - - fetchDiaryData(String token, int diaryId) async { - final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/$diaryId/show/'), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - ); - final diary = jsonDecode(response.body)['diary']; - - return diary; - } - - fetchChartValues( - String token, - int diaryID, - Emitter emit, - ) async { - final responseChart = await http.get( - Uri.parse( - dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/dailyNutritionData/', - ), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - ); - - if (responseChart.statusCode == 200) { - final responseBody = jsonDecode(responseChart.body); - - final recommendedChartValues = responseBody['dailyNutritionRecommendation'].values.map((value) => convertToInt(value)).toList(); - - final consumedChartValues = responseBody['dailyNutritionIntake'].values.map((value) => convertToInt(value)).toList(); - - print([recommendedChartValues, consumedChartValues]); - return [recommendedChartValues, consumedChartValues]; - } else { - emit(DiaryEditErrorState('Ошибка при декодировании данных КБЖУ')); - print('fail'); - return [[], []]; // Return empty lists instead of -1 - } - } - - refreshScreen( - int mealID, - DiaryEditEvent event, - Emitter emit, - ) async { - await reloadScreen(event, emit); - } - - reloadScreen( - DiaryEditEvent event, - Emitter emit, - ) async { - print("Reloading..."); - try { - //final token = - // "9|laravel_sanctum_KFXbccDcWEvTPfJmV99EQv1neAggmpR2TidVGDPN34fa201a"; final box = await Hive.openBox('token'); - final box = await Hive.openBox('token'); - final token = box.get('token'); - final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/index'), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - ); - - if (response.statusCode == 200) { - final data = jsonDecode(response.body); - if (data is Map && data.containsKey('id')) { - final int diaryId = data['id']; - - final diaryResponse = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/$diaryId/show/'), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - ); - - final diary = jsonDecode(diaryResponse.body)['diary']; - - if (diary is Map) { - final String diaryDate = diary['date'] ?? DateTime.now().toString(); - final responseChart = await http.get( - Uri.parse( - dotenv.env['SERVER_ROOT']! + '/diary/$diaryId/dailyNutritionData/', - ), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - ); - if (responseChart.statusCode == 200) { - final recommendedChartValues = jsonDecode( - responseChart.body, - )['dailyNutritionRecommendation']; - final consumedChartValues = jsonDecode(responseChart.body)['dailyNutritionIntake']; - final List meals = fillMealList(diary['meals']); - try { - await Future( - () => emit( - DiaryEditLoadedState( - diaryEditModelObj: state.diaryEditModelObj?.copyWith( - mealList: meals, - portionList: fillPortions(), - ), - currentMeal: meals[0], - portionController: SelectionPopupModel( - id: 0, - title: "порций", - isSelected: true, - ), - wakeupExpanded: true, - moodExpanded: true, - moderationExpanded: false, - token: token, - recommendedChartValues: recommendedChartValues.values.map((value) => convertToInt(value)).toList(), - consumedChartValues: consumedChartValues.values.map((value) => convertToInt(value)).toList(), - portions: diary['meals'][0]['portions'], - photos: diary['meals'][0]['photos'], - wakeupController: toTime(diary['wakeup'] ?? "09:00"), - retireController: toTime(diary['retire'] ?? "23:00"), - mealTimeController: toTime(diary['meals'][0]['time'] ?? "10:00"), - selectedSatiety: diary['meals'][0]['satiety'], - selectedMood: diary['meals'][0]['mood'], - commentController: TextEditingController(text: diary['comment']), - productNameController: TextEditingController(), - productQuantityController: TextEditingController(), - caloriesController: TextEditingController(), - proteinsController: TextEditingController(), - fatsController: TextEditingController(), - carbsController: TextEditingController(), - diaryId: diaryId, - diaryDate: diaryDate, - isLoading: false, - autocompleteList: [], - ), - ), - ); - - print("Updated"); - } catch (e) { - print("Ошибка при создании нового состояния $e"); - } - } else { - emit(DiaryEditErrorState('Ошибка при декодировании данных КБЖУ')); - } - } else { - emit( - DiaryEditErrorState( - 'Ошибка при декодировании данных дневника', - ), - ); - } - } else { - emit( - DiaryEditErrorState('Некоторые необходимые данные отсутствуют.'), - ); - } - } else { - emit(DiaryEditErrorState('Ошибка сервера: ${response.statusCode}')); - } - } catch (e) { - emit(DiaryEditErrorState('Ошибка при получении данных дневника: $e')); - } - } - - Future _changeSatiety( - ChangeSatiety event, - Emitter emit, - ) async { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - var updatedState = currentState.copyWith(selectedSatiety: event.selectedElement); - - // Отправляем данные по HTTP маршруту и ждем ответ - var response = await sendSatietyData( - currentState.token, - event.selectedElement, - currentState.currentMeal?.id, - currentState.diaryId, - ); - - if (response.statusCode == 200) { - updatedState.selectedSatiety = event.selectedElement; - emit(updatedState); // Передаем обновленное состояние в emit - } - } - } - - Future sendSatietyData( - String? token, - int selectedSatiety, - int? mealID, - int diaryID, - ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/meal/$mealID/satiety/fill'; - final Map credentials = { - 'satiety': selectedSatiety, - }; - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - body: json.encode(credentials), - encoding: utf8, - ); - return response; - } - - Future _changeMood( - ChangeMood event, - Emitter emit, - ) async { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - var updatedState = currentState.copyWith(selectedMood: event.selectedElement); - - // Отправляем данные по HTTP маршруту и ждем ответ - var response = await sendMoodData( - currentState.token, - event.selectedElement, - currentState.currentMeal?.id, - currentState.diaryId, - ); - - if (response.statusCode == 200) { - print( - 'Mood change success! meal_id: ${currentState.currentMeal?.id}, mood: ${event.selectedElement}', - ); - updatedState.selectedMood = event.selectedElement; - emit(updatedState); // Передаем обновленное состояние в emit - } - } - } - - Future sendMoodData( - String? token, - int selectedMood, - int? mealID, - int diaryID, - ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/meal/$mealID/mood/fill'; - final Map credentials = { - 'mood': selectedMood, - }; - - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - - FutureOr _changeWakeup( - WakeupEvent event, - Emitter emit, - ) async { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - var response = await sendWakeupData( - currentState.token, - event.selectedTime, - currentState.diaryId, - ); - if (response.statusCode == 200) { - await reloadScreen(event, emit); - var updatedState = currentState.copyWith(wakeupController: event.selectedTime); - print("Wakeup time changed to ${event.selectedTime}"); - emit(updatedState); // Передаем обновленное состояние в emit - } else - print("Wakeup time change error"); - } - } - - FutureOr _changeRetire( - RetireEvent event, - Emitter emit, - ) async { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - var response = await sendRetireData( - currentState.token, - event.selectedTime, - currentState.diaryId, - ); - if (response.statusCode == 200) { - await reloadScreen(event, emit); - var updatedState = currentState.copyWith(retireController: event.selectedTime); - print("Retire time changed to ${event.selectedTime}"); - emit(updatedState); // Передаем обновленное состояние в emit - } else - print("Retire time change error"); - } - } - - Future sendWakeupData( - String? token, - TimeOfDay wakeup, - int diaryID, - ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/wakeUp/fill'; - final formatter = DateFormat('HH:mm'); - final wakeupString = formatter.format(DateTime(2022, 1, 1, wakeup.hour, wakeup.minute)); - final Map credentials = { - 'wakeUp': wakeupString, - }; - - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - - Future sendRetireData( - String? token, - TimeOfDay retire, - int diaryID, - ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill'; - final formatter = DateFormat('HH:mm'); - final retireString = formatter.format(DateTime(2022, 1, 1, retire.hour, retire.minute)); - final Map credentials = { - 'retire': retireString, - }; - - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - - FutureOr _changeMealTime( - ChangeMealTime event, - Emitter emit, - ) async { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - var updatedState = currentState.copyWith(mealTimeController: event.time); - - emit(updatedState); - } - } - - Future sendMealTimeData( - String? token, - TimeOfDay mealTime, - int? mealID, - int diaryID, - ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/???'; - final Map credentials = { - 'time': mealTime, - 'meal_id': mealID, - 'diary_id': diaryID, - }; - - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - - FutureOr _changeMeal( - ChangeMeal event, - Emitter emit, - ) async { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - final meal = currentState.meals?.firstWhere( - (meal) => meal['id'] == event.value.id, - orElse: () => null, - ); - int? id = event.value.id; - DiaryEditLoadedState updatedState = currentState.copyWith( - currentMeal: event.value, - portions: meal['portions'], - photos: meal['photos'], - mealTimeController: toTime(meal['time'] ?? "1$id:00"), - selectedMood: meal['mood'], - selectedSatiety: meal['satiety'], - ); - print(updatedState.photos); - emit(updatedState); - } - } - - FutureOr _clearInput( - ClearInput event, - Emitter emit, - ) { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - DiaryEditLoadedState updatedState = currentState.copyWith(); - emit(updatedState); - } - } - - FutureOr _changePortion( - ChangePortion event, - Emitter emit, - ) { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - DiaryEditLoadedState updatedState = currentState.copyWith( - portionController: event.value, - ); - emit(updatedState); - } - } - - FutureOr _toggleMood( - ToggleMoodExpandedEvent event, - Emitter emit, - ) { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - - emit(currentState.copyWith(moodExpanded: !currentState.moodExpanded)); - currentState.moodExpanded = !currentState.moodExpanded; - } - } - - FutureOr _toggleWakeup( - ToggleWakeupExpandedEvent event, - Emitter emit, - ) { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - - emit(currentState.copyWith(wakeupExpanded: !currentState.wakeupExpanded)); - currentState.wakeupExpanded = !currentState.wakeupExpanded; - } - } - - FutureOr _addPortion( - AddPortionEvent event, - Emitter emit, - ) async { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - - var response = await sendPortionData( - currentState.token, - currentState.productNameController?.text, - currentState.portionController?.id == 0 ? 'pcs' : 'gr', - int.parse(currentState.productQuantityController!.text), - currentState.currentMeal!.id, - currentState.diaryId, - ); - - if (response.statusCode == 200) { - emit(currentState.copyWith(isAdded: true)); - await reloadScreen(event, emit); - } else { - print( - 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}', - ); - } - } - } - - FutureOr sendPortionData( - String? token, - String? name, - String portion, - int? quantity, - int? mealID, - int diaryID, - ) async { - String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/create'; - - final Map credentials = { - 'product_name': name, - 'portion': portion, - 'quantity': quantity, - }; - - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - - Future _inputProduct( - ProductInput event, - Emitter emit, - ) async { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - String? token = currentState.token; - - final Map credentials = {'name': event.input}; - final uri = Uri.parse( - '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/filter?${Uri(queryParameters: credentials).query}', - ); - - final response = await http.get( - uri, - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - ); - - final productNutritionalValues = jsonDecode(response.body)['product_nutritional_value']; - - if (productNutritionalValues is List) { - // Create a new controller with the input text and update the autocomplete list - var updatedState = currentState.copyWith( - productNameController: TextEditingController(text: event.input), - autocompleteList: productNutritionalValues.map((product) => product['name']).toList(), - ); - if (event.input.length > 3) { - updatedState = updatedState.copyWith(moderationExpanded: true); - } else { - updatedState = updatedState.copyWith(moderationExpanded: false); - } - - emit(updatedState); // Emit the updated state - } - } - } - - Future _removePortion( - RemovePortionEvent event, - Emitter emit, - ) async { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - - int? mealId = currentState.currentMeal?.id; // Rename id to mealId for clarity - - var response = await sendRemovePortion( - currentState.token, - event.portionId, - mealId, - currentState.diaryId, - ); - - if (response.statusCode == 204) { - await reloadScreen(event, emit); - } else { - print( - 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}', - ); - } - } - } - - Future sendRemovePortion( - String? token, - int? portionID, - int? mealID, - int diaryID, - ) async { - String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete'; - - var response = await http.delete( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - encoding: utf8, - ); - - return response; - } - - FutureOr _removeImage( - RemoveImageEvent event, - Emitter emit, - ) async { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - - var response = await sendRemovePhoto( - currentState.token, - event.path, - event.photoID, - currentState.currentMeal?.id, - currentState.diaryId, - ); - print(response.statusCode); - if (response.statusCode == 204) { - await reloadScreen(event, emit); - } else { - print( - 'Failed to remove photo. Status Code: ${response.statusCode} ${response.body}', - ); - } - } - } - - Future sendRemovePhoto( - String? token, - String? path, - String? photoID, - int? mealID, - int diaryID, - ) async { - String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete'; - final Map credentials = { - 'id': photoID, - 'path': path, - }; - var response = await http.delete( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - - Future _finishDay(FinishDay event, Emitter emit) async { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - - var response = await sendFinishDay( - currentState.token, - currentState.diaryId, - currentState.wakeupController, - currentState.retireController, - currentState.commentController?.text, - ); - - if (response.statusCode == 200) { - await reloadScreen(event, emit); - } - } - } - - Future sendFinishDay( - String? token, - int diaryID, - TimeOfDay? wakeup, - TimeOfDay? retire, - String? comment, - ) async { - final formatter = DateFormat('HH:mm'); - final wakeupString = formatter.format(DateTime(2022, 1, 1, wakeup!.hour, wakeup.minute)); - final retireString = formatter.format(DateTime(2022, 1, 1, retire!.hour, retire.minute)); - - final Map credentials = { - 'wakeup': wakeupString, - 'retire': retireString, - 'comment': comment ?? " ", - }; - - String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/finishDay'; - - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - - Future _uploadImages( - UploadImages event, - Emitter emit, - ) async { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - - emit(currentState.copyWith(isLoading: true)); - await uploadImageToServer( - event.image.path, - currentState.diaryId, - currentState.currentMeal!.id!, - currentState.token, - ); - await reloadScreen(event, emit); - } - } - - Future uploadImageToServer( - String imagePath, - int diaryID, - int mealId, - String? token, - ) async { - String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload'; - - var request = http.MultipartRequest('POST', Uri.parse(url)); - request.headers['Authorization'] = 'Bearer $token'; - - request.files.add(await http.MultipartFile.fromPath('photo', imagePath)); - - var client = http.Client(); - var streamedResponse = await client.send(request); - - if (streamedResponse.statusCode == 200) { - var response = await http.Response.fromStream(streamedResponse); - var imageUrl = response.body; - print('Image successfully uploaded'); - return imageUrl; - } else { - throw Exception( - 'Failed to upload image. Status code: ${streamedResponse.statusCode}}', - ); - } - } - - FutureOr _sendModeration( - SendModeration event, - Emitter emit, - ) async { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - final response = await _sendModerationData( - event.name, - event.energyOn100gr, - event.proteinsOn100gr, - event.fatsOn100gr, - event.carbohydratesOn100gr, - currentState.token, - ); - - if (response.statusCode == 200) - print("Moderation success"); - else - print("Moderation error"); - } - } - - Future _sendModerationData( - String name, - String energy_on_100gr, - String proteins_on_100gr, - String fats_on_100gr, - String carbohydrates_on_100gr, - String? token, - ) async { - final Uri url = Uri.parse( - '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/sendToModeration', - ); - final Uri serverURL = Uri.parse('${dotenv.env['SERVER_ROOT']!}'); - String host = serverURL.host; - final Map credentials = { - 'name': name, - 'energy_on_100gr': energy_on_100gr, - 'proteins_on_100gr': proteins_on_100gr, - 'fats_on_100gr': fats_on_100gr, - 'carbohydrates_on_100gr': carbohydrates_on_100gr, - }; - - var headers = { - //'Content-Length': bodyBytes, - 'Authorization': 'Bearer $token', - 'Host': host, - }; - - var response = await http.post( - url, - headers: headers, - body: credentials, - encoding: utf8, - ); - - if (response.statusCode == 200) { - return response; - } else { - throw Exception( - 'Failed to send a product for moderation ${response.statusCode}', - ); - } - } - - FutureOr _addComment( - AddComment event, - Emitter emit, - ) async { - if (state is DiaryEditLoadedState) { - var currentState = state as DiaryEditLoadedState; - var updatedState = currentState.copyWith( - commentController: TextEditingController(text: event.comment), - ); - - // Отправляем данные по HTTP маршруту и ждем ответ - var response = await sendCommentData( - currentState.token, - event.comment, - currentState.diaryId, - ); - - if (response.statusCode == 200) { - emit(updatedState); // Передаем обновленное состояние в emit - } - } - } - - Future sendCommentData( - String? token, - String comment, - int diaryID, - ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill'; - final Map credentials = { - 'comment': comment, - }; - - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - - TimeOfDay toTime(String timeStr) { - List timeParts = timeStr.split(":"); - int hour = int.parse(timeParts[0]); - int minute = int.parse(timeParts[1]); - - TimeOfDay timeOfDay = TimeOfDay(hour: hour, minute: minute); - return timeOfDay; - } - - List fillMealList(List meals) { - meals.sort(compareTypes); - return meals.map((meal) { - String title = "Прием пищи ${meal['type']}"; - return SelectionPopupModel(id: meal['id'], title: title); - }).toList(); - } - - int compareTypes(a, b) { - return a['type'].compareTo(b['type']); - } - - List fillPortions() { - return [ - SelectionPopupModel(id: 0, title: "порций", isSelected: true), - SelectionPopupModel(id: 1, title: "грамм"), - ]; - } -} - -int convertToInt(dynamic value) { - if (value is int) { - return value; - } else if (value is double) { - return value.toInt(); - } else { - throw FormatException('Unexpected value type: ${value.runtimeType}'); - } -} diff --git a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart index 71551d6..352daf7 100644 --- a/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart +++ b/lib/presentation/diary/diary_edit_screen/bloc/diary_edit_state.dart @@ -1,6 +1,6 @@ // ignore_for_file: must_be_immutable -part of 'diary_edit_bloc.dart'; +/*part of '../../../../features/diary/presentation/bloc/diary_bloc.dart'; class DiaryEditState extends Equatable { const DiaryEditState({this.diaryEditModelObj}); @@ -182,4 +182,4 @@ class DiaryEditErrorState extends DiaryEditState { @override List get props => [errorMessage]; -} +}*/ \ No newline at end of file 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 dfea7c2..1ccb56c 100644 --- a/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart +++ b/lib/presentation/diary/diary_edit_screen/diary_edit_screen.dart @@ -1,6 +1,6 @@ // ignore_for_file: unused_local_variable -import 'bloc/diary_edit_bloc.dart'; +/*import '../../../features/diary/presentation/bloc/diary_bloc.dart'; import 'models/diary_edit_model.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -1250,3 +1250,4 @@ bool checkConsumedValues(List recommendedValues, List consumedValues) // Если ни одно потребленное значение не превышает рекомендованное с соответствующим индексом return false; // Возвращаем true } +*/ \ No newline at end of file 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 deleted file mode 100644 index d403e45..0000000 --- a/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.freezed.dart +++ /dev/null @@ -1,235 +0,0 @@ -// 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 '../../../../features/blog_post_create/models/blog_post_create_credentials_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'); - -BlogPostCreateCredentialsModel _$BlogPostCreateCredentialsModelFromJson( - Map json) { - return _BlogPostCreateCredentialsModel.fromJson(json); -} - -/// @nodoc -mixin _$BlogPostCreateCredentialsModel { - String get title => throw _privateConstructorUsedError; - String get description => throw _privateConstructorUsedError; - @JsonKey(name: 'youtube_url') - String get youtubeUrl => throw _privateConstructorUsedError; - String get status => throw _privateConstructorUsedError; - - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $BlogPostCreateCredentialsModelCopyWith - get copyWith => throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $BlogPostCreateCredentialsModelCopyWith<$Res> { - 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}); -} - -/// @nodoc -class _$BlogPostCreateCredentialsModelCopyWithImpl<$Res, - $Val extends BlogPostCreateCredentialsModel> - implements $BlogPostCreateCredentialsModelCopyWith<$Res> { - _$BlogPostCreateCredentialsModelCopyWithImpl(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? title = null, - Object? description = null, - Object? youtubeUrl = null, - Object? status = null, - }) { - return _then(_value.copyWith( - title: null == title - ? _value.title - : title // ignore: cast_nullable_to_non_nullable - as String, - description: null == description - ? _value.description - : description // ignore: cast_nullable_to_non_nullable - as String, - youtubeUrl: null == youtubeUrl - ? _value.youtubeUrl - : youtubeUrl // ignore: cast_nullable_to_non_nullable - as String, - status: null == status - ? _value.status - : status // ignore: cast_nullable_to_non_nullable - as String, - ) as $Val); - } -} - -/// @nodoc -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}); -} - -/// @nodoc -class __$$BlogPostCreateCredentialsModelImplCopyWithImpl<$Res> - extends _$BlogPostCreateCredentialsModelCopyWithImpl<$Res, - _$BlogPostCreateCredentialsModelImpl> - implements _$$BlogPostCreateCredentialsModelImplCopyWith<$Res> { - __$$BlogPostCreateCredentialsModelImplCopyWithImpl( - _$BlogPostCreateCredentialsModelImpl _value, - $Res Function(_$BlogPostCreateCredentialsModelImpl) _then) - : super(_value, _then); - - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? title = null, - Object? description = null, - Object? youtubeUrl = null, - Object? status = null, - }) { - return _then(_$BlogPostCreateCredentialsModelImpl( - title: null == title - ? _value.title - : title // ignore: cast_nullable_to_non_nullable - as String, - description: null == description - ? _value.description - : description // ignore: cast_nullable_to_non_nullable - as String, - youtubeUrl: null == youtubeUrl - ? _value.youtubeUrl - : youtubeUrl // ignore: cast_nullable_to_non_nullable - as String, - status: null == status - ? _value.status - : status // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc -@JsonSerializable() -class _$BlogPostCreateCredentialsModelImpl - implements _BlogPostCreateCredentialsModel { - const _$BlogPostCreateCredentialsModelImpl( - {required this.title, - required this.description, - @JsonKey(name: 'youtube_url') required this.youtubeUrl, - this.status = 'active'}); - - factory _$BlogPostCreateCredentialsModelImpl.fromJson( - Map json) => - _$$BlogPostCreateCredentialsModelImplFromJson(json); - - @override - final String title; - @override - final String description; - @override - @JsonKey(name: 'youtube_url') - final String youtubeUrl; - @override - @JsonKey() - final String status; - - @override - String toString() { - return 'BlogPostCreateCredentialsModel(title: $title, description: $description, youtubeUrl: $youtubeUrl, status: $status)'; - } - - @override - bool operator ==(Object other) { - return identical(this, other) || - (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.status, status) || other.status == status)); - } - - @JsonKey(ignore: true) - @override - 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); - - @override - Map toJson() { - return _$$BlogPostCreateCredentialsModelImplToJson( - this, - ); - } -} - -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; - - @override - String get title; - @override - String get description; - @override - @JsonKey(name: 'youtube_url') - String get youtubeUrl; - @override - String get status; - @override - @JsonKey(ignore: true) - _$$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 deleted file mode 100644 index 5dec030..0000000 --- a/lib/presentation/feed/blog_post_create_screen/models/blog_post_create_credentials_model.g.dart +++ /dev/null @@ -1,25 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of '../../../../features/blog_post_create/models/blog_post_create_credentials_model.dart'; - -// ************************************************************************** -// 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', - ); - -Map _$$BlogPostCreateCredentialsModelImplToJson( - _$BlogPostCreateCredentialsModelImpl instance) => - { - 'title': instance.title, - 'description': instance.description, - 'youtube_url': instance.youtubeUrl, - 'status': instance.status, - }; diff --git a/lib/presentation/feed/feed_screen/models/feed_model.dart b/lib/presentation/feed/feed_screen/models/feed_model.dart deleted file mode 100644 index 9e13172..0000000 --- a/lib/presentation/feed/feed_screen/models/feed_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 [k0_page], -/// and is typically used to hold data that is passed between different parts of the application. -class FeedModel extends Equatable { - FeedModel(); - - FeedModel copyWith() { - return FeedModel(); - } - - @override - List get props => []; -} diff --git a/test/diary_test.dart b/test/diary_test.dart index 56d1c58..d506347 100644 --- a/test/diary_test.dart +++ b/test/diary_test.dart @@ -1,8 +1,8 @@ -import 'package:flutter/material.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/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/features/diary/presentation/bloc/diary_bloc.dart'; import 'package:eatvio_app/presentation/diary/diary_edit_screen/models/diary_edit_model.dart'; void main() { @@ -69,3 +69,4 @@ void main() { // Add more tests for other scenarios if needed }); } +*/ \ No newline at end of file -- 2.49.1 From aacba077b7e08dc3f9e8dcfad0f0674200eac2de Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Thu, 11 Jul 2024 14:49:50 +0300 Subject: [PATCH 039/110] feature(registration): new registration flow --- lib/app_router.dart | 6 + .../registration_cubit.dart | 10 + .../registration_state.dart | 13 + .../registration_state.freezed.dart | 315 +++ .../pages/registration_screen.dart | 201 ++ .../auth/auth_screen/auth_screen.dart | 5 +- .../additional_information_screen.dart | 48 +- .../allergies_screen/allergies_screen.dart | 81 +- .../blood_pressure_screen.dart | 241 +- .../body_circumferences_screen.dart | 140 +- .../city_of_living_screen.dart | 2287 ++++++++--------- .../credentials_screen.dart | 50 +- .../date_of_birth_screen.dart | 94 +- .../favorite_foods_screen.dart | 63 +- .../favorite_sports_screen.dart | 65 +- .../gender_screen/gender_screen.dart | 57 +- .../height_screen/height_screen.dart | 88 +- .../bloc/language_select_bloc.dart | 26 +- .../language_select_screen.dart | 126 +- .../medicine_intake_screen.dart | 64 +- .../registration/name_screen/name_screen.dart | 48 +- .../weight_screen/weight_screen.dart | 109 +- lib/widgets/app_bar/appbar_title_image.dart | 6 +- 23 files changed, 2176 insertions(+), 1967 deletions(-) create mode 100644 lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart create mode 100644 lib/features/registration/presentation/bloc/registration_cubit/registration_state.dart create mode 100644 lib/features/registration/presentation/bloc/registration_cubit/registration_state.freezed.dart create mode 100644 lib/features/registration/presentation/pages/registration_screen.dart diff --git a/lib/app_router.dart b/lib/app_router.dart index 20905a6..5ca4a54 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -2,6 +2,7 @@ import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.dart'; import 'package:eatvio_app/core/token_storage.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/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'; @@ -54,6 +55,11 @@ class AppRouter { }, builder: (context, state) => AuthScreen.builder(context), routes: [ + GoRoute( + path: 'registration-screen', + name: 'registrationScreen', + builder: (context, state) => const RegistrationScreen(), + ), GoRoute( path: 'language-select-screen', name: 'languageSelectScreen', 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 0000000..bf421e7 --- /dev/null +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart @@ -0,0 +1,10 @@ +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_state.dart'; +import 'package:eatvio_app/presentation/registration/language_select_screen/models/language_select_model.dart'; + +class RegistrationCubit extends Cubit { + RegistrationCubit() : super(RegistrationState.loaded(sheet: LanguageSelectModel().userRegistrationSheet)); + + updateSheet(UserRegistrationSheet sheet) => emit(RegistrationState.loaded(sheet: sheet)); +} 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 0000000..b6ea767 --- /dev/null +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_state.dart @@ -0,0 +1,13 @@ +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'registration_state.freezed.dart'; + +@freezed +abstract class RegistrationState with _$RegistrationState { + const factory RegistrationState() = _RegistrationState; + + const factory RegistrationState.loaded({ + required UserRegistrationSheet sheet, + }) = RegistrationStateLoaded; +} 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 0000000..01b2382 --- /dev/null +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_state.freezed.dart @@ -0,0 +1,315 @@ +// 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 { + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function(UserRegistrationSheet sheet) loaded, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function(UserRegistrationSheet sheet)? loaded, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function(UserRegistrationSheet sheet)? loaded, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map( + TResult Function(_RegistrationState value) $default, { + required TResult Function(RegistrationStateLoaded value) loaded, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_RegistrationState value)? $default, { + TResult? Function(RegistrationStateLoaded value)? loaded, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap( + TResult Function(_RegistrationState value)? $default, { + TResult Function(RegistrationStateLoaded value)? loaded, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $RegistrationStateCopyWith<$Res> { + factory $RegistrationStateCopyWith( + RegistrationState value, $Res Function(RegistrationState) then) = + _$RegistrationStateCopyWithImpl<$Res, RegistrationState>; +} + +/// @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; +} + +/// @nodoc +abstract class _$$RegistrationStateImplCopyWith<$Res> { + factory _$$RegistrationStateImplCopyWith(_$RegistrationStateImpl value, + $Res Function(_$RegistrationStateImpl) then) = + __$$RegistrationStateImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$RegistrationStateImplCopyWithImpl<$Res> + extends _$RegistrationStateCopyWithImpl<$Res, _$RegistrationStateImpl> + implements _$$RegistrationStateImplCopyWith<$Res> { + __$$RegistrationStateImplCopyWithImpl(_$RegistrationStateImpl _value, + $Res Function(_$RegistrationStateImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$RegistrationStateImpl implements _RegistrationState { + const _$RegistrationStateImpl(); + + @override + String toString() { + return 'RegistrationState()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$RegistrationStateImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function(UserRegistrationSheet sheet) loaded, + }) { + return $default(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function(UserRegistrationSheet sheet)? loaded, + }) { + return $default?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function(UserRegistrationSheet sheet)? loaded, + required TResult orElse(), + }) { + if ($default != null) { + return $default(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_RegistrationState value) $default, { + required TResult Function(RegistrationStateLoaded value) loaded, + }) { + return $default(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_RegistrationState value)? $default, { + TResult? Function(RegistrationStateLoaded value)? loaded, + }) { + return $default?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_RegistrationState value)? $default, { + TResult Function(RegistrationStateLoaded value)? loaded, + required TResult orElse(), + }) { + if ($default != null) { + return $default(this); + } + return orElse(); + } +} + +abstract class _RegistrationState implements RegistrationState { + const factory _RegistrationState() = _$RegistrationStateImpl; +} + +/// @nodoc +abstract class _$$RegistrationStateLoadedImplCopyWith<$Res> { + factory _$$RegistrationStateLoadedImplCopyWith( + _$RegistrationStateLoadedImpl value, + $Res Function(_$RegistrationStateLoadedImpl) then) = + __$$RegistrationStateLoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({UserRegistrationSheet sheet}); +} + +/// @nodoc +class __$$RegistrationStateLoadedImplCopyWithImpl<$Res> + extends _$RegistrationStateCopyWithImpl<$Res, _$RegistrationStateLoadedImpl> + implements _$$RegistrationStateLoadedImplCopyWith<$Res> { + __$$RegistrationStateLoadedImplCopyWithImpl( + _$RegistrationStateLoadedImpl _value, + $Res Function(_$RegistrationStateLoadedImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? sheet = null, + }) { + return _then(_$RegistrationStateLoadedImpl( + sheet: null == sheet + ? _value.sheet + : sheet // ignore: cast_nullable_to_non_nullable + as UserRegistrationSheet, + )); + } +} + +/// @nodoc + +class _$RegistrationStateLoadedImpl implements RegistrationStateLoaded { + const _$RegistrationStateLoadedImpl({required this.sheet}); + + @override + final UserRegistrationSheet sheet; + + @override + String toString() { + return 'RegistrationState.loaded(sheet: $sheet)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$RegistrationStateLoadedImpl && + (identical(other.sheet, sheet) || other.sheet == sheet)); + } + + @override + int get hashCode => Object.hash(runtimeType, sheet); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$RegistrationStateLoadedImplCopyWith<_$RegistrationStateLoadedImpl> + get copyWith => __$$RegistrationStateLoadedImplCopyWithImpl< + _$RegistrationStateLoadedImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function(UserRegistrationSheet sheet) loaded, + }) { + return loaded(sheet); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function(UserRegistrationSheet sheet)? loaded, + }) { + return loaded?.call(sheet); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function(UserRegistrationSheet sheet)? loaded, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(sheet); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_RegistrationState value) $default, { + required TResult Function(RegistrationStateLoaded value) loaded, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_RegistrationState value)? $default, { + TResult? Function(RegistrationStateLoaded value)? loaded, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_RegistrationState value)? $default, { + TResult Function(RegistrationStateLoaded value)? loaded, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class RegistrationStateLoaded implements RegistrationState { + const factory RegistrationStateLoaded( + {required final UserRegistrationSheet sheet}) = + _$RegistrationStateLoadedImpl; + + UserRegistrationSheet get sheet; + @JsonKey(ignore: true) + _$$RegistrationStateLoadedImplCopyWith<_$RegistrationStateLoadedImpl> + get copyWith => throw _privateConstructorUsedError; +} 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 0000000..f530f8b --- /dev/null +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -0,0 +1,201 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/core/utils/image_constant.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/features/registration/presentation/bloc/registration_cubit/registration_state.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/bloc/credentials_bloc.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/bloc/language_select_bloc.dart'; +import 'package:eatvio_app/presentation/registration/language_select_screen/language_select_screen.dart'; +import 'package:eatvio_app/presentation/registration/language_select_screen/models/language_select_model.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/theme/theme_helper.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'; + +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(); + + _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) { + (state as RegistrationStateLoaded); + 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: () { + 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.builder(context), + CredentialsScreen.builder(context, state.sheet), + NameScreen.builder(context, state.sheet), + GenderScreen.builder(context, state.sheet), + DateOfBirthScreen.builder(context, state.sheet), + CityOfLivingScreen.builder(context, state.sheet), + BodyCircumferencesScreen.builder(context, state.sheet), + WeightScreen.builder(context, state.sheet), + HeightScreen.builder(context, state.sheet), + BloodPressureScreen.builder(context, state.sheet), + AllergiesScreen.builder(context, state.sheet), + MedicineIntakeScreen.builder(context, state.sheet), + FavoriteSportsScreen.builder(context, state.sheet), + FavoriteFoodsScreen.builder(context, state.sheet), + AdditionalInformationScreen.builder(context, state.sheet), + ], + ), + ), + ); + }, + ), + ); + } +} diff --git a/lib/presentation/auth/auth_screen/auth_screen.dart b/lib/presentation/auth/auth_screen/auth_screen.dart index c435f2d..c299013 100644 --- a/lib/presentation/auth/auth_screen/auth_screen.dart +++ b/lib/presentation/auth/auth_screen/auth_screen.dart @@ -168,8 +168,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/registration/additional_information_screen/additional_information_screen.dart b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart index 1543cd5..94e6f54 100644 --- a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart +++ b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart @@ -29,46 +29,24 @@ class AdditionalInformationScreen extends StatelessWidget { @override Widget build(BuildContext context) { - return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: Container( + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: 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: (14 / 15).toDouble(), - 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), - ); - }, - ), + // 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), + // ); + // }, + // ), ], ), ), diff --git a/lib/presentation/registration/allergies_screen/allergies_screen.dart b/lib/presentation/registration/allergies_screen/allergies_screen.dart index 0c5fac4..e37134e 100644 --- a/lib/presentation/registration/allergies_screen/allergies_screen.dart +++ b/lib/presentation/registration/allergies_screen/allergies_screen.dart @@ -28,57 +28,36 @@ class AllergiesScreen extends StatefulWidget { 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: (10 / 15).toDouble(), - 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), - ); - }, - ), - ], - ), + 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), + _buildTextFormField(context), + // 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), + // ); + // }, + // ), + ], + ), ), ); } diff --git a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart b/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart index afce1b8..cf3a8a3 100644 --- a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart +++ b/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart @@ -30,148 +30,123 @@ class BloodPressureScreen extends StatefulWidget { } class _BloodPressureScreenState extends State { + final digitsOnly = FilteringTextInputFormatter.digitsOnly; + @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, + 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, ), ), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: (9 / 15).toDouble(), - backgroundColor: theme.colorScheme.onPrimary, - valueColor: AlwaysStoppedAnimation(appTheme.blueA400), + 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), - 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), + 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); + }, ), - 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), - ); - }, + 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), + ); + }, + ), ), - ), - 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), - ); - }, - ), - ], - ), + 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), + ); + }, + ), + ), + // 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), + // ); + // }, + // ), + ], + ), ), ); } diff --git a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart b/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart index b4b696d..96aa089 100644 --- a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart +++ b/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart @@ -12,7 +12,7 @@ import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_m import 'package:eatvio_app/widgets/custom_text_form_field.dart'; import 'package:flutter/material.dart'; -class BodyCircumferencesScreen extends StatelessWidget { +class BodyCircumferencesScreen extends StatefulWidget { const BodyCircumferencesScreen({Key? key}) : super(key: key); static Widget builder(BuildContext context, sheet) { @@ -23,87 +23,71 @@ class BodyCircumferencesScreen extends StatelessWidget { ); } + @override + State createState() => _BodyCircumferencesScreenState(); +} + +class _BodyCircumferencesScreenState extends State { + final digitsOnly = FilteringTextInputFormatter.digitsOnly; + @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), + 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: 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); + }, + ), + ], ), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: (6 / 15).toDouble(), - backgroundColor: theme.colorScheme.onPrimary, - valueColor: AlwaysStoppedAnimation(appTheme.blueA400), - ), + 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: 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), - ); - }, - ), - ], - ), + 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, + ); + }, + ), + // 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), + // ); + // }, + // ), + ], + ), ), ); } 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 index cd862cd..feb25d8 100644 --- 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 @@ -25,1154 +25,16 @@ class CityOfLivingScreen extends StatelessWidget { @override Widget build(BuildContext context) { - List _options = [ - "Абаза", - "Абакан", - "Абдулино", - "Абинск", - "Агидель", - "Агрыз", - "Адыгейск", - "Азнакаево", - "Азов", - "Ак-Довурак", - "Аксай", - "Алагир", - "Алапаевск", - "Алатырь", - "Алдан", - "Алейск", - "Александров", - "Александровск", - "Александровск-Сахалинский", - "Алексеевка", - "Алексин", - "Алзамай", - "АлупкаОспаривается", - "АлуштаОспаривается", - "Альметьевск", - "Амурск", - "Анадырь", - "Анапа", - "Ангарск", - "Андреаполь", - "Анжеро-Судженск", - "Анива", - "Апатиты", - "Апрелевка", - "Апшеронск", - "Арамиль", - "Аргун", - "Ардатов", - "Ардон", - "Арзамас", - "Аркадак", - "Армавир", - "АрмянскОспаривается", - "Арсеньев", - "Арск", - "Артём", - "Артёмовск", - "Артёмовский", - "Архангельск", - "Асбест", - "Асино", - "Астрахань", - "Аткарск", - "Ахтубинск", - "Ачинск", - "Аша", - "Бабаево", - "Бабушкин", - "Бавлы", - "Багратионовск", - "Байкальск", - "Баймак", - "Бакал", - "Баксан", - "Балабаново", - "Балаково", - "Балахна", - "Балашиха", - "Балашов", - "Балей", - "Балтийск", - "Барабинск", - "Барнаул", - "Барыш", - "Батайск", - "БахчисарайОспаривается", - "Бежецк", - "Белая Калитва", - "Белая Холуница", - "Белгород", - "Белебей", - "Белёв", - "Белинский", - "Белово", - "Белогорск", - "БелогорскОспаривается", - "Белозерск", - "Белокуриха", - "Беломорск", - "Белоозёрский", - "Белорецк", - "Белореченск", - "Белоусово", - "Белоярский", - "Белый", - "Бердск", - "Березники", - "Берёзовский", - "Берёзовский", - "Беслан", - "Бийск", - "Бикин", - "Билибино", - "Биробиджан", - "Бирск", - "Бирюсинск", - "Бирюч", - "Благовещенск", - "Благовещенск", - "Благодарный", - "Бобров", - "Богданович", - "Богородицк", - "Богородск", - "Боготол", - "Богучар", - "Бодайбо", - "Бокситогорск", - "Болгар", - "Бологое", - "Болотное", - "Болохово", - "Болхов", - "Большой Камень", - "Бор", - "Борзя", - "Борисоглебск", - "Боровичи", - "Боровск", - "Бородино", - "Братск", - "Бронницы", - "Брянск", - "Бугульма", - "Бугуруслан", - "Будённовск", - "Бузулук", - "Буинск", - "Буй", - "Буйнакск", - "Бутурлиновка", - "Валдай", - "Валуйки", - "Велиж", - "Великие Луки", - "Великий Новгород", - "Великий Устюг", - "Вельск", - "Венёв", - "Верещагино", - "Верея", - "Верхнеуральск", - "Верхний Тагил", - "Верхний Уфалей", - "Верхняя Пышма", - "Верхняя Салда", - "Верхняя Тура", - "Верхотурье", - "Верхоянск", - "Весьегонск", - "Ветлуга", - "Видное", - "Вилюйск", - "Вилючинск", - "Вихоревка", - "Вичуга", - "Владивосток", - "Владикавказ", - "Владимир", - "Волгоград", - "Волгодонск", - "Волгореченск", - "Волжск", - "Волжский", - "Вологда", - "Володарск", - "Волоколамск", - "Волосово", - "Волхов", - "Волчанск", - "Вольск", - "Воркута", - "Воронеж", - "Ворсма", - "Воскресенск", - "Воткинск", - "Всеволожск", - "Вуктыл", - "Выборг", - "Выкса", - "Высоковск", - "Высоцк", - "Вытегра", - "Вышний Волочёк", - "Вяземский", - "Вязники", - "Вязьма", - "Вятские Поляны", - "Гаврилов Посад", - "Гаврилов-Ям", - "Гагарин", - "Гаджиево", - "Гай", - "Галич", - "Гатчина", - "Гвардейск", - "Гдов", - "Геленджик", - "Георгиевск", - "Глазов", - "Голицыно", - "Горбатов", - "Горно-Алтайск", - "Горнозаводск", - "Горняк", - "Городец", - "Городище", - "Городовиковск", - "Гороховец", - "Горячий Ключ", - "Грайворон", - "Гремячинск", - "Грозный", - "Грязи", - "Грязовец", - "Губаха", - "Губкин", - "Губкинский", - "Гудермес", - "Гуково", - "Гулькевичи", - "Гурьевск", - "Гурьевск", - "Гусев", - "Гусиноозёрск", - "Гусь-Хрустальный", - "Давлеканово", - "Дагестанские Огни", - "Далматово", - "Дальнегорск", - "Дальнереченск", - "Данилов", - "Данков", - "Дегтярск", - "Дедовск", - "Демидов", - "Дербент", - "Десногорск", - "ДжанкойОспаривается", - "Дзержинск", - "Дзержинский", - "Дивногорск", - "Дигора", - "Димитровград", - "Дмитриев", - "Дмитров", - "Дмитровск", - "Дно", - "Добрянка", - "Долгопрудный", - "Долинск", - "Домодедово", - "Донецк", - "Донской", - "Дорогобуж", - "Дрезна", - "Дубна", - "Дубовка", - "Дудинка", - "Духовщина", - "Дюртюли", - "Дятьково", - "ЕвпаторияОспаривается", - "Егорьевск", - "Ейск", - "Екатеринбург", - "Елабуга", - "Елец", - "Елизово", - "Ельня", - "Еманжелинск", - "Емва", - "Енисейск", - "Ермолино", - "Ершов", - "Ессентуки", - "Ефремов", - "Железноводск", - "Железногорск", - "Железногорск", - "Железногорск-Илимский", - "Жердевка", - "Жигулёвск", - "Жиздра", - "Жирновск", - "Жуков", - "Жуковка", - "Жуковский", - "Завитинск", - "Заводоуковск", - "Заволжск", - "Заволжье", - "Задонск", - "Заинск", - "Закаменск", - "Заозёрный", - "Заозёрск", - "Западная Двина", - "Заполярный", - "Зарайск", - "Заречный", - "Заречный", - "Заринск", - "Звенигово", - "Звенигород", - "Зверево", - "Зеленогорск", - "Зеленоградск", - "Зеленодольск", - "Зеленокумск", - "Зерноград", - "Зея", - "Зима", - "Златоуст", - "Злынка", - "Змеиногорск", - "Знаменск", - "Зубцов", - "Зуевка", - "Ивангород", - "Иваново", - "Ивантеевка", - "Ивдель", - "Игарка", - "Ижевск", - "Избербаш", - "Изобильный", - "Иланский", - "Инза", - "Иннополис", - "Инсар", - "Инта", - "Ипатово", - "Ирбит", - "Иркутск", - "Исилькуль", - "Искитим", - "Истра", - "Ишим", - "Ишимбай", - "Йошкар-Ола", - "Кадников", - "Казань", - "Калач", - "Калач-на-Дону", - "Калачинск", - "Калининград", - "Калининск", - "Калтан", - "Калуга", - "Калязин", - "Камбарка", - "Каменка", - "Каменногорск", - "Каменск-Уральский", - "Каменск-Шахтинский", - "Камень-на-Оби", - "Камешково", - "Камызяк", - "Камышин", - "Камышлов", - "Канаш", - "Кандалакша", - "Канск", - "Карабаново", - "Карабаш", - "Карабулак", - "Карасук", - "Карачаевск", - "Карачев", - "Каргат", - "Каргополь", - "Карпинск", - "Карталы", - "Касимов", - "Касли", - "Каспийск", - "Катав-Ивановск", - "Катайск", - "Качканар", - "Кашин", - "Кашира", - "Кедровый", - "Кемерово", - "Кемь", - "КерчьОспаривается", - "Кизел", - "Кизилюрт", - "Кизляр", - "Кимовск", - "Кимры", - "Кингисепп", - "Кинель", - "Кинешма", - "Киреевск", - "Киренск", - "Киржач", - "Кириллов", - "Кириши", - "Киров", - "Киров", - "Кировград", - "Кирово-Чепецк", - "Кировск", - "Кировск", - "Кирс", - "Кирсанов", - "Киселёвск", - "Кисловодск", - "Клин", - "Клинцы", - "Княгинино", - "Ковдор", - "Ковров", - "Ковылкино", - "Когалым", - "Кодинск", - "Козельск", - "Козловка", - "Козьмодемьянск", - "Кола", - "Кологрив", - "Коломна", - "Колпашево", - "Кольчугино", - "Коммунар", - "Комсомольск", - "Комсомольск-на-Амуре", - "Конаково", - "Кондопога", - "Кондрово", - "Константиновск", - "Копейск", - "Кораблино", - "Кореновск", - "Коркино", - "Королёв", - "Короча", - "Корсаков", - "Коряжма", - "Костерёво", - "Костомукша", - "Кострома", - "Котельники", - "Котельниково", - "Котельнич", - "Котлас", - "Котово", - "Котовск", - "Кохма", - "Красавино", - "Красноармейск", - "Красноармейск", - "Красновишерск", - "Красногорск", - "Краснодар", - "Краснозаводск", - "Краснознаменск", - "Краснознаменск", - "Краснокаменск", - "Краснокамск", - "КрасноперекопскОспаривается", - "Краснослободск", - "Краснослободск", - "Краснотурьинск", - "Красноуральск", - "Красноуфимск", - "Красноярск", - "Красный Кут", - "Красный Сулин", - "Красный Холм", - "Кремёнки", - "Кропоткин", - "Крымск", - "Кстово", - "Кубинка", - "Кувандык", - "Кувшиново", - "Кудрово", - "Кудымкар", - "Кузнецк", - "Куйбышев", - "Кукмор", - "Кулебаки", - "Кумертау", - "Кунгур", - "Купино", - "Курган", - "Курганинск", - "Курильск", - "Курлово", - "Куровское", - "Курск", - "Куртамыш", - "Курчалой", - "Курчатов", - "Куса", - "Кушва", - "Кызыл", - "Кыштым", - "Кяхта", - "Лабинск", - "Лабытнанги", - "Лагань", - "Ладушкин", - "Лаишево", - "Лакинск", - "Лангепас", - "Лахденпохья", - "Лебедянь", - "Лениногорск", - "Ленинск", - "Ленинск-Кузнецкий", - "Ленск", - "Лермонтов", - "Лесной", - "Лесозаводск", - "Лесосибирск", - "Ливны", - "Ликино-Дулёво", - "Липецк", - "Липки", - "Лиски", - "Лихославль", - "Лобня", - "Лодейное Поле", - "Лосино-Петровский", - "Луга", - "Луза", - "Лукоянов", - "Луховицы", - "Лысково", - "Лысьва", - "Лыткарино", - "Льгов", - "Любань", - "Люберцы", - "Любим", - "Людиново", - "Лянтор", - "Магадан", - "Магас", - "Магнитогорск", - "Майкоп", - "Майский", - "Макаров", - "Макарьев", - "Макушино", - "Малая Вишера", - "Малгобек", - "Малмыж", - "Малоархангельск", - "Малоярославец", - "Мамадыш", - "Мамоново", - "Мантурово", - "Мариинск", - "Мариинский Посад", - "Маркс", - "Махачкала", - "Мглин", - "Мегион", - "Медвежьегорск", - "Медногорск", - "Медынь", - "Межгорье", - "Междуреченск", - "Мезень", - "Меленки", - "Мелеуз", - "Менделеевск", - "Мензелинск", - "Мещовск", - "Миасс", - "Микунь", - "Миллерово", - "Минеральные Воды", - "Минусинск", - "Миньяр", - "Мирный", - "Мирный", - "Михайлов", - "Михайловка", - "Михайловск", - "Михайловск", - "Мичуринск", - "Могоча", - "Можайск", - "Можга", - "Моздок", - "Мончегорск", - "Морозовск", - "Моршанск", - "Мосальск", - "Москва", - "Муравленко", - "Мураши", - "Мурино", - "Мурманск", - "Муром", - "Мценск", - "Мыски", - "Мытищи", - "Мышкин", - "Набережные Челны", - "Навашино", - "Наволоки", - "Надым", - "Назарово", - "Назрань", - "Называевск", - "Нальчик", - "Нариманов", - "Наро-Фоминск", - "Нарткала", - "Нарьян-Мар", - "Находка", - "Невель", - "Невельск", - "Невинномысск", - "Невьянск", - "Нелидово", - "Неман", - "Нерехта", - "Нерчинск", - "Нерюнгри", - "Нестеров", - "Нефтегорск", - "Нефтекамск", - "Нефтекумск", - "Нефтеюганск", - "Нея", - "Нижневартовск", - "Нижнекамск", - "Нижнеудинск", - "Нижние Серги", - "Нижний Ломов", - "Нижний Новгород", - "Нижний Тагил", - "Нижняя Салда", - "Нижняя Тура", - "Николаевск", - "Николаевск-на-Амуре", - "Никольск", - "Никольск", - "Никольское", - "Новая Ладога", - "Новая Ляля", - "Новоалександровск", - "Новоалтайск", - "Новоаннинский", - "Нововоронеж", - "Новодвинск", - "Новозыбков", - "Новокубанск", - "Новокузнецк", - "Новокуйбышевск", - "Новомичуринск", - "Новомосковск", - "Новопавловск", - "Новоржев", - "Новороссийск", - "Новосибирск", - "Новосиль", - "Новосокольники", - "Новотроицк", - "Новоузенск", - "Новоульяновск", - "Новоуральск", - "Новохопёрск", - "Новочебоксарск", - "Новочеркасск", - "Новошахтинск", - "Новый Оскол", - "Новый Уренгой", - "Ногинск", - "Нолинск", - "Норильск", - "Ноябрьск", - "Нурлат", - "Нытва", - "Нюрба", - "Нягань", - "Нязепетровск", - "Няндома", - "Облучье", - "Обнинск", - "Обоянь", - "Обь", - "Одинцово", - "Озёрск", - "Озёрск", - "Озёры", - "Октябрьск", - "Октябрьский", - "Окуловка", - "Олёкминск", - "Оленегорск", - "Олонец", - "Омск", - "Омутнинск", - "Онега", - "Опочка", - "Орёл", - "Оренбург", - "Орехово-Зуево", - "Орлов", - "Орск", - "Оса", - "Осинники", - "Осташков", - "Остров", - "Островной", - "Острогожск", - "Отрадное", - "Отрадный", - "Оха", - "Оханск", - "Очёр", - "Павлово", - "Павловск", - "Павловский Посад", - "Палласовка", - "Партизанск", - "Певек", - "Пенза", - "Первомайск", - "Первоуральск", - "Перевоз", - "Пересвет", - "Переславль-Залесский", - "Пермь", - "Пестово", - "Петров Вал", - "Петровск", - "Петровск-Забайкальский", - "Петрозаводск", - "Петропавловск-Камчатский", - "Петухово", - "Петушки", - "Печора", - "Печоры", - "Пикалёво", - "Пионерский", - "Питкяранта", - "Плавск", - "Пласт", - "Плёс", - "Поворино", - "Подольск", - "Подпорожье", - "Покачи", - "Покров", - "Покровск", - "Полевской", - "Полесск", - "Полысаево", - "Полярные Зори", - "Полярный", - "Поронайск", - "Порхов", - "Похвистнево", - "Почеп", - "Починок", - "Пошехонье", - "Правдинск", - "Приволжск", - "Приморск", - "Приморск", - "Приморско-Ахтарск", - "Приозерск", - "Прокопьевск", - "Пролетарск", - "Протвино", - "Прохладный", - "Псков", - "Пугачёв", - "Пудож", - "Пустошка", - "Пучеж", - "Пушкино", - "Пущино", - "Пыталово", - "Пыть-Ях", - "Пятигорск", - "Радужный", - "Радужный", - "Райчихинск", - "Раменское", - "Рассказово", - "Ревда", - "Реж", - "Реутов", - "Ржев", - "Родники", - "Рославль", - "Россошь", - "Ростов-на-Дону", - "Ростов", - "Рошаль", - "Ртищево", - "Рубцовск", - "Рудня", - "Руза", - "Рузаевка", - "Рыбинск", - "Рыбное", - "Рыльск", - "Ряжск", - "Рязань", - "СакиОспаривается", - "Салават", - "Салаир", - "Салехард", - "Сальск", - "Самара", - "Санкт-Петербург", - "Саранск", - "Сарапул", - "Саратов", - "Саров", - "Сасово", - "Сатка", - "Сафоново", - "Саяногорск", - "Саянск", - "Светлогорск", - "Светлоград", - "Светлый", - "Светогорск", - "Свирск", - "Свободный", - "Себеж", - "СевастопольОспаривается", - "Северо-Курильск", - "Северобайкальск", - "Северодвинск", - "Североморск", - "Североуральск", - "Северск", - "Севск", - "Сегежа", - "Сельцо", - "Семёнов", - "Семикаракорск", - "Семилуки", - "Сенгилей", - "Серафимович", - "Сергач", - "Сергиев Посад", - "Сердобск", - "Серов", - "Серпухов", - "Сертолово", - "Сибай", - "Сим", - "СимферопольОспаривается", - "Сковородино", - "Скопин", - "Славгород", - "Славск", - "Славянск-на-Кубани", - "Сланцы", - "Слободской", - "Слюдянка", - "Смоленск", - "Снежинск", - "Снежногорск", - "Собинка", - "Советск", - "Советск", - "Советск", - "Советская Гавань", - "Советский", - "Сокол", - "Солигалич", - "Соликамск", - "Солнечногорск", - "Соль-Илецк", - "Сольвычегодск", - "Сольцы", - "Сорочинск", - "Сорск", - "Сортавала", - "Сосенский", - "Сосновка", - "Сосновоборск", - "Сосновый Бор", - "Сосногорск", - "Сочи", - "Спас-Деменск", - "Спас-Клепики", - "Спасск", - "Спасск-Дальний", - "Спасск-Рязанский", - "Среднеколымск", - "Среднеуральск", - "Сретенск", - "Ставрополь", - "Старая Купавна", - "Старая Русса", - "Старица", - "Стародуб", - "Старый КрымОспаривается", - "Старый Оскол", - "Стерлитамак", - "Стрежевой", - "Строитель", - "Струнино", - "Ступино", - "Суворов", - "СудакОспаривается", - "Суджа", - "Судогда", - "Суздаль", - "Сунжа", - "Суоярви", - "Сураж", - "Сургут", - "Суровикино", - "Сурск", - "Сусуман", - "Сухиничи", - "Сухой Лог", - "Сызрань", - "Сыктывкар", - "Сысерть", - "Сычёвка", - "Сясьстрой", - "Тавда", - "Таганрог", - "Тайга", - "Тайшет", - "Талдом", - "Талица", - "Тамбов", - "Тара", - "Тарко-Сале", - "Таруса", - "Татарск", - "Таштагол", - "Тверь", - "Теберда", - "Тейково", - "Темников", - "Темрюк", - "Терек", - "Тетюши", - "Тимашёвск", - "Тихвин", - "Тихорецк", - "Тобольск", - "Тогучин", - "Тольятти", - "Томари", - "Томмот", - "Томск", - "Топки", - "Торжок", - "Торопец", - "Тосно", - "Тотьма", - "Трёхгорный", - "Троицк", - "Трубчевск", - "Туапсе", - "Туймазы", - "Тула", - "Тулун", - "Туран", - "Туринск", - "Тутаев", - "Тында", - "Тырныауз", - "Тюкалинск", - "Тюмень", - "Уварово", - "Углегорск", - "Углич", - "Удачный", - "Удомля", - "Ужур", - "Узловая", - "Улан-Удэ", - "Ульяновск", - "Унеча", - "Урай", - "Урень", - "Уржум", - "Урус-Мартан", - "Урюпинск", - "Усинск", - "Усмань", - "Усолье-Сибирское", - "Усолье", - "Уссурийск", - "Усть-Джегута", - "Усть-Илимск", - "Усть-Катав", - "Усть-Кут", - "Усть-Лабинск", - "Устюжна", - "Уфа", - "Ухта", - "Учалы", - "Уяр", - "Фатеж", - "ФеодосияОспаривается", - "Фокино", - "Фокино", - "Фролово", - "Фрязино", - "Фурманов", - "Хабаровск", - "Хадыженск", - "Ханты-Мансийск", - "Харабали", - "Харовск", - "Хасавюрт", - "Хвалынск", - "Хилок", - "Химки", - "Холм", - "Холмск", - "Хотьково", - "Цивильск", - "Цимлянск", - "Циолковский", - "Чадан", - "Чайковский", - "Чапаевск", - "Чаплыгин", - "Чебаркуль", - "Чебоксары", - "Чегем", - "Чекалин", - "Челябинск", - "Чердынь", - "Черемхово", - "Черепаново", - "Череповец", - "Черкесск", - "Чёрмоз", - "Черноголовка", - "Черногорск", - "Чернушка", - "Черняховск", - "Чехов", - "Чистополь", - "Чита", - "Чкаловск", - "Чудово", - "Чулым", - "Чусовой", - "Чухлома", - "Шагонар", - "Шадринск", - "Шали", - "Шарыпово", - "Шарья", - "Шатура", - "Шахты", - "Шахунья", - "Шацк", - "Шебекино", - "Шелехов", - "Шенкурск", - "Шилка", - "Шимановск", - "Шиханы", - "Шлиссельбург", - "Шумерля", - "Шумиха", - "Шуя", - "Щёкино", - "ЩёлкиноОспаривается", - "Щёлково", - "Щигры", - "Щучье", - "Электрогорск", - "Электросталь", - "Электроугли", - "Элиста", - "Энгельс", - "Эртиль", - "Югорск", - "Южа", - "Южно-Сахалинск", - "Южно-Сухокумск", - "Южноуральск", - "Юрга", - "Юрьев-Польский", - "Юрьевец", - "Юрюзань", - "Юхнов", - "Ядрин", - "Якутск", - "ЯлтаОспаривается", - "Ялуторовск", - "Янаул", - "Яранск", - "Яровое", - "Ярославль", - "Ярцево", - "Ясногорск", - "Ясный", - "Яхрома", - ]; - - return Scaffold( - appBar: _buildAppBar(context), - body: Container( + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: 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: (5 / 15).toDouble(), - backgroundColor: theme.colorScheme.onPrimary, - valueColor: AlwaysStoppedAnimation(appTheme.blueA400), - ), - ), - ), SizedBox(height: 39.v), Text("place_of_living".tr, style: theme.textTheme.headlineSmall), - Spacer(flex: 34), + SizedBox(height: 39.v), Text("country".tr, style: theme.textTheme.bodyLarge), SizedBox(height: 2.v), BlocSelector( @@ -1242,17 +104,16 @@ class CityOfLivingScreen extends StatelessWidget { ); }, ), - 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), - ); - }, - ), + // 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), + // ); + // }, + // ), ], ), ), @@ -1309,3 +170,1123 @@ buildOptions(List _options) { }); }; } + +const List _options = const [ + "Абаза", + "Абакан", + "Абдулино", + "Абинск", + "Агидель", + "Агрыз", + "Адыгейск", + "Азнакаево", + "Азов", + "Ак-Довурак", + "Аксай", + "Алагир", + "Алапаевск", + "Алатырь", + "Алдан", + "Алейск", + "Александров", + "Александровск", + "Александровск-Сахалинский", + "Алексеевка", + "Алексин", + "Алзамай", + "АлупкаОспаривается", + "АлуштаОспаривается", + "Альметьевск", + "Амурск", + "Анадырь", + "Анапа", + "Ангарск", + "Андреаполь", + "Анжеро-Судженск", + "Анива", + "Апатиты", + "Апрелевка", + "Апшеронск", + "Арамиль", + "Аргун", + "Ардатов", + "Ардон", + "Арзамас", + "Аркадак", + "Армавир", + "АрмянскОспаривается", + "Арсеньев", + "Арск", + "Артём", + "Артёмовск", + "Артёмовский", + "Архангельск", + "Асбест", + "Асино", + "Астрахань", + "Аткарск", + "Ахтубинск", + "Ачинск", + "Аша", + "Бабаево", + "Бабушкин", + "Бавлы", + "Багратионовск", + "Байкальск", + "Баймак", + "Бакал", + "Баксан", + "Балабаново", + "Балаково", + "Балахна", + "Балашиха", + "Балашов", + "Балей", + "Балтийск", + "Барабинск", + "Барнаул", + "Барыш", + "Батайск", + "БахчисарайОспаривается", + "Бежецк", + "Белая Калитва", + "Белая Холуница", + "Белгород", + "Белебей", + "Белёв", + "Белинский", + "Белово", + "Белогорск", + "БелогорскОспаривается", + "Белозерск", + "Белокуриха", + "Беломорск", + "Белоозёрский", + "Белорецк", + "Белореченск", + "Белоусово", + "Белоярский", + "Белый", + "Бердск", + "Березники", + "Берёзовский", + "Берёзовский", + "Беслан", + "Бийск", + "Бикин", + "Билибино", + "Биробиджан", + "Бирск", + "Бирюсинск", + "Бирюч", + "Благовещенск", + "Благовещенск", + "Благодарный", + "Бобров", + "Богданович", + "Богородицк", + "Богородск", + "Боготол", + "Богучар", + "Бодайбо", + "Бокситогорск", + "Болгар", + "Бологое", + "Болотное", + "Болохово", + "Болхов", + "Большой Камень", + "Бор", + "Борзя", + "Борисоглебск", + "Боровичи", + "Боровск", + "Бородино", + "Братск", + "Бронницы", + "Брянск", + "Бугульма", + "Бугуруслан", + "Будённовск", + "Бузулук", + "Буинск", + "Буй", + "Буйнакск", + "Бутурлиновка", + "Валдай", + "Валуйки", + "Велиж", + "Великие Луки", + "Великий Новгород", + "Великий Устюг", + "Вельск", + "Венёв", + "Верещагино", + "Верея", + "Верхнеуральск", + "Верхний Тагил", + "Верхний Уфалей", + "Верхняя Пышма", + "Верхняя Салда", + "Верхняя Тура", + "Верхотурье", + "Верхоянск", + "Весьегонск", + "Ветлуга", + "Видное", + "Вилюйск", + "Вилючинск", + "Вихоревка", + "Вичуга", + "Владивосток", + "Владикавказ", + "Владимир", + "Волгоград", + "Волгодонск", + "Волгореченск", + "Волжск", + "Волжский", + "Вологда", + "Володарск", + "Волоколамск", + "Волосово", + "Волхов", + "Волчанск", + "Вольск", + "Воркута", + "Воронеж", + "Ворсма", + "Воскресенск", + "Воткинск", + "Всеволожск", + "Вуктыл", + "Выборг", + "Выкса", + "Высоковск", + "Высоцк", + "Вытегра", + "Вышний Волочёк", + "Вяземский", + "Вязники", + "Вязьма", + "Вятские Поляны", + "Гаврилов Посад", + "Гаврилов-Ям", + "Гагарин", + "Гаджиево", + "Гай", + "Галич", + "Гатчина", + "Гвардейск", + "Гдов", + "Геленджик", + "Георгиевск", + "Глазов", + "Голицыно", + "Горбатов", + "Горно-Алтайск", + "Горнозаводск", + "Горняк", + "Городец", + "Городище", + "Городовиковск", + "Гороховец", + "Горячий Ключ", + "Грайворон", + "Гремячинск", + "Грозный", + "Грязи", + "Грязовец", + "Губаха", + "Губкин", + "Губкинский", + "Гудермес", + "Гуково", + "Гулькевичи", + "Гурьевск", + "Гурьевск", + "Гусев", + "Гусиноозёрск", + "Гусь-Хрустальный", + "Давлеканово", + "Дагестанские Огни", + "Далматово", + "Дальнегорск", + "Дальнереченск", + "Данилов", + "Данков", + "Дегтярск", + "Дедовск", + "Демидов", + "Дербент", + "Десногорск", + "ДжанкойОспаривается", + "Дзержинск", + "Дзержинский", + "Дивногорск", + "Дигора", + "Димитровград", + "Дмитриев", + "Дмитров", + "Дмитровск", + "Дно", + "Добрянка", + "Долгопрудный", + "Долинск", + "Домодедово", + "Донецк", + "Донской", + "Дорогобуж", + "Дрезна", + "Дубна", + "Дубовка", + "Дудинка", + "Духовщина", + "Дюртюли", + "Дятьково", + "ЕвпаторияОспаривается", + "Егорьевск", + "Ейск", + "Екатеринбург", + "Елабуга", + "Елец", + "Елизово", + "Ельня", + "Еманжелинск", + "Емва", + "Енисейск", + "Ермолино", + "Ершов", + "Ессентуки", + "Ефремов", + "Железноводск", + "Железногорск", + "Железногорск", + "Железногорск-Илимский", + "Жердевка", + "Жигулёвск", + "Жиздра", + "Жирновск", + "Жуков", + "Жуковка", + "Жуковский", + "Завитинск", + "Заводоуковск", + "Заволжск", + "Заволжье", + "Задонск", + "Заинск", + "Закаменск", + "Заозёрный", + "Заозёрск", + "Западная Двина", + "Заполярный", + "Зарайск", + "Заречный", + "Заречный", + "Заринск", + "Звенигово", + "Звенигород", + "Зверево", + "Зеленогорск", + "Зеленоградск", + "Зеленодольск", + "Зеленокумск", + "Зерноград", + "Зея", + "Зима", + "Златоуст", + "Злынка", + "Змеиногорск", + "Знаменск", + "Зубцов", + "Зуевка", + "Ивангород", + "Иваново", + "Ивантеевка", + "Ивдель", + "Игарка", + "Ижевск", + "Избербаш", + "Изобильный", + "Иланский", + "Инза", + "Иннополис", + "Инсар", + "Инта", + "Ипатово", + "Ирбит", + "Иркутск", + "Исилькуль", + "Искитим", + "Истра", + "Ишим", + "Ишимбай", + "Йошкар-Ола", + "Кадников", + "Казань", + "Калач", + "Калач-на-Дону", + "Калачинск", + "Калининград", + "Калининск", + "Калтан", + "Калуга", + "Калязин", + "Камбарка", + "Каменка", + "Каменногорск", + "Каменск-Уральский", + "Каменск-Шахтинский", + "Камень-на-Оби", + "Камешково", + "Камызяк", + "Камышин", + "Камышлов", + "Канаш", + "Кандалакша", + "Канск", + "Карабаново", + "Карабаш", + "Карабулак", + "Карасук", + "Карачаевск", + "Карачев", + "Каргат", + "Каргополь", + "Карпинск", + "Карталы", + "Касимов", + "Касли", + "Каспийск", + "Катав-Ивановск", + "Катайск", + "Качканар", + "Кашин", + "Кашира", + "Кедровый", + "Кемерово", + "Кемь", + "КерчьОспаривается", + "Кизел", + "Кизилюрт", + "Кизляр", + "Кимовск", + "Кимры", + "Кингисепп", + "Кинель", + "Кинешма", + "Киреевск", + "Киренск", + "Киржач", + "Кириллов", + "Кириши", + "Киров", + "Киров", + "Кировград", + "Кирово-Чепецк", + "Кировск", + "Кировск", + "Кирс", + "Кирсанов", + "Киселёвск", + "Кисловодск", + "Клин", + "Клинцы", + "Княгинино", + "Ковдор", + "Ковров", + "Ковылкино", + "Когалым", + "Кодинск", + "Козельск", + "Козловка", + "Козьмодемьянск", + "Кола", + "Кологрив", + "Коломна", + "Колпашево", + "Кольчугино", + "Коммунар", + "Комсомольск", + "Комсомольск-на-Амуре", + "Конаково", + "Кондопога", + "Кондрово", + "Константиновск", + "Копейск", + "Кораблино", + "Кореновск", + "Коркино", + "Королёв", + "Короча", + "Корсаков", + "Коряжма", + "Костерёво", + "Костомукша", + "Кострома", + "Котельники", + "Котельниково", + "Котельнич", + "Котлас", + "Котово", + "Котовск", + "Кохма", + "Красавино", + "Красноармейск", + "Красноармейск", + "Красновишерск", + "Красногорск", + "Краснодар", + "Краснозаводск", + "Краснознаменск", + "Краснознаменск", + "Краснокаменск", + "Краснокамск", + "КрасноперекопскОспаривается", + "Краснослободск", + "Краснослободск", + "Краснотурьинск", + "Красноуральск", + "Красноуфимск", + "Красноярск", + "Красный Кут", + "Красный Сулин", + "Красный Холм", + "Кремёнки", + "Кропоткин", + "Крымск", + "Кстово", + "Кубинка", + "Кувандык", + "Кувшиново", + "Кудрово", + "Кудымкар", + "Кузнецк", + "Куйбышев", + "Кукмор", + "Кулебаки", + "Кумертау", + "Кунгур", + "Купино", + "Курган", + "Курганинск", + "Курильск", + "Курлово", + "Куровское", + "Курск", + "Куртамыш", + "Курчалой", + "Курчатов", + "Куса", + "Кушва", + "Кызыл", + "Кыштым", + "Кяхта", + "Лабинск", + "Лабытнанги", + "Лагань", + "Ладушкин", + "Лаишево", + "Лакинск", + "Лангепас", + "Лахденпохья", + "Лебедянь", + "Лениногорск", + "Ленинск", + "Ленинск-Кузнецкий", + "Ленск", + "Лермонтов", + "Лесной", + "Лесозаводск", + "Лесосибирск", + "Ливны", + "Ликино-Дулёво", + "Липецк", + "Липки", + "Лиски", + "Лихославль", + "Лобня", + "Лодейное Поле", + "Лосино-Петровский", + "Луга", + "Луза", + "Лукоянов", + "Луховицы", + "Лысково", + "Лысьва", + "Лыткарино", + "Льгов", + "Любань", + "Люберцы", + "Любим", + "Людиново", + "Лянтор", + "Магадан", + "Магас", + "Магнитогорск", + "Майкоп", + "Майский", + "Макаров", + "Макарьев", + "Макушино", + "Малая Вишера", + "Малгобек", + "Малмыж", + "Малоархангельск", + "Малоярославец", + "Мамадыш", + "Мамоново", + "Мантурово", + "Мариинск", + "Мариинский Посад", + "Маркс", + "Махачкала", + "Мглин", + "Мегион", + "Медвежьегорск", + "Медногорск", + "Медынь", + "Межгорье", + "Междуреченск", + "Мезень", + "Меленки", + "Мелеуз", + "Менделеевск", + "Мензелинск", + "Мещовск", + "Миасс", + "Микунь", + "Миллерово", + "Минеральные Воды", + "Минусинск", + "Миньяр", + "Мирный", + "Мирный", + "Михайлов", + "Михайловка", + "Михайловск", + "Михайловск", + "Мичуринск", + "Могоча", + "Можайск", + "Можга", + "Моздок", + "Мончегорск", + "Морозовск", + "Моршанск", + "Мосальск", + "Москва", + "Муравленко", + "Мураши", + "Мурино", + "Мурманск", + "Муром", + "Мценск", + "Мыски", + "Мытищи", + "Мышкин", + "Набережные Челны", + "Навашино", + "Наволоки", + "Надым", + "Назарово", + "Назрань", + "Называевск", + "Нальчик", + "Нариманов", + "Наро-Фоминск", + "Нарткала", + "Нарьян-Мар", + "Находка", + "Невель", + "Невельск", + "Невинномысск", + "Невьянск", + "Нелидово", + "Неман", + "Нерехта", + "Нерчинск", + "Нерюнгри", + "Нестеров", + "Нефтегорск", + "Нефтекамск", + "Нефтекумск", + "Нефтеюганск", + "Нея", + "Нижневартовск", + "Нижнекамск", + "Нижнеудинск", + "Нижние Серги", + "Нижний Ломов", + "Нижний Новгород", + "Нижний Тагил", + "Нижняя Салда", + "Нижняя Тура", + "Николаевск", + "Николаевск-на-Амуре", + "Никольск", + "Никольск", + "Никольское", + "Новая Ладога", + "Новая Ляля", + "Новоалександровск", + "Новоалтайск", + "Новоаннинский", + "Нововоронеж", + "Новодвинск", + "Новозыбков", + "Новокубанск", + "Новокузнецк", + "Новокуйбышевск", + "Новомичуринск", + "Новомосковск", + "Новопавловск", + "Новоржев", + "Новороссийск", + "Новосибирск", + "Новосиль", + "Новосокольники", + "Новотроицк", + "Новоузенск", + "Новоульяновск", + "Новоуральск", + "Новохопёрск", + "Новочебоксарск", + "Новочеркасск", + "Новошахтинск", + "Новый Оскол", + "Новый Уренгой", + "Ногинск", + "Нолинск", + "Норильск", + "Ноябрьск", + "Нурлат", + "Нытва", + "Нюрба", + "Нягань", + "Нязепетровск", + "Няндома", + "Облучье", + "Обнинск", + "Обоянь", + "Обь", + "Одинцово", + "Озёрск", + "Озёрск", + "Озёры", + "Октябрьск", + "Октябрьский", + "Окуловка", + "Олёкминск", + "Оленегорск", + "Олонец", + "Омск", + "Омутнинск", + "Онега", + "Опочка", + "Орёл", + "Оренбург", + "Орехово-Зуево", + "Орлов", + "Орск", + "Оса", + "Осинники", + "Осташков", + "Остров", + "Островной", + "Острогожск", + "Отрадное", + "Отрадный", + "Оха", + "Оханск", + "Очёр", + "Павлово", + "Павловск", + "Павловский Посад", + "Палласовка", + "Партизанск", + "Певек", + "Пенза", + "Первомайск", + "Первоуральск", + "Перевоз", + "Пересвет", + "Переславль-Залесский", + "Пермь", + "Пестово", + "Петров Вал", + "Петровск", + "Петровск-Забайкальский", + "Петрозаводск", + "Петропавловск-Камчатский", + "Петухово", + "Петушки", + "Печора", + "Печоры", + "Пикалёво", + "Пионерский", + "Питкяранта", + "Плавск", + "Пласт", + "Плёс", + "Поворино", + "Подольск", + "Подпорожье", + "Покачи", + "Покров", + "Покровск", + "Полевской", + "Полесск", + "Полысаево", + "Полярные Зори", + "Полярный", + "Поронайск", + "Порхов", + "Похвистнево", + "Почеп", + "Починок", + "Пошехонье", + "Правдинск", + "Приволжск", + "Приморск", + "Приморск", + "Приморско-Ахтарск", + "Приозерск", + "Прокопьевск", + "Пролетарск", + "Протвино", + "Прохладный", + "Псков", + "Пугачёв", + "Пудож", + "Пустошка", + "Пучеж", + "Пушкино", + "Пущино", + "Пыталово", + "Пыть-Ях", + "Пятигорск", + "Радужный", + "Радужный", + "Райчихинск", + "Раменское", + "Рассказово", + "Ревда", + "Реж", + "Реутов", + "Ржев", + "Родники", + "Рославль", + "Россошь", + "Ростов-на-Дону", + "Ростов", + "Рошаль", + "Ртищево", + "Рубцовск", + "Рудня", + "Руза", + "Рузаевка", + "Рыбинск", + "Рыбное", + "Рыльск", + "Ряжск", + "Рязань", + "СакиОспаривается", + "Салават", + "Салаир", + "Салехард", + "Сальск", + "Самара", + "Санкт-Петербург", + "Саранск", + "Сарапул", + "Саратов", + "Саров", + "Сасово", + "Сатка", + "Сафоново", + "Саяногорск", + "Саянск", + "Светлогорск", + "Светлоград", + "Светлый", + "Светогорск", + "Свирск", + "Свободный", + "Себеж", + "СевастопольОспаривается", + "Северо-Курильск", + "Северобайкальск", + "Северодвинск", + "Североморск", + "Североуральск", + "Северск", + "Севск", + "Сегежа", + "Сельцо", + "Семёнов", + "Семикаракорск", + "Семилуки", + "Сенгилей", + "Серафимович", + "Сергач", + "Сергиев Посад", + "Сердобск", + "Серов", + "Серпухов", + "Сертолово", + "Сибай", + "Сим", + "СимферопольОспаривается", + "Сковородино", + "Скопин", + "Славгород", + "Славск", + "Славянск-на-Кубани", + "Сланцы", + "Слободской", + "Слюдянка", + "Смоленск", + "Снежинск", + "Снежногорск", + "Собинка", + "Советск", + "Советск", + "Советск", + "Советская Гавань", + "Советский", + "Сокол", + "Солигалич", + "Соликамск", + "Солнечногорск", + "Соль-Илецк", + "Сольвычегодск", + "Сольцы", + "Сорочинск", + "Сорск", + "Сортавала", + "Сосенский", + "Сосновка", + "Сосновоборск", + "Сосновый Бор", + "Сосногорск", + "Сочи", + "Спас-Деменск", + "Спас-Клепики", + "Спасск", + "Спасск-Дальний", + "Спасск-Рязанский", + "Среднеколымск", + "Среднеуральск", + "Сретенск", + "Ставрополь", + "Старая Купавна", + "Старая Русса", + "Старица", + "Стародуб", + "Старый КрымОспаривается", + "Старый Оскол", + "Стерлитамак", + "Стрежевой", + "Строитель", + "Струнино", + "Ступино", + "Суворов", + "СудакОспаривается", + "Суджа", + "Судогда", + "Суздаль", + "Сунжа", + "Суоярви", + "Сураж", + "Сургут", + "Суровикино", + "Сурск", + "Сусуман", + "Сухиничи", + "Сухой Лог", + "Сызрань", + "Сыктывкар", + "Сысерть", + "Сычёвка", + "Сясьстрой", + "Тавда", + "Таганрог", + "Тайга", + "Тайшет", + "Талдом", + "Талица", + "Тамбов", + "Тара", + "Тарко-Сале", + "Таруса", + "Татарск", + "Таштагол", + "Тверь", + "Теберда", + "Тейково", + "Темников", + "Темрюк", + "Терек", + "Тетюши", + "Тимашёвск", + "Тихвин", + "Тихорецк", + "Тобольск", + "Тогучин", + "Тольятти", + "Томари", + "Томмот", + "Томск", + "Топки", + "Торжок", + "Торопец", + "Тосно", + "Тотьма", + "Трёхгорный", + "Троицк", + "Трубчевск", + "Туапсе", + "Туймазы", + "Тула", + "Тулун", + "Туран", + "Туринск", + "Тутаев", + "Тында", + "Тырныауз", + "Тюкалинск", + "Тюмень", + "Уварово", + "Углегорск", + "Углич", + "Удачный", + "Удомля", + "Ужур", + "Узловая", + "Улан-Удэ", + "Ульяновск", + "Унеча", + "Урай", + "Урень", + "Уржум", + "Урус-Мартан", + "Урюпинск", + "Усинск", + "Усмань", + "Усолье-Сибирское", + "Усолье", + "Уссурийск", + "Усть-Джегута", + "Усть-Илимск", + "Усть-Катав", + "Усть-Кут", + "Усть-Лабинск", + "Устюжна", + "Уфа", + "Ухта", + "Учалы", + "Уяр", + "Фатеж", + "ФеодосияОспаривается", + "Фокино", + "Фокино", + "Фролово", + "Фрязино", + "Фурманов", + "Хабаровск", + "Хадыженск", + "Ханты-Мансийск", + "Харабали", + "Харовск", + "Хасавюрт", + "Хвалынск", + "Хилок", + "Химки", + "Холм", + "Холмск", + "Хотьково", + "Цивильск", + "Цимлянск", + "Циолковский", + "Чадан", + "Чайковский", + "Чапаевск", + "Чаплыгин", + "Чебаркуль", + "Чебоксары", + "Чегем", + "Чекалин", + "Челябинск", + "Чердынь", + "Черемхово", + "Черепаново", + "Череповец", + "Черкесск", + "Чёрмоз", + "Черноголовка", + "Черногорск", + "Чернушка", + "Черняховск", + "Чехов", + "Чистополь", + "Чита", + "Чкаловск", + "Чудово", + "Чулым", + "Чусовой", + "Чухлома", + "Шагонар", + "Шадринск", + "Шали", + "Шарыпово", + "Шарья", + "Шатура", + "Шахты", + "Шахунья", + "Шацк", + "Шебекино", + "Шелехов", + "Шенкурск", + "Шилка", + "Шимановск", + "Шиханы", + "Шлиссельбург", + "Шумерля", + "Шумиха", + "Шуя", + "Щёкино", + "ЩёлкиноОспаривается", + "Щёлково", + "Щигры", + "Щучье", + "Электрогорск", + "Электросталь", + "Электроугли", + "Элиста", + "Энгельс", + "Эртиль", + "Югорск", + "Южа", + "Южно-Сахалинск", + "Южно-Сухокумск", + "Южноуральск", + "Юрга", + "Юрьев-Польский", + "Юрьевец", + "Юрюзань", + "Юхнов", + "Ядрин", + "Якутск", + "ЯлтаОспаривается", + "Ялуторовск", + "Янаул", + "Яранск", + "Яровое", + "Ярославль", + "Ярцево", + "Ясногорск", + "Ясный", + "Яхрома", +]; diff --git a/lib/presentation/registration/credentials_screen/credentials_screen.dart b/lib/presentation/registration/credentials_screen/credentials_screen.dart index 23517a0..8fab0f4 100644 --- a/lib/presentation/registration/credentials_screen/credentials_screen.dart +++ b/lib/presentation/registration/credentials_screen/credentials_screen.dart @@ -6,7 +6,6 @@ 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'; @@ -25,34 +24,14 @@ class CredentialsScreen extends StatelessWidget { @override Widget build(BuildContext context) { - mediaQueryData = MediaQuery.of(context); - return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: Container( + 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: [ - 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 / 15).toDouble(), - 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), @@ -93,17 +72,16 @@ class CredentialsScreen extends StatelessWidget { 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), - ); - }, - ), + // 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), + // ); + // }, + // ), ], ), ), 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 index e6a223f..9683947 100644 --- 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 @@ -1,3 +1,4 @@ +import 'package:flutter/cupertino.dart'; import 'package:go_router/go_router.dart'; import 'bloc/date_of_birth_bloc.dart'; @@ -35,53 +36,33 @@ class _DateOfBirthScreenState extends State { @override Widget build(BuildContext context) { - mediaQueryData = MediaQuery.of(context); - return BlocBuilder( - builder: (context, state) { - return Scaffold( - appBar: _buildAppBar(context), - body: Container( + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: BlocBuilder( + builder: (context, state) { + return 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: (4 / 15).toDouble(), - backgroundColor: theme.colorScheme.onPrimary, - valueColor: AlwaysStoppedAnimation(appTheme.blueA400), - ), - ), - ), - SizedBox(height: 38.v), Text("date_of_birth".tr, style: theme.textTheme.headlineSmall), - Spacer(flex: 39), + const SizedBox(height: 32), _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), - ); - }, - ), + // 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), + // ); + // }, + // ), ], ), - ), - ); - }, + ); + }, + ), ); } @@ -138,10 +119,43 @@ class _DateOfBirthScreenState extends State { onTapCalendar(BuildContext context) { return () { - openDatePickerDialog(context); + // openDatePickerDialog(context); + _showDialog( + CupertinoDatePicker( + initialDateTime: DateTime.now(), + mode: CupertinoDatePickerMode.date, + onDateTimeChanged: (DateTime newTime) { + setState(() { + selectedDate = newTime; + }); + }, + ), + ); }; } + 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, + ), + ), + ); + } + /// Navigates to the previous screen. onTapArrowLeft(BuildContext context) { GoRouter.of(context).pop(); diff --git a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart b/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart index 7660118..8aaaa48 100644 --- a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart +++ b/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart @@ -29,33 +29,13 @@ class FavoriteFoodsScreen extends StatefulWidget { class _FavoriteFoodsScreenState extends State { @override Widget build(BuildContext context) { - return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: Container( + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: 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: (13 / 15).toDouble(), - 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), @@ -71,25 +51,24 @@ class _FavoriteFoodsScreenState extends State { _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), - ); - }, - ), + // 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), + // ); + // }, + // ), ], ), ), diff --git a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart b/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart index 187a284..2ff9f3c 100644 --- a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart +++ b/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart @@ -29,56 +29,35 @@ class FavoriteSportsScreen extends StatefulWidget { class _FavoriteSportsScreenState extends State { @override Widget build(BuildContext context) { - return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: Container( + 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: [ - 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: (12 / 15).toDouble(), - backgroundColor: theme.colorScheme.onPrimary, - valueColor: AlwaysStoppedAnimation(appTheme.blueA400), - ), - ), - ), - SizedBox(height: 38.v), Text("your_favorite_sports".tr, style: theme.textTheme.headlineSmall), - Spacer(flex: 32), + SizedBox(height: 22.v), _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), - ); - }, - ), + // 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), + // ); + // }, + // ), ], ), ), diff --git a/lib/presentation/registration/gender_screen/gender_screen.dart b/lib/presentation/registration/gender_screen/gender_screen.dart index 8fc7d23..df642d6 100644 --- a/lib/presentation/registration/gender_screen/gender_screen.dart +++ b/lib/presentation/registration/gender_screen/gender_screen.dart @@ -31,35 +31,15 @@ class GenderScreen extends StatefulWidget { 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( + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: BlocBuilder( + builder: (context, state) { + return 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: (3 / 15).toDouble(), - backgroundColor: theme.colorScheme.onPrimary, - valueColor: AlwaysStoppedAnimation(appTheme.blueA400), - ), - ), - ), - SizedBox(height: 36.v), Text("your_gender".tr, style: theme.textTheme.headlineSmall), RadioListTile( title: Text('Мужской'), @@ -83,22 +63,21 @@ class _GenderScreenState extends State { 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), - ); - }, - ), + // 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), + // ); + // }, + // ), ], ), - ), - ); - }, + ); + }, + ), ); } diff --git a/lib/presentation/registration/height_screen/height_screen.dart b/lib/presentation/registration/height_screen/height_screen.dart index c990dc9..5adc277 100644 --- a/lib/presentation/registration/height_screen/height_screen.dart +++ b/lib/presentation/registration/height_screen/height_screen.dart @@ -24,84 +24,40 @@ class HeightScreen extends StatelessWidget { @override Widget build(BuildContext context) { - mediaQueryData = MediaQuery.of(context); - return Scaffold( - appBar: _buildAppBar(context), - body: Container( + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: 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: (8 / 15).toDouble(), - backgroundColor: theme.colorScheme.onPrimary, - valueColor: AlwaysStoppedAnimation( - appTheme.blueA400, - ), - ), - ), + Text( + "height_measurements".tr, + style: theme.textTheme.headlineSmall, ), - SizedBox(height: 39.v), + SizedBox(height: 174.v), Column( children: [ Text( - "height_measurements".tr, - style: theme.textTheme.headlineSmall, + "your_height".tr, + style: theme.textTheme.bodyLarge, ), - 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, - ], - ); - }, - ), - ], + 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), - ); - }, - ), ], ), ), 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 index b0592bb..c77ba3a 100644 --- a/lib/presentation/registration/language_select_screen/bloc/language_select_bloc.dart +++ b/lib/presentation/registration/language_select_screen/bloc/language_select_bloc.dart @@ -2,33 +2,29 @@ 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 { +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()),),); + _onInitialize(LanguageSelectInitialEvent event, Emitter emit) async { + emit( + state.copyWith( + languageSelectModelObj: state.languageSelectModelObj?.copyWith(dropdownItemList: fillDropdownItemList()), + ), + ); } - _changeDropDown( - ChangeDropDownEvent event, - Emitter emit, - ) { + _changeDropDown(ChangeDropDownEvent event, Emitter emit) { emit(state.copyWith(selectedDropDownValue: event.value)); - state.languageSelectModelObj?.userRegistrationSheet.lang = - event.value.title; + state.languageSelectModelObj?.userRegistrationSheet.lang = event.value.title; } List fillDropdownItemList() { diff --git a/lib/presentation/registration/language_select_screen/language_select_screen.dart b/lib/presentation/registration/language_select_screen/language_select_screen.dart index 884281f..6cac92e 100644 --- a/lib/presentation/registration/language_select_screen/language_select_screen.dart +++ b/lib/presentation/registration/language_select_screen/language_select_screen.dart @@ -5,7 +5,6 @@ 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 { @@ -24,84 +23,57 @@ class LanguageSelectScreen extends StatelessWidget { @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 / 15).toDouble(), - backgroundColor: theme.colorScheme.onPrimary, - valueColor: AlwaysStoppedAnimation(appTheme.blueA400), - ), - ), + 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, ), - 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, - ), + ), + const SizedBox(height: 32), + 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), ), - 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), - ); - }, + child: CustomImageView( + imagePath: ImageConstant.imgFavorite, + height: 12.adaptSize, + width: 12.adaptSize, + ), + ), + hintText: "Не выбрано".tr, + items: languageSelectModelObj?.dropdownItemList ?? [], + onChanged: (value) => _onDropDownChanged(context, value), + ); + }, + ), + // 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), + // ); + // }, + // ), + ], ), ); } diff --git a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart b/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart index 2a55586..af7cc5a 100644 --- a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart +++ b/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart @@ -29,34 +29,13 @@ class MedicineIntakeScreen extends StatefulWidget { class _MedicineIntakeScreenState extends State { @override Widget build(BuildContext context) { - mediaQueryData = MediaQuery.of(context); - return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: Container( + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: 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: (11 / 15).toDouble(), - 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), @@ -70,25 +49,24 @@ class _MedicineIntakeScreenState extends State { ), 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), - ); - }, - ), + // 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), + // ); + // }, + // ), ], ), ), diff --git a/lib/presentation/registration/name_screen/name_screen.dart b/lib/presentation/registration/name_screen/name_screen.dart index 4fb599d..53845a5 100644 --- a/lib/presentation/registration/name_screen/name_screen.dart +++ b/lib/presentation/registration/name_screen/name_screen.dart @@ -28,34 +28,13 @@ class NameScreen extends StatelessWidget { @override Widget build(BuildContext context) { - mediaQueryData = MediaQuery.of(context); - return Scaffold( - resizeToAvoidBottomInset: false, - appBar: _buildAppBar(context), - body: Container( + return SingleChildScrollView( + padding: EdgeInsets.only(bottom: 80), + child: 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: (2 / 15).toDouble(), - 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), @@ -77,17 +56,16 @@ class NameScreen extends StatelessWidget { ); }, ), - 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 - ); - }, - ), + // 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 + // ); + // }, + // ), ], ), ), diff --git a/lib/presentation/registration/weight_screen/weight_screen.dart b/lib/presentation/registration/weight_screen/weight_screen.dart index caad9e7..4b65047 100644 --- a/lib/presentation/registration/weight_screen/weight_screen.dart +++ b/lib/presentation/registration/weight_screen/weight_screen.dart @@ -24,85 +24,42 @@ class WeightScreen extends StatelessWidget { @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, - ), + 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, ), - child: ClipRRect( - borderRadius: BorderRadius.circular(8.h), - child: LinearProgressIndicator( - value: (7 / 15).toDouble(), - backgroundColor: theme.colorScheme.onPrimary, - valueColor: AlwaysStoppedAnimation( - appTheme.blueA400, + 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, + ], + ); + }, + ), + ], ), - ), - 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), - ); - }, - ), - ], - ), + ], + ), ), ); } diff --git a/lib/widgets/app_bar/appbar_title_image.dart b/lib/widgets/app_bar/appbar_title_image.dart index 4ef20de..6242412 100644 --- a/lib/widgets/app_bar/appbar_title_image.dart +++ b/lib/widgets/app_bar/appbar_title_image.dart @@ -26,14 +26,12 @@ class AppbarTitleImage extends StatelessWidget { padding: margin ?? EdgeInsets.zero, child: CustomImageView( imagePath: imagePath, - height: 50.adaptSize, - width: 50.adaptSize, + height: 48, fit: BoxFit.contain, ), ), ); } - void onTapCall() { - } + void onTapCall() {} } -- 2.49.1 From 0f50f3b1c9e7cff4948ed51a50bd3a6a6a424732 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Thu, 11 Jul 2024 17:39:36 +0300 Subject: [PATCH 040/110] feature(registration): fix analyzer --- .../pages/registration_screen.dart | 6 -- .../additional_information_screen.dart | 15 ---- .../allergies_screen/allergies_screen.dart | 15 ---- .../blood_pressure_screen.dart | 14 ---- .../body_circumferences_screen.dart | 14 ---- .../city_of_living_screen.dart | 14 ---- .../credentials_screen.dart | 6 -- .../date_of_birth_screen.dart | 14 ---- .../favorite_foods_screen.dart | 14 ---- .../favorite_sports_screen.dart | 13 --- .../gender_screen/gender_screen.dart | 15 ---- .../height_screen/height_screen.dart | 14 ---- .../medicine_intake_screen.dart | 14 ---- .../registration/name_screen/name_screen.dart | 84 +++++++------------ .../weight_screen/weight_screen.dart | 14 ---- 15 files changed, 32 insertions(+), 234 deletions(-) diff --git a/lib/features/registration/presentation/pages/registration_screen.dart b/lib/features/registration/presentation/pages/registration_screen.dart index f530f8b..d181e3c 100644 --- a/lib/features/registration/presentation/pages/registration_screen.dart +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -1,6 +1,4 @@ import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/core/utils/image_constant.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/features/registration/presentation/bloc/registration_cubit/registration_state.dart'; import 'package:eatvio_app/presentation/registration/additional_information_screen/additional_information_screen.dart'; @@ -8,20 +6,16 @@ import 'package:eatvio_app/presentation/registration/allergies_screen/allergies_ 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/bloc/credentials_bloc.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/bloc/language_select_bloc.dart'; import 'package:eatvio_app/presentation/registration/language_select_screen/language_select_screen.dart'; -import 'package:eatvio_app/presentation/registration/language_select_screen/models/language_select_model.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/theme/theme_helper.dart'; import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; diff --git a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart index 94e6f54..d1c18d0 100644 --- a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart +++ b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart @@ -3,10 +3,6 @@ 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'; @@ -77,17 +73,6 @@ class AdditionalInformationScreen extends StatelessWidget { }; } - /// 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); diff --git a/lib/presentation/registration/allergies_screen/allergies_screen.dart b/lib/presentation/registration/allergies_screen/allergies_screen.dart index e37134e..51c5e6a 100644 --- a/lib/presentation/registration/allergies_screen/allergies_screen.dart +++ b/lib/presentation/registration/allergies_screen/allergies_screen.dart @@ -3,10 +3,6 @@ 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'; @@ -77,17 +73,6 @@ class _AllergiesScreenState extends State { }; } - /// 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); diff --git a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart b/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart index cf3a8a3..1ad3636 100644 --- a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart +++ b/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart @@ -5,11 +5,7 @@ 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'; @@ -208,16 +204,6 @@ class _BloodPressureScreenState extends State { }; } - /// 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 () { diff --git a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart b/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart index 96aa089..d9f0861 100644 --- a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart +++ b/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart @@ -4,10 +4,6 @@ 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'; @@ -132,16 +128,6 @@ class _BodyCircumferencesScreenState extends State { }; } - /// 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 () { 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 index feb25d8..0d35f1f 100644 --- 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 @@ -3,11 +3,7 @@ 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'; @@ -133,16 +129,6 @@ class CityOfLivingScreen extends StatelessWidget { }; } - /// 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 () { diff --git a/lib/presentation/registration/credentials_screen/credentials_screen.dart b/lib/presentation/registration/credentials_screen/credentials_screen.dart index 8fab0f4..d9e15d3 100644 --- a/lib/presentation/registration/credentials_screen/credentials_screen.dart +++ b/lib/presentation/registration/credentials_screen/credentials_screen.dart @@ -3,8 +3,6 @@ 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/data/models/userRegistrationModel/user_registration_model.dart'; import 'package:eatvio_app/widgets/custom_text_form_field.dart'; @@ -129,10 +127,6 @@ class CredentialsScreen extends StatelessWidget { }; } - /// 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 = []; 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 index 9683947..432a5be 100644 --- 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 @@ -4,10 +4,6 @@ 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'; @@ -74,16 +70,6 @@ class _DateOfBirthScreenState extends State { }; } - /// 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 () { diff --git a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart b/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart index 8aaaa48..a1015d7 100644 --- a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart +++ b/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart @@ -3,10 +3,6 @@ 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'; @@ -91,16 +87,6 @@ class _FavoriteFoodsScreenState extends State { }; } - /// 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 () { diff --git a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart b/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart index 2ff9f3c..5a8f3f3 100644 --- a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart +++ b/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart @@ -3,10 +3,6 @@ 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'; @@ -79,15 +75,6 @@ class _FavoriteSportsScreenState extends State { }; } - _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 () { diff --git a/lib/presentation/registration/gender_screen/gender_screen.dart b/lib/presentation/registration/gender_screen/gender_screen.dart index df642d6..72f8f5c 100644 --- a/lib/presentation/registration/gender_screen/gender_screen.dart +++ b/lib/presentation/registration/gender_screen/gender_screen.dart @@ -4,10 +4,6 @@ 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 { @@ -101,17 +97,6 @@ class _GenderScreenState extends State { }; } - /// 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 () { diff --git a/lib/presentation/registration/height_screen/height_screen.dart b/lib/presentation/registration/height_screen/height_screen.dart index 5adc277..66e2762 100644 --- a/lib/presentation/registration/height_screen/height_screen.dart +++ b/lib/presentation/registration/height_screen/height_screen.dart @@ -3,12 +3,8 @@ 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'; @@ -71,16 +67,6 @@ class HeightScreen extends StatelessWidget { }; } - /// 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 () { diff --git a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart b/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart index af7cc5a..2edc4d6 100644 --- a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart +++ b/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart @@ -3,10 +3,6 @@ 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'; @@ -94,16 +90,6 @@ class _MedicineIntakeScreenState extends State { }; } - /// 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 () { diff --git a/lib/presentation/registration/name_screen/name_screen.dart b/lib/presentation/registration/name_screen/name_screen.dart index 53845a5..be74170 100644 --- a/lib/presentation/registration/name_screen/name_screen.dart +++ b/lib/presentation/registration/name_screen/name_screen.dart @@ -1,14 +1,7 @@ -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'; @@ -72,57 +65,44 @@ class NameScreen extends StatelessWidget { ); } - /// 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'), - ), - ], - ), - ); - } - } - } + // _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); diff --git a/lib/presentation/registration/weight_screen/weight_screen.dart b/lib/presentation/registration/weight_screen/weight_screen.dart index 4b65047..9f0ab8e 100644 --- a/lib/presentation/registration/weight_screen/weight_screen.dart +++ b/lib/presentation/registration/weight_screen/weight_screen.dart @@ -3,12 +3,8 @@ 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'; @@ -71,16 +67,6 @@ class WeightScreen extends StatelessWidget { }; } - /// 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 () { -- 2.49.1 From 2294d11ee79bf929dfbb36d8ab51e39cc84c237a Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Thu, 11 Jul 2024 18:09:42 +0300 Subject: [PATCH 041/110] feature(registration): fix analyzer 2 --- .../language_select_screen.dart | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/lib/presentation/registration/language_select_screen/language_select_screen.dart b/lib/presentation/registration/language_select_screen/language_select_screen.dart index 6cac92e..f2ac257 100644 --- a/lib/presentation/registration/language_select_screen/language_select_screen.dart +++ b/lib/presentation/registration/language_select_screen/language_select_screen.dart @@ -1,6 +1,3 @@ -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'; @@ -78,15 +75,15 @@ class LanguageSelectScreen extends StatelessWidget { ); } - void Function()? _saveAndPush(LanguageSelectState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.languageSelectModelObj!.userRegistrationSheet; - GoRouter.of(context).goNamed( - 'credentialsScreen', - extra: sheet, - ); - }; - } + // 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)); -- 2.49.1 From c4fd047d60266540234549b4d22d535e6852909c Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Thu, 11 Jul 2024 18:28:02 +0300 Subject: [PATCH 042/110] feature(registration): temp remove test --- test/add_info_test.dart | 54 ----------------------- test/allergies_test.dart | 54 ----------------------- test/auth_test.dart | 41 ----------------- test/blood_pressure_test.dart | 54 ----------------------- test/body_circumferences_test.dart | 54 ----------------------- test/city_of_living_test.dart | 54 ----------------------- test/credentials_test.dart | 54 ----------------------- test/date_of_birth_test.dart | 54 ----------------------- test/diary_test.dart | 71 ------------------------------ test/favorite_foods_test.dart | 54 ----------------------- test/favorite_sports_test.dart | 55 ----------------------- test/gender_test.dart | 55 ----------------------- test/height_test.dart | 55 ----------------------- test/language_select_test.dart | 26 ----------- test/launch_test.dart | 15 ------- test/medicine_intake_test.dart | 55 ----------------------- test/name_test.dart | 55 ----------------------- test/profile_test.dart | 26 ----------- test/settings_test.dart | 26 ----------- test/weight_test.dart | 55 ----------------------- 20 files changed, 967 deletions(-) delete mode 100644 test/add_info_test.dart delete mode 100644 test/allergies_test.dart delete mode 100644 test/auth_test.dart delete mode 100644 test/blood_pressure_test.dart delete mode 100644 test/body_circumferences_test.dart delete mode 100644 test/city_of_living_test.dart delete mode 100644 test/credentials_test.dart delete mode 100644 test/date_of_birth_test.dart delete mode 100644 test/diary_test.dart delete mode 100644 test/favorite_foods_test.dart delete mode 100644 test/favorite_sports_test.dart delete mode 100644 test/gender_test.dart delete mode 100644 test/height_test.dart delete mode 100644 test/language_select_test.dart delete mode 100644 test/launch_test.dart delete mode 100644 test/medicine_intake_test.dart delete mode 100644 test/name_test.dart delete mode 100644 test/profile_test.dart delete mode 100644 test/settings_test.dart delete mode 100644 test/weight_test.dart diff --git a/test/add_info_test.dart b/test/add_info_test.dart deleted file mode 100644 index 86379dd..0000000 --- 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 d0a7832..0000000 --- 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/auth_test.dart b/test/auth_test.dart deleted file mode 100644 index e131dc8..0000000 --- a/test/auth_test.dart +++ /dev/null @@ -1,41 +0,0 @@ -import 'package:eatvio_app/core/app_export.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; -import 'package:eatvio_app/presentation/auth/auth_screen/auth_screen.dart'; -import 'package:eatvio_app/presentation/auth/auth_screen/bloc/auth_bloc.dart'; -import 'package:eatvio_app/presentation/auth/auth_screen/models/auth_model.dart'; - -void main() { - group('AuthScreen', () { - testWidgets('renders AuthScreen with initial state', - (WidgetTester tester) async { - final authBloc = AuthBloc(AuthState(authModelObj: AuthModel())); - - await tester.pumpWidget( - MaterialApp( - localizationsDelegates: [ - AppLocalizationDelegate(), - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - supportedLocales: [ - Locale( - 'ru', - '', - ), - ], - home: BlocProvider( - create: (context) => authBloc, - child: Builder( - builder: (context) { - return AuthScreen(); - }, - ), - ), - ), - ); - }); - }); -} diff --git a/test/blood_pressure_test.dart b/test/blood_pressure_test.dart deleted file mode 100644 index a8c70db..0000000 --- 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 339c3b8..0000000 --- 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 1a6c18b..0000000 --- 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 a82cd41..0000000 --- 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 8ce0a1f..0000000 --- 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 56d1c58..0000000 --- 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 6364726..0000000 --- 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 1c7311e..0000000 --- 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 94ab621..0000000 --- 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 cd512ed..0000000 --- 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 15582cf..0000000 --- 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 4f1eafe..0000000 --- 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 eae83c1..0000000 --- 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 1e271cb..0000000 --- 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 cf0ebc4..0000000 --- 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 c605878..0000000 --- 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 e5f9fe0..0000000 --- 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 -- 2.49.1 From b9ea8afd4ee60ad38c3aeb76f812d7e6cb879c21 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Thu, 11 Jul 2024 18:30:21 +0300 Subject: [PATCH 043/110] Revert "feature(registration): temp remove test" This reverts commit c4fd047d60266540234549b4d22d535e6852909c. --- test/add_info_test.dart | 54 +++++++++++++++++++++++ test/allergies_test.dart | 54 +++++++++++++++++++++++ test/auth_test.dart | 41 +++++++++++++++++ test/blood_pressure_test.dart | 54 +++++++++++++++++++++++ test/body_circumferences_test.dart | 54 +++++++++++++++++++++++ test/city_of_living_test.dart | 54 +++++++++++++++++++++++ test/credentials_test.dart | 54 +++++++++++++++++++++++ test/date_of_birth_test.dart | 54 +++++++++++++++++++++++ test/diary_test.dart | 71 ++++++++++++++++++++++++++++++ test/favorite_foods_test.dart | 54 +++++++++++++++++++++++ test/favorite_sports_test.dart | 55 +++++++++++++++++++++++ test/gender_test.dart | 55 +++++++++++++++++++++++ test/height_test.dart | 55 +++++++++++++++++++++++ test/language_select_test.dart | 26 +++++++++++ test/launch_test.dart | 15 +++++++ test/medicine_intake_test.dart | 55 +++++++++++++++++++++++ test/name_test.dart | 55 +++++++++++++++++++++++ test/profile_test.dart | 26 +++++++++++ test/settings_test.dart | 26 +++++++++++ test/weight_test.dart | 55 +++++++++++++++++++++++ 20 files changed, 967 insertions(+) create mode 100644 test/add_info_test.dart create mode 100644 test/allergies_test.dart create mode 100644 test/auth_test.dart create mode 100644 test/blood_pressure_test.dart create mode 100644 test/body_circumferences_test.dart create mode 100644 test/city_of_living_test.dart create mode 100644 test/credentials_test.dart create mode 100644 test/date_of_birth_test.dart create mode 100644 test/diary_test.dart create mode 100644 test/favorite_foods_test.dart create mode 100644 test/favorite_sports_test.dart create mode 100644 test/gender_test.dart create mode 100644 test/height_test.dart create mode 100644 test/language_select_test.dart create mode 100644 test/launch_test.dart create mode 100644 test/medicine_intake_test.dart create mode 100644 test/name_test.dart create mode 100644 test/profile_test.dart create mode 100644 test/settings_test.dart create mode 100644 test/weight_test.dart diff --git a/test/add_info_test.dart b/test/add_info_test.dart new file mode 100644 index 0000000..86379dd --- /dev/null +++ b/test/add_info_test.dart @@ -0,0 +1,54 @@ +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 new file mode 100644 index 0000000..d0a7832 --- /dev/null +++ b/test/allergies_test.dart @@ -0,0 +1,54 @@ +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/auth_test.dart b/test/auth_test.dart new file mode 100644 index 0000000..e131dc8 --- /dev/null +++ b/test/auth_test.dart @@ -0,0 +1,41 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:eatvio_app/presentation/auth/auth_screen/auth_screen.dart'; +import 'package:eatvio_app/presentation/auth/auth_screen/bloc/auth_bloc.dart'; +import 'package:eatvio_app/presentation/auth/auth_screen/models/auth_model.dart'; + +void main() { + group('AuthScreen', () { + testWidgets('renders AuthScreen with initial state', + (WidgetTester tester) async { + final authBloc = AuthBloc(AuthState(authModelObj: AuthModel())); + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: [ + AppLocalizationDelegate(), + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: [ + Locale( + 'ru', + '', + ), + ], + home: BlocProvider( + create: (context) => authBloc, + child: Builder( + builder: (context) { + return AuthScreen(); + }, + ), + ), + ), + ); + }); + }); +} diff --git a/test/blood_pressure_test.dart b/test/blood_pressure_test.dart new file mode 100644 index 0000000..a8c70db --- /dev/null +++ b/test/blood_pressure_test.dart @@ -0,0 +1,54 @@ +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 new file mode 100644 index 0000000..339c3b8 --- /dev/null +++ b/test/body_circumferences_test.dart @@ -0,0 +1,54 @@ +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 new file mode 100644 index 0000000..1a6c18b --- /dev/null +++ b/test/city_of_living_test.dart @@ -0,0 +1,54 @@ +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 new file mode 100644 index 0000000..a82cd41 --- /dev/null +++ b/test/credentials_test.dart @@ -0,0 +1,54 @@ +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 new file mode 100644 index 0000000..8ce0a1f --- /dev/null +++ b/test/date_of_birth_test.dart @@ -0,0 +1,54 @@ +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 new file mode 100644 index 0000000..56d1c58 --- /dev/null +++ b/test/diary_test.dart @@ -0,0 +1,71 @@ +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 new file mode 100644 index 0000000..6364726 --- /dev/null +++ b/test/favorite_foods_test.dart @@ -0,0 +1,54 @@ +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 new file mode 100644 index 0000000..1c7311e --- /dev/null +++ b/test/favorite_sports_test.dart @@ -0,0 +1,55 @@ +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 new file mode 100644 index 0000000..94ab621 --- /dev/null +++ b/test/gender_test.dart @@ -0,0 +1,55 @@ +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 new file mode 100644 index 0000000..cd512ed --- /dev/null +++ b/test/height_test.dart @@ -0,0 +1,55 @@ +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 new file mode 100644 index 0000000..15582cf --- /dev/null +++ b/test/language_select_test.dart @@ -0,0 +1,26 @@ +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 new file mode 100644 index 0000000..4f1eafe --- /dev/null +++ b/test/launch_test.dart @@ -0,0 +1,15 @@ +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 new file mode 100644 index 0000000..eae83c1 --- /dev/null +++ b/test/medicine_intake_test.dart @@ -0,0 +1,55 @@ +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 new file mode 100644 index 0000000..1e271cb --- /dev/null +++ b/test/name_test.dart @@ -0,0 +1,55 @@ +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 new file mode 100644 index 0000000..cf0ebc4 --- /dev/null +++ b/test/profile_test.dart @@ -0,0 +1,26 @@ +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 new file mode 100644 index 0000000..c605878 --- /dev/null +++ b/test/settings_test.dart @@ -0,0 +1,26 @@ +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 new file mode 100644 index 0000000..e5f9fe0 --- /dev/null +++ b/test/weight_test.dart @@ -0,0 +1,55 @@ +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 -- 2.49.1 From e3a134b73abd663eb5d02dc1875506ede614a432 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Thu, 11 Jul 2024 18:36:17 +0300 Subject: [PATCH 044/110] feature(registration): fix tests --- .../additional_information_screen.dart | 1 - test/add_info_test.dart | 2 +- test/allergies_test.dart | 2 +- test/blood_pressure_test.dart | 2 +- test/body_circumferences_test.dart | 2 +- test/city_of_living_test.dart | 2 +- test/credentials_test.dart | 2 +- test/date_of_birth_test.dart | 2 +- test/favorite_foods_test.dart | 2 +- test/favorite_sports_test.dart | 2 +- test/gender_test.dart | 2 +- test/height_test.dart | 2 +- test/language_select_test.dart | 2 +- test/medicine_intake_test.dart | 2 +- test/name_test.dart | 2 +- test/settings_test.dart | 2 +- test/weight_test.dart | 2 +- 17 files changed, 16 insertions(+), 17 deletions(-) diff --git a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart index d1c18d0..b39743e 100644 --- a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart +++ b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart @@ -82,7 +82,6 @@ class AdditionalInformationScreen extends StatelessWidget { /// Section Widget _buildTextFormField(BuildContext context) { return SizedBox( - height: 315.v, width: 343.h, child: Stack( alignment: Alignment.center, diff --git a/test/add_info_test.dart b/test/add_info_test.dart index 86379dd..9fa83f8 100644 --- a/test/add_info_test.dart +++ b/test/add_info_test.dart @@ -45,7 +45,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: AdditionalInformationScreen(), + child: Scaffold(body: AdditionalInformationScreen()), ), ), ); diff --git a/test/allergies_test.dart b/test/allergies_test.dart index d0a7832..ca8a2f2 100644 --- a/test/allergies_test.dart +++ b/test/allergies_test.dart @@ -45,7 +45,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: AllergiesScreen(), + child: Scaffold(body: AllergiesScreen()), ), ), ); diff --git a/test/blood_pressure_test.dart b/test/blood_pressure_test.dart index a8c70db..30cbb03 100644 --- a/test/blood_pressure_test.dart +++ b/test/blood_pressure_test.dart @@ -45,7 +45,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: BloodPressureScreen(), + child: Scaffold(body: BloodPressureScreen()), ), ), ); diff --git a/test/body_circumferences_test.dart b/test/body_circumferences_test.dart index 339c3b8..933c8e0 100644 --- a/test/body_circumferences_test.dart +++ b/test/body_circumferences_test.dart @@ -45,7 +45,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: BodyCircumferencesScreen(), + child: Scaffold(body: BodyCircumferencesScreen()), ), ), ); diff --git a/test/city_of_living_test.dart b/test/city_of_living_test.dart index 1a6c18b..229c6f2 100644 --- a/test/city_of_living_test.dart +++ b/test/city_of_living_test.dart @@ -45,7 +45,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: CityOfLivingScreen(), + child: Scaffold(body: CityOfLivingScreen()), ), ), ); diff --git a/test/credentials_test.dart b/test/credentials_test.dart index a82cd41..73995cc 100644 --- a/test/credentials_test.dart +++ b/test/credentials_test.dart @@ -45,7 +45,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: CredentialsScreen(), + child: Scaffold(body: CredentialsScreen()), ), ), ); diff --git a/test/date_of_birth_test.dart b/test/date_of_birth_test.dart index 8ce0a1f..e2cac1e 100644 --- a/test/date_of_birth_test.dart +++ b/test/date_of_birth_test.dart @@ -45,7 +45,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: DateOfBirthScreen(), + child: Scaffold(body: DateOfBirthScreen()), ), ), ); diff --git a/test/favorite_foods_test.dart b/test/favorite_foods_test.dart index 6364726..fa4553a 100644 --- a/test/favorite_foods_test.dart +++ b/test/favorite_foods_test.dart @@ -45,7 +45,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: FavoriteFoodsScreen(), + child: Scaffold(body: FavoriteFoodsScreen()), ), ), ); diff --git a/test/favorite_sports_test.dart b/test/favorite_sports_test.dart index 1c7311e..4b6f672 100644 --- a/test/favorite_sports_test.dart +++ b/test/favorite_sports_test.dart @@ -45,7 +45,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: FavoriteSportsScreen(), + child: Scaffold(body: FavoriteSportsScreen()), ), ), ); diff --git a/test/gender_test.dart b/test/gender_test.dart index 94ab621..45466f4 100644 --- a/test/gender_test.dart +++ b/test/gender_test.dart @@ -45,7 +45,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: GenderScreen(), + child: Scaffold(body: GenderScreen()), ), ), ); diff --git a/test/height_test.dart b/test/height_test.dart index cd512ed..34eaec4 100644 --- a/test/height_test.dart +++ b/test/height_test.dart @@ -45,7 +45,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: HeightScreen(), + child: Scaffold(body: HeightScreen()), ), ), ); diff --git a/test/language_select_test.dart b/test/language_select_test.dart index 15582cf..d667404 100644 --- a/test/language_select_test.dart +++ b/test/language_select_test.dart @@ -16,7 +16,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: LanguageSelectScreen(), + child: Scaffold(body: LanguageSelectScreen()), ), ), ); diff --git a/test/medicine_intake_test.dart b/test/medicine_intake_test.dart index eae83c1..510b7e8 100644 --- a/test/medicine_intake_test.dart +++ b/test/medicine_intake_test.dart @@ -45,7 +45,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: MedicineIntakeScreen(), + child: Scaffold(body: MedicineIntakeScreen()), ), ), ); diff --git a/test/name_test.dart b/test/name_test.dart index 1e271cb..f2a2517 100644 --- a/test/name_test.dart +++ b/test/name_test.dart @@ -45,7 +45,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: NameScreen(), + child: Scaffold(body: NameScreen()), ), ), ); diff --git a/test/settings_test.dart b/test/settings_test.dart index c605878..4e5021a 100644 --- a/test/settings_test.dart +++ b/test/settings_test.dart @@ -17,7 +17,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: MySettingsScreen(), + child: Scaffold(body: MySettingsScreen()), ), ), ); diff --git a/test/weight_test.dart b/test/weight_test.dart index e5f9fe0..fcd45c4 100644 --- a/test/weight_test.dart +++ b/test/weight_test.dart @@ -45,7 +45,7 @@ void main() { MaterialApp( home: BlocProvider.value( value: myProfileBloc, - child: WeightScreen(), + child: Scaffold(body: WeightScreen()), ), ), ); -- 2.49.1 From 551debd4502da71dfc75934426d13ee112f14936 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 12 Jul 2024 13:16:01 +0300 Subject: [PATCH 045/110] refactor(diary): API connect attempt --- lib/features/diary/models/diary,dart | 19 ++ lib/features/diary/models/diary_model.dart | 126 +------- .../diary/models/diary_model.freezed.dart | 157 +++++----- lib/features/diary/models/diary_model.g.dart | 20 +- lib/features/diary/models/meal.dart | 21 ++ lib/features/diary/models/meal.freezed.dart | 291 ++++++++++++++++++ lib/features/diary/models/meal.g.dart | 32 ++ lib/features/diary/models/photo.dart | 16 + lib/features/diary/models/photo.freezed.dart | 204 ++++++++++++ lib/features/diary/models/photo.g.dart | 22 ++ lib/features/diary/models/portion.dart | 17 + .../diary/models/portion.freezed.dart | 206 +++++++++++++ lib/features/diary/models/portion.g.dart | 23 ++ .../diary/presentation/bloc/diary_bloc.dart | 12 +- .../diary/presentation/bloc/diary_state.dart | 3 + .../bloc/diary_state.freezed.dart | 13 + .../presentation/pages/diary_screen.dart | 11 +- .../diary/repositories/diary_repository.dart | 2 +- .../diary/services/diary_service.dart | 2 +- .../diary/services/diary_service.g.dart | 29 +- test/diary_test.dart | 72 ----- 21 files changed, 999 insertions(+), 299 deletions(-) create mode 100644 lib/features/diary/models/diary,dart create mode 100644 lib/features/diary/models/meal.dart create mode 100644 lib/features/diary/models/meal.freezed.dart create mode 100644 lib/features/diary/models/meal.g.dart create mode 100644 lib/features/diary/models/photo.dart create mode 100644 lib/features/diary/models/photo.freezed.dart create mode 100644 lib/features/diary/models/photo.g.dart create mode 100644 lib/features/diary/models/portion.dart create mode 100644 lib/features/diary/models/portion.freezed.dart create mode 100644 lib/features/diary/models/portion.g.dart delete mode 100644 test/diary_test.dart diff --git a/lib/features/diary/models/diary,dart b/lib/features/diary/models/diary,dart new file mode 100644 index 0000000..f7c5935 --- /dev/null +++ b/lib/features/diary/models/diary,dart @@ -0,0 +1,19 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'diary.freezed.dart'; +part 'diary.g.dart'; + +@freezed +class Diary with _$Diary { + const factory Diary({ + required int id, + required DateTime date, + required int closed, + String? comment, + DateTime? wakeup, + DateTime? retire, + }) = _Diary; + + factory Diary.fromJson(Map json) => + _$DiaryFromJson(json); +} diff --git a/lib/features/diary/models/diary_model.dart b/lib/features/diary/models/diary_model.dart index fe7d6a2..079d483 100644 --- a/lib/features/diary/models/diary_model.dart +++ b/lib/features/diary/models/diary_model.dart @@ -1,127 +1,21 @@ import 'package:freezed_annotation/freezed_annotation.dart'; +import './meal.dart'; part 'diary_model.freezed.dart'; part 'diary_model.g.dart'; @freezed class DiaryModel with _$DiaryModel { - const factory DiaryModel( - {required int id, - required DateTime date, - required DateTime wakeup, - required DateTime retire, - required int closed, - required String comment, - required List meals}) = _DiaryModel; + const factory DiaryModel({ + required int id, + required DateTime date, + required int closed, + required List? meals, + String? comment, + DateTime? wakeup, + DateTime? retire, + }) = _DiaryModel; factory DiaryModel.fromJson(Map json) => _$DiaryModelFromJson(json); } - -class Meal { - late int id; - late String time; - late int type; - late int satiety; - late int mood; - List? portions; - List? photos; - - Meal( - {required this.id, - required this.time, - required this.type, - required this.satiety, - required this.mood, - this.portions, - this.photos}); - - Meal.fromJson(Map json) { - List portions = []; - List photos = []; - id = json['id']; - time = json['time']; - type = json['type']; - satiety = json['satiety']; - mood = json['mood']; - if (json['portions'] != null) { - json['portions'].forEach((v) { - portions.add(new Portion.fromJson(v)); - }); - } - if (json['photos'] != null) { - json['photos'].forEach((v) { - photos.add(new Photo.fromJson(v)); - }); - } - } - - Map toJson() { - final Map data = new Map(); - data['id'] = this.id; - data['time'] = this.time; - data['type'] = this.type; - data['satiety'] = this.satiety; - data['mood'] = this.mood; - if (this.portions != null) { - data['portions'] = this.portions?.map((v) => v.toJson()).toList(); - } - if (this.photos != null) { - data['photos'] = this.photos?.map((v) => v.toJson()).toList(); - } - return data; - } -} - -class Portion { - late int id; - late String productName; - late int quantity; - late String portion; - - Portion( - {required this.id, - required this.productName, - required this.quantity, - required this.portion}); - - Portion.fromJson(v); - - Map toJson() { - final Map data = new Map(); - data['id'] = this.id; - data['product_name'] = this.productName; - data['quantity'] = this.quantity; - data['portion'] = this.portion; - return data; - } -} - -class Photo { - late int id; - late String originalName; - late String path; - late int size; - - Photo( - {required this.id, - required this.originalName, - required this.path, - required this.size}); - - Photo.fromJson(Map json) { - id = json['id']; - originalName = json['original_name']; - path = json['path']; - size = json['size']; - } - - Map toJson() { - final Map data = new Map(); - data['id'] = this.id; - data['original_name'] = this.originalName; - data['path'] = this.path; - data['size'] = this.size; - return data; - } -} diff --git a/lib/features/diary/models/diary_model.freezed.dart b/lib/features/diary/models/diary_model.freezed.dart index 6705ecf..2c612ec 100644 --- a/lib/features/diary/models/diary_model.freezed.dart +++ b/lib/features/diary/models/diary_model.freezed.dart @@ -22,11 +22,11 @@ DiaryModel _$DiaryModelFromJson(Map json) { mixin _$DiaryModel { int get id => throw _privateConstructorUsedError; DateTime get date => throw _privateConstructorUsedError; - DateTime get wakeup => throw _privateConstructorUsedError; - DateTime get retire => throw _privateConstructorUsedError; int get closed => throw _privateConstructorUsedError; - String get comment => throw _privateConstructorUsedError; - List get meals => throw _privateConstructorUsedError; + List? get meals => throw _privateConstructorUsedError; + String? get comment => throw _privateConstructorUsedError; + DateTime? get wakeup => throw _privateConstructorUsedError; + DateTime? get retire => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -43,11 +43,11 @@ abstract class $DiaryModelCopyWith<$Res> { $Res call( {int id, DateTime date, - DateTime wakeup, - DateTime retire, int closed, - String comment, - List meals}); + List? meals, + String? comment, + DateTime? wakeup, + DateTime? retire}); } /// @nodoc @@ -65,11 +65,11 @@ class _$DiaryModelCopyWithImpl<$Res, $Val extends DiaryModel> $Res call({ Object? id = null, Object? date = null, - Object? wakeup = null, - Object? retire = null, Object? closed = null, - Object? comment = null, - Object? meals = null, + Object? meals = freezed, + Object? comment = freezed, + Object? wakeup = freezed, + Object? retire = freezed, }) { return _then(_value.copyWith( id: null == id @@ -80,26 +80,26 @@ class _$DiaryModelCopyWithImpl<$Res, $Val extends DiaryModel> ? _value.date : date // ignore: cast_nullable_to_non_nullable as DateTime, - wakeup: null == wakeup - ? _value.wakeup - : wakeup // ignore: cast_nullable_to_non_nullable - as DateTime, - retire: null == retire - ? _value.retire - : retire // ignore: cast_nullable_to_non_nullable - as DateTime, closed: null == closed ? _value.closed : closed // ignore: cast_nullable_to_non_nullable as int, - comment: null == comment - ? _value.comment - : comment // ignore: cast_nullable_to_non_nullable - as String, - meals: null == meals + meals: freezed == meals ? _value.meals : meals // ignore: cast_nullable_to_non_nullable - as List, + as List?, + comment: freezed == comment + ? _value.comment + : comment // ignore: cast_nullable_to_non_nullable + as String?, + wakeup: freezed == wakeup + ? _value.wakeup + : wakeup // ignore: cast_nullable_to_non_nullable + as DateTime?, + retire: freezed == retire + ? _value.retire + : retire // ignore: cast_nullable_to_non_nullable + as DateTime?, ) as $Val); } } @@ -115,11 +115,11 @@ abstract class _$$DiaryModelImplCopyWith<$Res> $Res call( {int id, DateTime date, - DateTime wakeup, - DateTime retire, int closed, - String comment, - List meals}); + List? meals, + String? comment, + DateTime? wakeup, + DateTime? retire}); } /// @nodoc @@ -135,11 +135,11 @@ class __$$DiaryModelImplCopyWithImpl<$Res> $Res call({ Object? id = null, Object? date = null, - Object? wakeup = null, - Object? retire = null, Object? closed = null, - Object? comment = null, - Object? meals = null, + Object? meals = freezed, + Object? comment = freezed, + Object? wakeup = freezed, + Object? retire = freezed, }) { return _then(_$DiaryModelImpl( id: null == id @@ -150,26 +150,26 @@ class __$$DiaryModelImplCopyWithImpl<$Res> ? _value.date : date // ignore: cast_nullable_to_non_nullable as DateTime, - wakeup: null == wakeup - ? _value.wakeup - : wakeup // ignore: cast_nullable_to_non_nullable - as DateTime, - retire: null == retire - ? _value.retire - : retire // ignore: cast_nullable_to_non_nullable - as DateTime, closed: null == closed ? _value.closed : closed // ignore: cast_nullable_to_non_nullable as int, - comment: null == comment - ? _value.comment - : comment // ignore: cast_nullable_to_non_nullable - as String, - meals: null == meals + meals: freezed == meals ? _value._meals : meals // ignore: cast_nullable_to_non_nullable - as List, + as List?, + comment: freezed == comment + ? _value.comment + : comment // ignore: cast_nullable_to_non_nullable + as String?, + wakeup: freezed == wakeup + ? _value.wakeup + : wakeup // ignore: cast_nullable_to_non_nullable + as DateTime?, + retire: freezed == retire + ? _value.retire + : retire // ignore: cast_nullable_to_non_nullable + as DateTime?, )); } } @@ -180,11 +180,11 @@ class _$DiaryModelImpl implements _DiaryModel { const _$DiaryModelImpl( {required this.id, required this.date, - required this.wakeup, - required this.retire, required this.closed, - required this.comment, - required final List meals}) + required final List? meals, + this.comment, + this.wakeup, + this.retire}) : _meals = meals; factory _$DiaryModelImpl.fromJson(Map json) => @@ -195,24 +195,27 @@ class _$DiaryModelImpl implements _DiaryModel { @override final DateTime date; @override - final DateTime wakeup; - @override - final DateTime retire; - @override final int closed; + final List? _meals; @override - final String comment; - final List _meals; - @override - List get meals { + List? get meals { + final value = _meals; + if (value == null) return null; if (_meals is EqualUnmodifiableListView) return _meals; // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_meals); + return EqualUnmodifiableListView(value); } + @override + final String? comment; + @override + final DateTime? wakeup; + @override + final DateTime? retire; + @override String toString() { - return 'DiaryModel(id: $id, date: $date, wakeup: $wakeup, retire: $retire, closed: $closed, comment: $comment, meals: $meals)'; + return 'DiaryModel(id: $id, date: $date, closed: $closed, meals: $meals, comment: $comment, wakeup: $wakeup, retire: $retire)'; } @override @@ -222,17 +225,17 @@ class _$DiaryModelImpl implements _DiaryModel { other is _$DiaryModelImpl && (identical(other.id, id) || other.id == id) && (identical(other.date, date) || other.date == date) && - (identical(other.wakeup, wakeup) || other.wakeup == wakeup) && - (identical(other.retire, retire) || other.retire == retire) && (identical(other.closed, closed) || other.closed == closed) && + const DeepCollectionEquality().equals(other._meals, _meals) && (identical(other.comment, comment) || other.comment == comment) && - const DeepCollectionEquality().equals(other._meals, _meals)); + (identical(other.wakeup, wakeup) || other.wakeup == wakeup) && + (identical(other.retire, retire) || other.retire == retire)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, date, wakeup, retire, closed, - comment, const DeepCollectionEquality().hash(_meals)); + int get hashCode => Object.hash(runtimeType, id, date, closed, + const DeepCollectionEquality().hash(_meals), comment, wakeup, retire); @JsonKey(ignore: true) @override @@ -252,11 +255,11 @@ abstract class _DiaryModel implements DiaryModel { const factory _DiaryModel( {required final int id, required final DateTime date, - required final DateTime wakeup, - required final DateTime retire, required final int closed, - required final String comment, - required final List meals}) = _$DiaryModelImpl; + required final List? meals, + final String? comment, + final DateTime? wakeup, + final DateTime? retire}) = _$DiaryModelImpl; factory _DiaryModel.fromJson(Map json) = _$DiaryModelImpl.fromJson; @@ -266,15 +269,15 @@ abstract class _DiaryModel implements DiaryModel { @override DateTime get date; @override - DateTime get wakeup; - @override - DateTime get retire; - @override int get closed; @override - String get comment; + List? get meals; @override - List get meals; + String? get comment; + @override + DateTime? get wakeup; + @override + DateTime? get retire; @override @JsonKey(ignore: true) _$$DiaryModelImplCopyWith<_$DiaryModelImpl> get copyWith => diff --git a/lib/features/diary/models/diary_model.g.dart b/lib/features/diary/models/diary_model.g.dart index 9fabca8..fc9f7d0 100644 --- a/lib/features/diary/models/diary_model.g.dart +++ b/lib/features/diary/models/diary_model.g.dart @@ -10,22 +10,26 @@ _$DiaryModelImpl _$$DiaryModelImplFromJson(Map json) => _$DiaryModelImpl( id: (json['id'] as num).toInt(), date: DateTime.parse(json['date'] as String), - wakeup: DateTime.parse(json['wakeup'] as String), - retire: DateTime.parse(json['retire'] as String), closed: (json['closed'] as num).toInt(), - comment: json['comment'] as String, - meals: (json['meals'] as List) - .map((e) => Meal.fromJson(e as Map)) + meals: (json['meals'] as List?) + ?.map((e) => Meal.fromJson(e as Map)) .toList(), + comment: json['comment'] as String?, + wakeup: json['wakeup'] == null + ? null + : DateTime.parse(json['wakeup'] as String), + retire: json['retire'] == null + ? null + : DateTime.parse(json['retire'] as String), ); Map _$$DiaryModelImplToJson(_$DiaryModelImpl instance) => { 'id': instance.id, 'date': instance.date.toIso8601String(), - 'wakeup': instance.wakeup.toIso8601String(), - 'retire': instance.retire.toIso8601String(), 'closed': instance.closed, - 'comment': instance.comment, 'meals': instance.meals, + 'comment': instance.comment, + 'wakeup': instance.wakeup?.toIso8601String(), + 'retire': instance.retire?.toIso8601String(), }; diff --git a/lib/features/diary/models/meal.dart b/lib/features/diary/models/meal.dart new file mode 100644 index 0000000..a268a47 --- /dev/null +++ b/lib/features/diary/models/meal.dart @@ -0,0 +1,21 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +import './portion.dart'; +import './photo.dart'; + +part 'meal.freezed.dart'; +part 'meal.g.dart'; + +@freezed +class Meal with _$Meal { + const factory Meal({ + required int id, + required String time, + required int type, + required int satiety, + required int mood, + required List portions, + required List photos, + }) = _Meal; + + factory Meal.fromJson(Map json) => _$MealFromJson(json); +} diff --git a/lib/features/diary/models/meal.freezed.dart b/lib/features/diary/models/meal.freezed.dart new file mode 100644 index 0000000..2c249b0 --- /dev/null +++ b/lib/features/diary/models/meal.freezed.dart @@ -0,0 +1,291 @@ +// 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 'meal.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'); + +Meal _$MealFromJson(Map json) { + return _Meal.fromJson(json); +} + +/// @nodoc +mixin _$Meal { + int get id => throw _privateConstructorUsedError; + String get time => throw _privateConstructorUsedError; + int get type => throw _privateConstructorUsedError; + int get satiety => throw _privateConstructorUsedError; + int get mood => throw _privateConstructorUsedError; + List get portions => throw _privateConstructorUsedError; + List get photos => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $MealCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $MealCopyWith<$Res> { + factory $MealCopyWith(Meal value, $Res Function(Meal) then) = + _$MealCopyWithImpl<$Res, Meal>; + @useResult + $Res call( + {int id, + String time, + int type, + int satiety, + int mood, + List portions, + List photos}); +} + +/// @nodoc +class _$MealCopyWithImpl<$Res, $Val extends Meal> + implements $MealCopyWith<$Res> { + _$MealCopyWithImpl(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 = null, + Object? time = null, + Object? type = null, + Object? satiety = null, + Object? mood = null, + Object? portions = null, + Object? photos = null, + }) { + return _then(_value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + time: null == time + ? _value.time + : time // ignore: cast_nullable_to_non_nullable + as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as int, + satiety: null == satiety + ? _value.satiety + : satiety // ignore: cast_nullable_to_non_nullable + as int, + mood: null == mood + ? _value.mood + : mood // ignore: cast_nullable_to_non_nullable + as int, + portions: null == portions + ? _value.portions + : portions // ignore: cast_nullable_to_non_nullable + as List, + photos: null == photos + ? _value.photos + : photos // ignore: cast_nullable_to_non_nullable + as List, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$MealImplCopyWith<$Res> implements $MealCopyWith<$Res> { + factory _$$MealImplCopyWith( + _$MealImpl value, $Res Function(_$MealImpl) then) = + __$$MealImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {int id, + String time, + int type, + int satiety, + int mood, + List portions, + List photos}); +} + +/// @nodoc +class __$$MealImplCopyWithImpl<$Res> + extends _$MealCopyWithImpl<$Res, _$MealImpl> + implements _$$MealImplCopyWith<$Res> { + __$$MealImplCopyWithImpl(_$MealImpl _value, $Res Function(_$MealImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? time = null, + Object? type = null, + Object? satiety = null, + Object? mood = null, + Object? portions = null, + Object? photos = null, + }) { + return _then(_$MealImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + time: null == time + ? _value.time + : time // ignore: cast_nullable_to_non_nullable + as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as int, + satiety: null == satiety + ? _value.satiety + : satiety // ignore: cast_nullable_to_non_nullable + as int, + mood: null == mood + ? _value.mood + : mood // ignore: cast_nullable_to_non_nullable + as int, + portions: null == portions + ? _value._portions + : portions // ignore: cast_nullable_to_non_nullable + as List, + photos: null == photos + ? _value._photos + : photos // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$MealImpl implements _Meal { + const _$MealImpl( + {required this.id, + required this.time, + required this.type, + required this.satiety, + required this.mood, + required final List portions, + required final List photos}) + : _portions = portions, + _photos = photos; + + factory _$MealImpl.fromJson(Map json) => + _$$MealImplFromJson(json); + + @override + final int id; + @override + final String time; + @override + final int type; + @override + final int satiety; + @override + final int mood; + final List _portions; + @override + List get portions { + if (_portions is EqualUnmodifiableListView) return _portions; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_portions); + } + + final List _photos; + @override + List get photos { + if (_photos is EqualUnmodifiableListView) return _photos; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_photos); + } + + @override + String toString() { + return 'Meal(id: $id, time: $time, type: $type, satiety: $satiety, mood: $mood, portions: $portions, photos: $photos)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$MealImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.time, time) || other.time == time) && + (identical(other.type, type) || other.type == type) && + (identical(other.satiety, satiety) || other.satiety == satiety) && + (identical(other.mood, mood) || other.mood == mood) && + const DeepCollectionEquality().equals(other._portions, _portions) && + const DeepCollectionEquality().equals(other._photos, _photos)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, + id, + time, + type, + satiety, + mood, + const DeepCollectionEquality().hash(_portions), + const DeepCollectionEquality().hash(_photos)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$MealImplCopyWith<_$MealImpl> get copyWith => + __$$MealImplCopyWithImpl<_$MealImpl>(this, _$identity); + + @override + Map toJson() { + return _$$MealImplToJson( + this, + ); + } +} + +abstract class _Meal implements Meal { + const factory _Meal( + {required final int id, + required final String time, + required final int type, + required final int satiety, + required final int mood, + required final List portions, + required final List photos}) = _$MealImpl; + + factory _Meal.fromJson(Map json) = _$MealImpl.fromJson; + + @override + int get id; + @override + String get time; + @override + int get type; + @override + int get satiety; + @override + int get mood; + @override + List get portions; + @override + List get photos; + @override + @JsonKey(ignore: true) + _$$MealImplCopyWith<_$MealImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/diary/models/meal.g.dart b/lib/features/diary/models/meal.g.dart new file mode 100644 index 0000000..5536ed9 --- /dev/null +++ b/lib/features/diary/models/meal.g.dart @@ -0,0 +1,32 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'meal.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$MealImpl _$$MealImplFromJson(Map json) => _$MealImpl( + id: (json['id'] as num).toInt(), + time: json['time'] as String, + type: (json['type'] as num).toInt(), + satiety: (json['satiety'] as num).toInt(), + mood: (json['mood'] as num).toInt(), + portions: (json['portions'] as List) + .map((e) => Portion.fromJson(e as Map)) + .toList(), + photos: (json['photos'] as List) + .map((e) => Photo.fromJson(e as Map)) + .toList(), + ); + +Map _$$MealImplToJson(_$MealImpl instance) => + { + 'id': instance.id, + 'time': instance.time, + 'type': instance.type, + 'satiety': instance.satiety, + 'mood': instance.mood, + 'portions': instance.portions, + 'photos': instance.photos, + }; diff --git a/lib/features/diary/models/photo.dart b/lib/features/diary/models/photo.dart new file mode 100644 index 0000000..f057ec5 --- /dev/null +++ b/lib/features/diary/models/photo.dart @@ -0,0 +1,16 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'photo.freezed.dart'; +part 'photo.g.dart'; + +@freezed +class Photo with _$Photo { + const factory Photo({ + required int id, + required String originalName, + required String path, + required int size, + }) = _Photo; + + factory Photo.fromJson(Map json) => _$PhotoFromJson(json); +} diff --git a/lib/features/diary/models/photo.freezed.dart b/lib/features/diary/models/photo.freezed.dart new file mode 100644 index 0000000..6b4520b --- /dev/null +++ b/lib/features/diary/models/photo.freezed.dart @@ -0,0 +1,204 @@ +// 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 'photo.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'); + +Photo _$PhotoFromJson(Map json) { + return _Photo.fromJson(json); +} + +/// @nodoc +mixin _$Photo { + int get id => throw _privateConstructorUsedError; + String get originalName => throw _privateConstructorUsedError; + String get path => throw _privateConstructorUsedError; + int get size => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $PhotoCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $PhotoCopyWith<$Res> { + factory $PhotoCopyWith(Photo value, $Res Function(Photo) then) = + _$PhotoCopyWithImpl<$Res, Photo>; + @useResult + $Res call({int id, String originalName, String path, int size}); +} + +/// @nodoc +class _$PhotoCopyWithImpl<$Res, $Val extends Photo> + implements $PhotoCopyWith<$Res> { + _$PhotoCopyWithImpl(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 = null, + Object? originalName = null, + Object? path = null, + Object? size = null, + }) { + return _then(_value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + originalName: null == originalName + ? _value.originalName + : originalName // ignore: cast_nullable_to_non_nullable + as String, + path: null == path + ? _value.path + : path // ignore: cast_nullable_to_non_nullable + as String, + size: null == size + ? _value.size + : size // ignore: cast_nullable_to_non_nullable + as int, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$PhotoImplCopyWith<$Res> implements $PhotoCopyWith<$Res> { + factory _$$PhotoImplCopyWith( + _$PhotoImpl value, $Res Function(_$PhotoImpl) then) = + __$$PhotoImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({int id, String originalName, String path, int size}); +} + +/// @nodoc +class __$$PhotoImplCopyWithImpl<$Res> + extends _$PhotoCopyWithImpl<$Res, _$PhotoImpl> + implements _$$PhotoImplCopyWith<$Res> { + __$$PhotoImplCopyWithImpl( + _$PhotoImpl _value, $Res Function(_$PhotoImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? originalName = null, + Object? path = null, + Object? size = null, + }) { + return _then(_$PhotoImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + originalName: null == originalName + ? _value.originalName + : originalName // ignore: cast_nullable_to_non_nullable + as String, + path: null == path + ? _value.path + : path // ignore: cast_nullable_to_non_nullable + as String, + size: null == size + ? _value.size + : size // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$PhotoImpl implements _Photo { + const _$PhotoImpl( + {required this.id, + required this.originalName, + required this.path, + required this.size}); + + factory _$PhotoImpl.fromJson(Map json) => + _$$PhotoImplFromJson(json); + + @override + final int id; + @override + final String originalName; + @override + final String path; + @override + final int size; + + @override + String toString() { + return 'Photo(id: $id, originalName: $originalName, path: $path, size: $size)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$PhotoImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.originalName, originalName) || + other.originalName == originalName) && + (identical(other.path, path) || other.path == path) && + (identical(other.size, size) || other.size == size)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, id, originalName, path, size); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$PhotoImplCopyWith<_$PhotoImpl> get copyWith => + __$$PhotoImplCopyWithImpl<_$PhotoImpl>(this, _$identity); + + @override + Map toJson() { + return _$$PhotoImplToJson( + this, + ); + } +} + +abstract class _Photo implements Photo { + const factory _Photo( + {required final int id, + required final String originalName, + required final String path, + required final int size}) = _$PhotoImpl; + + factory _Photo.fromJson(Map json) = _$PhotoImpl.fromJson; + + @override + int get id; + @override + String get originalName; + @override + String get path; + @override + int get size; + @override + @JsonKey(ignore: true) + _$$PhotoImplCopyWith<_$PhotoImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/diary/models/photo.g.dart b/lib/features/diary/models/photo.g.dart new file mode 100644 index 0000000..9b212a8 --- /dev/null +++ b/lib/features/diary/models/photo.g.dart @@ -0,0 +1,22 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'photo.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$PhotoImpl _$$PhotoImplFromJson(Map json) => _$PhotoImpl( + id: (json['id'] as num).toInt(), + originalName: json['originalName'] as String, + path: json['path'] as String, + size: (json['size'] as num).toInt(), + ); + +Map _$$PhotoImplToJson(_$PhotoImpl instance) => + { + 'id': instance.id, + 'originalName': instance.originalName, + 'path': instance.path, + 'size': instance.size, + }; diff --git a/lib/features/diary/models/portion.dart b/lib/features/diary/models/portion.dart new file mode 100644 index 0000000..9712d9b --- /dev/null +++ b/lib/features/diary/models/portion.dart @@ -0,0 +1,17 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'portion.freezed.dart'; +part 'portion.g.dart'; + +@freezed +class Portion with _$Portion { + const factory Portion({ + required int id, + required String productName, + required int quantity, + required String portion, + }) = _Portion; + + factory Portion.fromJson(Map json) => + _$PortionFromJson(json); +} diff --git a/lib/features/diary/models/portion.freezed.dart b/lib/features/diary/models/portion.freezed.dart new file mode 100644 index 0000000..ab79213 --- /dev/null +++ b/lib/features/diary/models/portion.freezed.dart @@ -0,0 +1,206 @@ +// 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 'portion.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'); + +Portion _$PortionFromJson(Map json) { + return _Portion.fromJson(json); +} + +/// @nodoc +mixin _$Portion { + int get id => throw _privateConstructorUsedError; + String get productName => throw _privateConstructorUsedError; + int get quantity => throw _privateConstructorUsedError; + String get portion => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $PortionCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $PortionCopyWith<$Res> { + factory $PortionCopyWith(Portion value, $Res Function(Portion) then) = + _$PortionCopyWithImpl<$Res, Portion>; + @useResult + $Res call({int id, String productName, int quantity, String portion}); +} + +/// @nodoc +class _$PortionCopyWithImpl<$Res, $Val extends Portion> + implements $PortionCopyWith<$Res> { + _$PortionCopyWithImpl(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 = null, + Object? productName = null, + Object? quantity = null, + Object? portion = null, + }) { + return _then(_value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + productName: null == productName + ? _value.productName + : productName // ignore: cast_nullable_to_non_nullable + as String, + quantity: null == quantity + ? _value.quantity + : quantity // ignore: cast_nullable_to_non_nullable + as int, + portion: null == portion + ? _value.portion + : portion // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$PortionImplCopyWith<$Res> implements $PortionCopyWith<$Res> { + factory _$$PortionImplCopyWith( + _$PortionImpl value, $Res Function(_$PortionImpl) then) = + __$$PortionImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({int id, String productName, int quantity, String portion}); +} + +/// @nodoc +class __$$PortionImplCopyWithImpl<$Res> + extends _$PortionCopyWithImpl<$Res, _$PortionImpl> + implements _$$PortionImplCopyWith<$Res> { + __$$PortionImplCopyWithImpl( + _$PortionImpl _value, $Res Function(_$PortionImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? productName = null, + Object? quantity = null, + Object? portion = null, + }) { + return _then(_$PortionImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + productName: null == productName + ? _value.productName + : productName // ignore: cast_nullable_to_non_nullable + as String, + quantity: null == quantity + ? _value.quantity + : quantity // ignore: cast_nullable_to_non_nullable + as int, + portion: null == portion + ? _value.portion + : portion // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$PortionImpl implements _Portion { + const _$PortionImpl( + {required this.id, + required this.productName, + required this.quantity, + required this.portion}); + + factory _$PortionImpl.fromJson(Map json) => + _$$PortionImplFromJson(json); + + @override + final int id; + @override + final String productName; + @override + final int quantity; + @override + final String portion; + + @override + String toString() { + return 'Portion(id: $id, productName: $productName, quantity: $quantity, portion: $portion)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$PortionImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.productName, productName) || + other.productName == productName) && + (identical(other.quantity, quantity) || + other.quantity == quantity) && + (identical(other.portion, portion) || other.portion == portion)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => + Object.hash(runtimeType, id, productName, quantity, portion); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$PortionImplCopyWith<_$PortionImpl> get copyWith => + __$$PortionImplCopyWithImpl<_$PortionImpl>(this, _$identity); + + @override + Map toJson() { + return _$$PortionImplToJson( + this, + ); + } +} + +abstract class _Portion implements Portion { + const factory _Portion( + {required final int id, + required final String productName, + required final int quantity, + required final String portion}) = _$PortionImpl; + + factory _Portion.fromJson(Map json) = _$PortionImpl.fromJson; + + @override + int get id; + @override + String get productName; + @override + int get quantity; + @override + String get portion; + @override + @JsonKey(ignore: true) + _$$PortionImplCopyWith<_$PortionImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/diary/models/portion.g.dart b/lib/features/diary/models/portion.g.dart new file mode 100644 index 0000000..aae2162 --- /dev/null +++ b/lib/features/diary/models/portion.g.dart @@ -0,0 +1,23 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'portion.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$PortionImpl _$$PortionImplFromJson(Map json) => + _$PortionImpl( + id: (json['id'] as num).toInt(), + productName: json['productName'] as String, + quantity: (json['quantity'] as num).toInt(), + portion: json['portion'] as String, + ); + +Map _$$PortionImplToJson(_$PortionImpl instance) => + { + 'id': instance.id, + 'productName': instance.productName, + 'quantity': instance.quantity, + 'portion': instance.portion, + }; diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index efc7b26..f2d0b7f 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -1,5 +1,5 @@ import 'dart:async'; -import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:eatvio_app/features/diary/models/meal.dart'; import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; import 'package:intl/intl.dart'; import 'package:equatable/equatable.dart'; @@ -53,10 +53,10 @@ class DiaryBloc extends Bloc { ) async { emit(const DiaryState.loading()); try { - final diary = - await diaryRepository.getDiary(await diaryRepository.getDiaryID()); + Map data = await diaryRepository.getDiaryID(); + final int? diaryID = data['id']; emit(DiaryState.loaded( - diary: diary, + diary: await diaryRepository.getDiary(diaryID ?? 45), commentController: TextEditingController(), productNameController: TextEditingController(), productQuantityController: TextEditingController(), @@ -359,8 +359,8 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - Meal? meal = - currentState.diary.meals.firstWhere((meal) => meal.id == event.value); + Meal? meal = currentState.diary.meals! + .firstWhere((meal) => meal.id == event.value); DiaryStateLoaded updatedState = currentState.copyWith( currentMeal: event.value, diff --git a/lib/features/diary/presentation/bloc/diary_state.dart b/lib/features/diary/presentation/bloc/diary_state.dart index d1c2c60..b9f2695 100644 --- a/lib/features/diary/presentation/bloc/diary_state.dart +++ b/lib/features/diary/presentation/bloc/diary_state.dart @@ -1,4 +1,7 @@ import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:eatvio_app/features/diary/models/meal.dart'; +import 'package:eatvio_app/features/diary/models/photo.dart'; +import 'package:eatvio_app/features/diary/models/portion.dart'; import 'package:flutter/material.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; diff --git a/lib/features/diary/presentation/bloc/diary_state.freezed.dart b/lib/features/diary/presentation/bloc/diary_state.freezed.dart index d5d614a..8a5aba4 100644 --- a/lib/features/diary/presentation/bloc/diary_state.freezed.dart +++ b/lib/features/diary/presentation/bloc/diary_state.freezed.dart @@ -592,6 +592,7 @@ abstract class _$$DiaryStateLoadedImplCopyWith<$Res> { bool isAdded}); $DiaryModelCopyWith<$Res> get diary; + $MealCopyWith<$Res>? get currentMeal; } /// @nodoc @@ -747,6 +748,18 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> return _then(_value.copyWith(diary: value)); }); } + + @override + @pragma('vm:prefer-inline') + $MealCopyWith<$Res>? get currentMeal { + if (_value.currentMeal == null) { + return null; + } + + return $MealCopyWith<$Res>(_value.currentMeal!, (value) { + return _then(_value.copyWith(currentMeal: value)); + }); + } } /// @nodoc diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index da60981..7f46d09 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -1,6 +1,9 @@ // ignore_for_file: unused_local_variable import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:eatvio_app/features/diary/models/meal.dart'; +import 'package:eatvio_app/features/diary/models/photo.dart'; +import 'package:eatvio_app/features/diary/models/portion.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/locator_service.dart'; @@ -674,12 +677,12 @@ class DiaryScreen extends StatelessWidget { } _buildCarousel(BuildContext context, DiaryStateLoaded state) { - if (state.currentMeal!.photos!.isEmpty) { + if (state.currentMeal!.photos.isEmpty) { return Text("Фото нет"); } else { return CarouselSlider( options: CarouselOptions(height: 340.0), - items: state.currentMeal!.photos!.map((photo) { + items: state.currentMeal!.photos.map((photo) { return _buildPhoto( context, photo); // Assuming photos are stored as strings }).toList(), @@ -1311,8 +1314,8 @@ bool checkConsumedValues( return false; // Возвращаем true } -List mealsToDropdown(List meals) { - return meals +List mealsToDropdown(List? meals) { + return meals! .map((meal) => SelectionPopupModel( id: meal.id, title: "Прием пищи ${meal.id}", diff --git a/lib/features/diary/repositories/diary_repository.dart b/lib/features/diary/repositories/diary_repository.dart index 440f419..2cadfd8 100644 --- a/lib/features/diary/repositories/diary_repository.dart +++ b/lib/features/diary/repositories/diary_repository.dart @@ -6,7 +6,7 @@ class DiaryRepository { DiaryRepository({required this.diaryService}); - Future getDiaryID() async { + Future> getDiaryID() async { try { return await diaryService.getDiaryID(); } catch (e) { diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart index dd27f0b..967c2af 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -10,7 +10,7 @@ abstract class DiaryService { factory DiaryService(Dio dio, {String baseUrl}) = _DiaryService; @GET('/diary/index') - Future getDiaryID(); + Future> getDiaryID(); @GET('/diary/{id}/show/') Future getDiary(@Path() int id); diff --git a/lib/features/diary/services/diary_service.g.dart b/lib/features/diary/services/diary_service.g.dart index 294e4e3..62ca8f6 100644 --- a/lib/features/diary/services/diary_service.g.dart +++ b/lib/features/diary/services/diary_service.g.dart @@ -19,28 +19,29 @@ class _DiaryService implements DiaryService { String? baseUrl; @override - Future getDiaryID() async { + Future> getDiaryID() async { final _extra = {}; final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch(_setStreamType(Options( + final _result = await _dio + .fetch>(_setStreamType>(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/diary/index', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - final _value = _result.data!; + .compose( + _dio.options, + '/diary/index', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = _result.data!.cast(); return _value; } diff --git a/test/diary_test.dart b/test/diary_test.dart deleted file mode 100644 index d506347..0000000 --- a/test/diary_test.dart +++ /dev/null @@ -1,72 +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/features/diary/presentation/bloc/diary_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 - }); -} -*/ \ No newline at end of file -- 2.49.1 From 89b94ea2a02324156955a62481fe79cee37de198 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Fri, 12 Jul 2024 14:23:53 +0300 Subject: [PATCH 046/110] feature(registration): try push --- lib/main.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/main.dart b/lib/main.dart index 7faced2..5cb4e31 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -68,7 +68,7 @@ class MyApp extends StatelessWidget { theme: theme, title: 'Eatvio', routerConfig: AppRouter.appRouter, - debugShowCheckedModeBanner: false, + debugShowCheckedModeBanner: true, localizationsDelegates: [ AppLocalizationDelegate(), GlobalMaterialLocalizations.delegate, -- 2.49.1 From ed74fd99f087142620b778a37a083cacb1613c8a Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Fri, 12 Jul 2024 14:33:18 +0300 Subject: [PATCH 047/110] refactor(diary): fix service --- .../presentation/pages/diary_screen.dart | 58 +++++++++---------- .../diary/repositories/diary_repository.dart | 2 +- .../diary/services/diary_service.dart | 2 +- .../diary/services/diary_service.g.dart | 9 +-- lib/main.dart | 23 ++------ 5 files changed, 40 insertions(+), 54 deletions(-) diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index 7f46d09..be3a7b4 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -6,7 +6,6 @@ import 'package:eatvio_app/features/diary/models/photo.dart'; import 'package:eatvio_app/features/diary/models/portion.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; -import 'package:eatvio_app/locator_service.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -26,38 +25,35 @@ import 'package:carousel_slider/carousel_slider.dart'; class DiaryScreen extends StatelessWidget { DiaryScreen({Key? key}) : super(key: key); Widget build(BuildContext context) { - return BlocProvider( - create: (context) => sl()..add(LoadDiary()), - child: BlocBuilder( - builder: (context, state) { - if (state is DiaryStateLoaded) { - return _buildDiary(context, state); - } else if (state is DiaryStateLoading) { - return Scaffold( - body: Center( - child: CupertinoActivityIndicator(), + return BlocBuilder( + builder: (context, state) { + if (state is DiaryStateLoaded) { + return _buildDiary(context, state); + } else if (state is DiaryStateLoading) { + return Scaffold( + body: Center( + child: CupertinoActivityIndicator(), + ), + ); + } else if (state is DiaryStateError) { + return Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: Center( + child: Text(state.errorMessage), ), - ); - } else if (state is DiaryStateError) { - return Scaffold( - body: Padding( - padding: const EdgeInsets.all(16), - child: Center( - child: Text(state.errorMessage), - ), + ), + ); + } else + return Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: Center( + child: Text("Неопределенная ошибка"), ), - ); - } else - return Scaffold( - body: Padding( - padding: const EdgeInsets.all(16), - child: Center( - child: Text("Неопределенная ошибка"), - ), - ), - ); - }, - ), + ), + ); + }, ); } diff --git a/lib/features/diary/repositories/diary_repository.dart b/lib/features/diary/repositories/diary_repository.dart index 2cadfd8..25903f1 100644 --- a/lib/features/diary/repositories/diary_repository.dart +++ b/lib/features/diary/repositories/diary_repository.dart @@ -16,7 +16,7 @@ class DiaryRepository { Future getDiary(int diaryID) async { try { - return await diaryService.getDiary(diaryID); + return (await diaryService.getDiary(diaryID))['diary']!; } catch (e) { rethrow; } diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart index 967c2af..e047b5e 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -13,7 +13,7 @@ abstract class DiaryService { Future> getDiaryID(); @GET('/diary/{id}/show/') - Future getDiary(@Path() int id); + Future> getDiary(@Path() int id); @GET('/diary/{id}/dailyNutritionData/') Future getChart(@Path() String id); diff --git a/lib/features/diary/services/diary_service.g.dart b/lib/features/diary/services/diary_service.g.dart index 62ca8f6..3ea7bd1 100644 --- a/lib/features/diary/services/diary_service.g.dart +++ b/lib/features/diary/services/diary_service.g.dart @@ -46,13 +46,13 @@ class _DiaryService implements DiaryService { } @override - Future getDiary(int id) async { + Future> getDiary(int id) async { final _extra = {}; final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType(Options( + final _result = await _dio.fetch>( + _setStreamType>(Options( method: 'GET', headers: _headers, extra: _extra, @@ -68,7 +68,8 @@ class _DiaryService implements DiaryService { _dio.options.baseUrl, baseUrl, )))); - final _value = DiaryModel.fromJson(_result.data!); + var _value = _result.data!.map((k, dynamic v) => + MapEntry(k, DiaryModel.fromJson(v as Map))); return _value; } diff --git a/lib/main.dart b/lib/main.dart index bd7e66c..f71b4a5 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -41,24 +41,13 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MultiBlocProvider( providers: [ - BlocProvider( - create: (context) => InitializationCubit(chatRepository: sl())), - BlocProvider( - create: (context) => - ThemeBloc(ThemeState(themeType: PrefUtils().getThemeData()))), - BlocProvider( - create: (context) => sl()..loadFeedBlogPostList()), - BlocProvider( - create: (context) => MyProfileBloc( - MyProfileState(myProfileModelObj: MyProfileModel())) - ..add(MyProfileInitialEvent())), - BlocProvider( - create: (context) => sl()..add(LoadDiary()), - ), + BlocProvider(create: (context) => InitializationCubit(chatRepository: sl())), + BlocProvider(create: (context) => ThemeBloc(ThemeState(themeType: PrefUtils().getThemeData()))), + BlocProvider(create: (context) => sl()..loadFeedBlogPostList()), + BlocProvider(create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent())), + BlocProvider(create: (context) => sl()..add(LoadDiary())), BlocProvider( - create: (context) => ChatSelectBloc( - ChatSelectState(chatSelectModelObj: ChatSelectModel())) - ..add(ChatSelectInitialEvent()), + create: (context) => ChatSelectBloc(ChatSelectState(chatSelectModelObj: ChatSelectModel()))..add(ChatSelectInitialEvent()), ), ], child: BlocListener( -- 2.49.1 From c903fa4e65d93275b61fb7dd6152945b2bcb3dea Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Fri, 12 Jul 2024 14:48:17 +0300 Subject: [PATCH 048/110] feat(registration): fix --- .DS_Store | Bin 0 -> 6148 bytes lib/main.dart | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..017f6122a1c39393f4632e375b97f19d52e245e6 GIT binary patch literal 6148 zcmeHKOHRWu5PhZ*l#dWBkk}yQ0#xD#0ksPjY~TPT{eTLARFopI%bq)M1+=PpPe`cV2f;eJOqlv88`iNQ zG7uT~Z4Ah}yMr9JOaxTGq*-A564>rwM7sxCmV65Ljrq;GIVG)jN z+rZ5+V2ml_4jE6FVPrp^?6xm(pYKwxkB3{uDS8}zm(2DU?Izr*vQ{1<;eH{5xc5f{ z*`;+3S^Y!8Gh3v+ZgtEf1CfEqzy|~JeMp%^XHHjE>!*X6UIC~RHmk5KzZ8N=oz9%D ztY#0zSSYoH8h6Do7S8t6*=0^wR$DlXyL=cI*|-~u(dhJ_syR$%b<86JkpZ89maT5d z`QKZ7|Mx+$78!^P{3`}b(mm@QaZ2uNZA?zi+LY;>Nkr@_s};h`9miUbqj;A|g?*_M Ws57T4tJy+{KLSca%pwCn%D_9st?(HD literal 0 HcmV?d00001 diff --git a/lib/main.dart b/lib/main.dart index 5cb4e31..7faced2 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -68,7 +68,7 @@ class MyApp extends StatelessWidget { theme: theme, title: 'Eatvio', routerConfig: AppRouter.appRouter, - debugShowCheckedModeBanner: true, + debugShowCheckedModeBanner: false, localizationsDelegates: [ AppLocalizationDelegate(), GlobalMaterialLocalizations.delegate, -- 2.49.1 From f3a0df20b779dee428f5848f3f6a47cc87ec2b08 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 12 Jul 2024 16:49:50 +0300 Subject: [PATCH 049/110] refactor(diary): Fix --- lib/features/diary/models/diary_model.dart | 2 +- .../diary/models/diary_model.freezed.dart | 32 ++- lib/features/diary/models/diary_model.g.dart | 4 +- .../diary/presentation/bloc/diary_bloc.dart | 33 +-- .../diary/presentation/bloc/diary_state.dart | 22 +- .../bloc/diary_state.freezed.dart | 212 +++++++++--------- .../presentation/pages/diary_screen.dart | 13 +- 7 files changed, 155 insertions(+), 163 deletions(-) diff --git a/lib/features/diary/models/diary_model.dart b/lib/features/diary/models/diary_model.dart index 079d483..3a89936 100644 --- a/lib/features/diary/models/diary_model.dart +++ b/lib/features/diary/models/diary_model.dart @@ -10,7 +10,7 @@ class DiaryModel with _$DiaryModel { required int id, required DateTime date, required int closed, - required List? meals, + required List meals, String? comment, DateTime? wakeup, DateTime? retire, diff --git a/lib/features/diary/models/diary_model.freezed.dart b/lib/features/diary/models/diary_model.freezed.dart index 2c612ec..3fe59e1 100644 --- a/lib/features/diary/models/diary_model.freezed.dart +++ b/lib/features/diary/models/diary_model.freezed.dart @@ -23,7 +23,7 @@ mixin _$DiaryModel { int get id => throw _privateConstructorUsedError; DateTime get date => throw _privateConstructorUsedError; int get closed => throw _privateConstructorUsedError; - List? get meals => throw _privateConstructorUsedError; + List get meals => throw _privateConstructorUsedError; String? get comment => throw _privateConstructorUsedError; DateTime? get wakeup => throw _privateConstructorUsedError; DateTime? get retire => throw _privateConstructorUsedError; @@ -44,7 +44,7 @@ abstract class $DiaryModelCopyWith<$Res> { {int id, DateTime date, int closed, - List? meals, + List meals, String? comment, DateTime? wakeup, DateTime? retire}); @@ -66,7 +66,7 @@ class _$DiaryModelCopyWithImpl<$Res, $Val extends DiaryModel> Object? id = null, Object? date = null, Object? closed = null, - Object? meals = freezed, + Object? meals = null, Object? comment = freezed, Object? wakeup = freezed, Object? retire = freezed, @@ -84,10 +84,10 @@ class _$DiaryModelCopyWithImpl<$Res, $Val extends DiaryModel> ? _value.closed : closed // ignore: cast_nullable_to_non_nullable as int, - meals: freezed == meals + meals: null == meals ? _value.meals : meals // ignore: cast_nullable_to_non_nullable - as List?, + as List, comment: freezed == comment ? _value.comment : comment // ignore: cast_nullable_to_non_nullable @@ -116,7 +116,7 @@ abstract class _$$DiaryModelImplCopyWith<$Res> {int id, DateTime date, int closed, - List? meals, + List meals, String? comment, DateTime? wakeup, DateTime? retire}); @@ -136,7 +136,7 @@ class __$$DiaryModelImplCopyWithImpl<$Res> Object? id = null, Object? date = null, Object? closed = null, - Object? meals = freezed, + Object? meals = null, Object? comment = freezed, Object? wakeup = freezed, Object? retire = freezed, @@ -154,10 +154,10 @@ class __$$DiaryModelImplCopyWithImpl<$Res> ? _value.closed : closed // ignore: cast_nullable_to_non_nullable as int, - meals: freezed == meals + meals: null == meals ? _value._meals : meals // ignore: cast_nullable_to_non_nullable - as List?, + as List, comment: freezed == comment ? _value.comment : comment // ignore: cast_nullable_to_non_nullable @@ -181,7 +181,7 @@ class _$DiaryModelImpl implements _DiaryModel { {required this.id, required this.date, required this.closed, - required final List? meals, + required final List meals, this.comment, this.wakeup, this.retire}) @@ -196,14 +196,12 @@ class _$DiaryModelImpl implements _DiaryModel { final DateTime date; @override final int closed; - final List? _meals; + final List _meals; @override - List? get meals { - final value = _meals; - if (value == null) return null; + List get meals { if (_meals is EqualUnmodifiableListView) return _meals; // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(value); + return EqualUnmodifiableListView(_meals); } @override @@ -256,7 +254,7 @@ abstract class _DiaryModel implements DiaryModel { {required final int id, required final DateTime date, required final int closed, - required final List? meals, + required final List meals, final String? comment, final DateTime? wakeup, final DateTime? retire}) = _$DiaryModelImpl; @@ -271,7 +269,7 @@ abstract class _DiaryModel implements DiaryModel { @override int get closed; @override - List? get meals; + List get meals; @override String? get comment; @override diff --git a/lib/features/diary/models/diary_model.g.dart b/lib/features/diary/models/diary_model.g.dart index fc9f7d0..1a13c7d 100644 --- a/lib/features/diary/models/diary_model.g.dart +++ b/lib/features/diary/models/diary_model.g.dart @@ -11,8 +11,8 @@ _$DiaryModelImpl _$$DiaryModelImplFromJson(Map json) => id: (json['id'] as num).toInt(), date: DateTime.parse(json['date'] as String), closed: (json['closed'] as num).toInt(), - meals: (json['meals'] as List?) - ?.map((e) => Meal.fromJson(e as Map)) + meals: (json['meals'] as List) + .map((e) => Meal.fromJson(e as Map)) .toList(), comment: json['comment'] as String?, wakeup: json['wakeup'] == null diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index f2d0b7f..9cc1b77 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:eatvio_app/features/diary/models/meal.dart'; import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; import 'package:intl/intl.dart'; @@ -55,8 +56,13 @@ class DiaryBloc extends Bloc { try { Map data = await diaryRepository.getDiaryID(); final int? diaryID = data['id']; + final DiaryModel diary = await diaryRepository.getDiary(diaryID ?? 45); + final Meal currentMeal = diary.meals[0]; emit(DiaryState.loaded( - diary: await diaryRepository.getDiary(diaryID ?? 45), + diary: diary, + currentMeal: currentMeal, + portions: currentMeal.portions, + photos: currentMeal.photos, commentController: TextEditingController(), productNameController: TextEditingController(), productQuantityController: TextEditingController(), @@ -69,8 +75,9 @@ class DiaryBloc extends Bloc { moodExpanded: false, isLoading: false, isAdded: false, - recommendedChartValues: [0, 0, 0, 0], - consumedChartValues: [0, 0, 0, 0])); + autocompleteList: [], + recommendedChartValues: [1, 1, 1, 1], + consumedChartValues: [1, 1, 1, 1])); } catch (e) { emit(DiaryState.error(errorMessage: e.toString())); print(e); @@ -143,13 +150,13 @@ class DiaryBloc extends Bloc { // Отправляем данные по HTTP маршруту и ждем ответ var response = await sendSatietyData( event.selectedElement, - currentState.currentMeal?.id, + currentState.currentMeal.id, currentState.diary.id, ); if (response.statusCode == 200) { print( - 'Satiety change success! meal_id: ${currentState.currentMeal?.id}, mood: ${event.selectedElement}', + 'Satiety change success! meal_id: ${currentState.currentMeal.id}, mood: ${event.selectedElement}', ); emit(updatedState); // Передаем обновленное состояние в emit } @@ -189,13 +196,13 @@ class DiaryBloc extends Bloc { // Отправляем данные по HTTP маршруту и ждем ответ var response = await sendMoodData( event.selectedElement, - currentState.currentMeal?.id, + currentState.currentMeal.id, currentState.diary.id, ); if (response.statusCode == 200) { print( - 'Mood change success! meal_id: ${currentState.currentMeal?.id}, mood: ${event.selectedElement}', + 'Mood change success! meal_id: ${currentState.currentMeal.id}, mood: ${event.selectedElement}', ); emit(updatedState); // Передаем обновленное состояние в emit } @@ -359,8 +366,8 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - Meal? meal = currentState.diary.meals! - .firstWhere((meal) => meal.id == event.value); + Meal? meal = + currentState.diary.meals.firstWhere((meal) => meal.id == event.value); DiaryStateLoaded updatedState = currentState.copyWith( currentMeal: event.value, @@ -431,7 +438,7 @@ class DiaryBloc extends Bloc { currentState.productNameController?.text, currentState.portionController?.id == 0 ? 'pcs' : 'gr', int.parse(currentState.productQuantityController!.text), - currentState.currentMeal!.id, + currentState.currentMeal.id, currentState.diary.id, ); @@ -523,7 +530,7 @@ class DiaryBloc extends Bloc { var currentState = state as DiaryStateLoaded; int? mealId = - currentState.currentMeal?.id; // Rename id to mealId for clarity + currentState.currentMeal.id; // Rename id to mealId for clarity var response = await sendRemovePortion( event.portionId, @@ -570,7 +577,7 @@ class DiaryBloc extends Bloc { var response = await sendRemovePhoto( event.path, event.photoID, - currentState.currentMeal?.id, + currentState.currentMeal.id, currentState.diary.id, ); print(response.statusCode); @@ -668,7 +675,7 @@ class DiaryBloc extends Bloc { await uploadImageToServer( event.image.path, currentState.diary.id, - currentState.currentMeal!.id, + currentState.currentMeal.id, ); await reloadScreen(event, emit); } diff --git a/lib/features/diary/presentation/bloc/diary_state.dart b/lib/features/diary/presentation/bloc/diary_state.dart index b9f2695..4f32447 100644 --- a/lib/features/diary/presentation/bloc/diary_state.dart +++ b/lib/features/diary/presentation/bloc/diary_state.dart @@ -18,23 +18,23 @@ abstract class DiaryState with _$DiaryState { const factory DiaryState.loaded({ required DiaryModel diary, String? diaryDate, - List? autocompleteList, + required List autocompleteList, required List recommendedChartValues, required List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + required List portions, + required List photos, + required Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - required TextEditingController? commentController, - required TextEditingController? productNameController, - required TextEditingController? productQuantityController, - required TextEditingController? caloriesController, - required TextEditingController? fatsController, - required TextEditingController? proteinsController, - required TextEditingController? carbsController, + required TextEditingController commentController, + required TextEditingController productNameController, + required TextEditingController productQuantityController, + required TextEditingController caloriesController, + required TextEditingController fatsController, + required TextEditingController proteinsController, + required TextEditingController carbsController, int? selectedMood, int? selectedSatiety, required bool wakeupExpanded, diff --git a/lib/features/diary/presentation/bloc/diary_state.freezed.dart b/lib/features/diary/presentation/bloc/diary_state.freezed.dart index 8a5aba4..6a06e2e 100644 --- a/lib/features/diary/presentation/bloc/diary_state.freezed.dart +++ b/lib/features/diary/presentation/bloc/diary_state.freezed.dart @@ -23,12 +23,12 @@ mixin _$DiaryState { required TResult Function( DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, @@ -58,12 +58,12 @@ mixin _$DiaryState { TResult? Function( DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, @@ -93,12 +93,12 @@ mixin _$DiaryState { TResult Function( DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, @@ -210,12 +210,12 @@ class _$DiaryStateImpl implements _DiaryState { required TResult Function( DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, @@ -248,12 +248,12 @@ class _$DiaryStateImpl implements _DiaryState { TResult? Function( DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, @@ -286,12 +286,12 @@ class _$DiaryStateImpl implements _DiaryState { TResult Function( DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, @@ -405,12 +405,12 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { required TResult Function( DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, @@ -443,12 +443,12 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { TResult? Function( DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, @@ -481,12 +481,12 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { TResult Function( DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, @@ -566,12 +566,12 @@ abstract class _$$DiaryStateLoadedImplCopyWith<$Res> { $Res call( {DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, @@ -592,7 +592,7 @@ abstract class _$$DiaryStateLoadedImplCopyWith<$Res> { bool isAdded}); $DiaryModelCopyWith<$Res> get diary; - $MealCopyWith<$Res>? get currentMeal; + $MealCopyWith<$Res> get currentMeal; } /// @nodoc @@ -608,12 +608,12 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> $Res call({ Object? diary = null, Object? diaryDate = freezed, - Object? autocompleteList = freezed, + Object? autocompleteList = null, Object? recommendedChartValues = null, Object? consumedChartValues = null, - Object? portions = freezed, - Object? photos = freezed, - Object? currentMeal = freezed, + Object? portions = null, + Object? photos = null, + Object? currentMeal = null, Object? portionController = freezed, Object? wakeupController = freezed, Object? retireController = freezed, @@ -642,10 +642,10 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> ? _value.diaryDate : diaryDate // ignore: cast_nullable_to_non_nullable as String?, - autocompleteList: freezed == autocompleteList + autocompleteList: null == autocompleteList ? _value._autocompleteList : autocompleteList // ignore: cast_nullable_to_non_nullable - as List?, + as List, recommendedChartValues: null == recommendedChartValues ? _value._recommendedChartValues : recommendedChartValues // ignore: cast_nullable_to_non_nullable @@ -654,18 +654,18 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> ? _value._consumedChartValues : consumedChartValues // ignore: cast_nullable_to_non_nullable as List, - portions: freezed == portions + portions: null == portions ? _value._portions : portions // ignore: cast_nullable_to_non_nullable - as List?, - photos: freezed == photos + as List, + photos: null == photos ? _value._photos : photos // ignore: cast_nullable_to_non_nullable - as List?, - currentMeal: freezed == currentMeal + as List, + currentMeal: null == currentMeal ? _value.currentMeal : currentMeal // ignore: cast_nullable_to_non_nullable - as Meal?, + as Meal, portionController: freezed == portionController ? _value.portionController : portionController // ignore: cast_nullable_to_non_nullable @@ -751,12 +751,8 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> @override @pragma('vm:prefer-inline') - $MealCopyWith<$Res>? get currentMeal { - if (_value.currentMeal == null) { - return null; - } - - return $MealCopyWith<$Res>(_value.currentMeal!, (value) { + $MealCopyWith<$Res> get currentMeal { + return $MealCopyWith<$Res>(_value.currentMeal, (value) { return _then(_value.copyWith(currentMeal: value)); }); } @@ -768,12 +764,12 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { const _$DiaryStateLoadedImpl( {required this.diary, this.diaryDate, - final List? autocompleteList, + required final List autocompleteList, required final List recommendedChartValues, required final List consumedChartValues, - final List? portions, - final List? photos, - this.currentMeal, + required final List portions, + required final List photos, + required this.currentMeal, this.portionController, this.wakeupController, this.retireController, @@ -802,15 +798,13 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { final DiaryModel diary; @override final String? diaryDate; - final List? _autocompleteList; + final List _autocompleteList; @override - List? get autocompleteList { - final value = _autocompleteList; - if (value == null) return null; + List get autocompleteList { if (_autocompleteList is EqualUnmodifiableListView) return _autocompleteList; // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(value); + return EqualUnmodifiableListView(_autocompleteList); } final List _recommendedChartValues; @@ -831,28 +825,24 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { return EqualUnmodifiableListView(_consumedChartValues); } - final List? _portions; + final List _portions; @override - List? get portions { - final value = _portions; - if (value == null) return null; + List get portions { if (_portions is EqualUnmodifiableListView) return _portions; // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(value); + return EqualUnmodifiableListView(_portions); } - final List? _photos; + final List _photos; @override - List? get photos { - final value = _photos; - if (value == null) return null; + List get photos { if (_photos is EqualUnmodifiableListView) return _photos; // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(value); + return EqualUnmodifiableListView(_photos); } @override - final Meal? currentMeal; + final Meal currentMeal; @override final SelectionPopupModel? portionController; @override @@ -997,12 +987,12 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { required TResult Function( DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, @@ -1061,12 +1051,12 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { TResult? Function( DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, @@ -1125,12 +1115,12 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { TResult Function( DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, @@ -1227,12 +1217,12 @@ abstract class DiaryStateLoaded implements DiaryState { const factory DiaryStateLoaded( {required final DiaryModel diary, final String? diaryDate, - final List? autocompleteList, + required final List autocompleteList, required final List recommendedChartValues, required final List consumedChartValues, - final List? portions, - final List? photos, - final Meal? currentMeal, + required final List portions, + required final List photos, + required final Meal currentMeal, final SelectionPopupModel? portionController, final TimeOfDay? wakeupController, final TimeOfDay? retireController, @@ -1254,12 +1244,12 @@ abstract class DiaryStateLoaded implements DiaryState { DiaryModel get diary; String? get diaryDate; - List? get autocompleteList; + List get autocompleteList; List get recommendedChartValues; List get consumedChartValues; - List? get portions; - List? get photos; - Meal? get currentMeal; + List get portions; + List get photos; + Meal get currentMeal; SelectionPopupModel? get portionController; TimeOfDay? get wakeupController; TimeOfDay? get retireController; @@ -1354,12 +1344,12 @@ class _$DiaryStateErrorImpl implements DiaryStateError { required TResult Function( DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, @@ -1392,12 +1382,12 @@ class _$DiaryStateErrorImpl implements DiaryStateError { TResult? Function( DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, @@ -1430,12 +1420,12 @@ class _$DiaryStateErrorImpl implements DiaryStateError { TResult Function( DiaryModel diary, String? diaryDate, - List? autocompleteList, + List autocompleteList, List recommendedChartValues, List consumedChartValues, - List? portions, - List? photos, - Meal? currentMeal, + List portions, + List photos, + Meal currentMeal, SelectionPopupModel? portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index be3a7b4..af39f0b 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -274,8 +274,7 @@ class DiaryScreen extends StatelessWidget { _buildMeal(BuildContext context, DiaryStateLoaded state) { final digitsOnly = FilteringTextInputFormatter.digitsOnly; List _options = - state.autocompleteList!.map((dynamic item) => item as String).toList(); - //print(_options); + state.autocompleteList.map((dynamic item) => item as String).toList(); FocusNode focusNodeName = FocusNode(); return Container( margin: EdgeInsets.symmetric(horizontal: 16.h), @@ -350,7 +349,6 @@ class DiaryScreen extends StatelessWidget { horizontal: 10.h, vertical: 9.v, ), - defaultValue: mealsToDropdown(diary.meals)[0], onChanged: changeMeal(context, state), ); }, @@ -448,7 +446,6 @@ class DiaryScreen extends StatelessWidget { SelectionPopupModel(title: "gr"), SelectionPopupModel(title: "pcs") ], - defaultValue: SelectionPopupModel(title: "gr"), onChanged: changePortion(context, state), ); }, @@ -461,7 +458,7 @@ class DiaryScreen extends StatelessWidget { SizedBox(height: 30.v), _buildAddProduct(context, state), SizedBox(height: 30.v), - ...state.portions! + ...state.portions .map((portion) => _buildProduct(context, portion)) .toList(), SizedBox(height: 30.v), @@ -673,12 +670,12 @@ class DiaryScreen extends StatelessWidget { } _buildCarousel(BuildContext context, DiaryStateLoaded state) { - if (state.currentMeal!.photos.isEmpty) { + if (state.currentMeal.photos.isEmpty) { return Text("Фото нет"); } else { return CarouselSlider( options: CarouselOptions(height: 340.0), - items: state.currentMeal!.photos.map((photo) { + items: state.currentMeal.photos.map((photo) { return _buildPhoto( context, photo); // Assuming photos are stored as strings }).toList(), @@ -1314,7 +1311,7 @@ List mealsToDropdown(List? meals) { return meals! .map((meal) => SelectionPopupModel( id: meal.id, - title: "Прием пищи ${meal.id}", + title: "Прием пищи ${meal.type}", isSelected: false, )) .toList(); -- 2.49.1 From 12a0db50932231ad1b2f69ffcb51c6fa66ef1012 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Sun, 14 Jul 2024 16:25:00 +0300 Subject: [PATCH 050/110] feat(registration): refactor --- test/add_info_test.dart | 54 ----------------------- test/allergies_test.dart | 54 ----------------------- test/blood_pressure_test.dart | 54 ----------------------- test/body_circumferences_test.dart | 54 ----------------------- test/city_of_living_test.dart | 54 ----------------------- test/credentials_test.dart | 54 ----------------------- test/date_of_birth_test.dart | 54 ----------------------- test/diary_test.dart | 71 ------------------------------ test/favorite_foods_test.dart | 54 ----------------------- test/favorite_sports_test.dart | 55 ----------------------- test/gender_test.dart | 55 ----------------------- test/height_test.dart | 55 ----------------------- test/language_select_test.dart | 26 ----------- test/launch_test.dart | 15 ------- test/medicine_intake_test.dart | 55 ----------------------- test/name_test.dart | 55 ----------------------- test/profile_test.dart | 26 ----------- test/settings_test.dart | 26 ----------- test/weight_test.dart | 55 ----------------------- 19 files changed, 926 deletions(-) delete mode 100644 test/add_info_test.dart delete mode 100644 test/allergies_test.dart delete mode 100644 test/blood_pressure_test.dart delete mode 100644 test/body_circumferences_test.dart delete mode 100644 test/city_of_living_test.dart delete mode 100644 test/credentials_test.dart delete mode 100644 test/date_of_birth_test.dart delete mode 100644 test/diary_test.dart delete mode 100644 test/favorite_foods_test.dart delete mode 100644 test/favorite_sports_test.dart delete mode 100644 test/gender_test.dart delete mode 100644 test/height_test.dart delete mode 100644 test/language_select_test.dart delete mode 100644 test/launch_test.dart delete mode 100644 test/medicine_intake_test.dart delete mode 100644 test/name_test.dart delete mode 100644 test/profile_test.dart delete mode 100644 test/settings_test.dart delete mode 100644 test/weight_test.dart diff --git a/test/add_info_test.dart b/test/add_info_test.dart deleted file mode 100644 index 9fa83f8..0000000 --- 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: Scaffold(body: AdditionalInformationScreen()), - ), - ), - ); - }); - }); -} diff --git a/test/allergies_test.dart b/test/allergies_test.dart deleted file mode 100644 index ca8a2f2..0000000 --- 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: Scaffold(body: AllergiesScreen()), - ), - ), - ); - }); - }); -} diff --git a/test/blood_pressure_test.dart b/test/blood_pressure_test.dart deleted file mode 100644 index 30cbb03..0000000 --- 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: Scaffold(body: BloodPressureScreen()), - ), - ), - ); - }); - }); -} diff --git a/test/body_circumferences_test.dart b/test/body_circumferences_test.dart deleted file mode 100644 index 933c8e0..0000000 --- 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: Scaffold(body: BodyCircumferencesScreen()), - ), - ), - ); - }); - }); -} diff --git a/test/city_of_living_test.dart b/test/city_of_living_test.dart deleted file mode 100644 index 229c6f2..0000000 --- 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: Scaffold(body: CityOfLivingScreen()), - ), - ), - ); - }); - }); -} diff --git a/test/credentials_test.dart b/test/credentials_test.dart deleted file mode 100644 index 73995cc..0000000 --- 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: Scaffold(body: CredentialsScreen()), - ), - ), - ); - }); - }); -} diff --git a/test/date_of_birth_test.dart b/test/date_of_birth_test.dart deleted file mode 100644 index e2cac1e..0000000 --- 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: Scaffold(body: DateOfBirthScreen()), - ), - ), - ); - }); - }); -} diff --git a/test/diary_test.dart b/test/diary_test.dart deleted file mode 100644 index 56d1c58..0000000 --- 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 fa4553a..0000000 --- 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: Scaffold(body: FavoriteFoodsScreen()), - ), - ), - ); - }); - }); -} diff --git a/test/favorite_sports_test.dart b/test/favorite_sports_test.dart deleted file mode 100644 index 4b6f672..0000000 --- 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: Scaffold(body: 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 45466f4..0000000 --- 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: Scaffold(body: 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 34eaec4..0000000 --- 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: Scaffold(body: 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 d667404..0000000 --- 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: Scaffold(body: 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 4f1eafe..0000000 --- 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 510b7e8..0000000 --- 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: Scaffold(body: 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 f2a2517..0000000 --- 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: Scaffold(body: 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 cf0ebc4..0000000 --- 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 4e5021a..0000000 --- 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: Scaffold(body: MySettingsScreen()), - ), - ), - ); - }); - }); -} diff --git a/test/weight_test.dart b/test/weight_test.dart deleted file mode 100644 index fcd45c4..0000000 --- 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: Scaffold(body: WeightScreen()), - ), - ), - ); - }); - }); -} -//sports \ No newline at end of file -- 2.49.1 From 3cdab9e1bb5567486eec0c296f00beba4ab653f2 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Sun, 14 Jul 2024 16:30:10 +0300 Subject: [PATCH 051/110] feature(registration): refactor --- lib/app_router.dart | 118 --- .../user_registration_model.dart | 146 ++-- .../user_registration_model.freezed.dart | 811 ++++++++++++++++++ .../user_registration_model.g.dart | 73 ++ .../registration_cubit.dart | 4 +- .../registration_state.dart | 8 +- .../registration_state.freezed.dart | 272 ++---- .../pages/registration_screen.dart | 113 ++- .../additional_information_screen.dart | 2 +- .../allergies_screen/allergies_screen.dart | 2 +- .../bloc/blood_pressure_bloc.dart | 8 +- .../blood_pressure_screen.dart | 4 +- .../body_circumferences_screen.dart | 8 +- .../bloc/city_of_living_bloc.dart | 2 +- .../city_of_living_screen.dart | 1 - .../credentials_screen.dart | 173 ++-- .../date_of_birth_screen.dart | 2 +- .../favorite_foods_screen.dart | 4 +- .../favorite_sports_screen.dart | 2 +- .../gender_screen/bloc/gender_bloc.dart | 2 +- .../gender_screen/gender_screen.dart | 2 +- .../height_screen/height_screen.dart | 2 +- .../bloc/language_select_bloc.dart | 2 +- .../language_select_screen.dart | 100 +-- .../models/language_select_model.dart | 1 + .../medicine_intake_screen.dart | 2 +- .../registration/name_screen/name_screen.dart | 2 +- .../weight_screen/weight_screen.dart | 2 +- lib/widgets/app_bar/appbar_title_image.dart | 31 +- lib/widgets/custom_drop_down.dart | 1 - lib/widgets/custom_text_form_field.dart | 3 +- 31 files changed, 1214 insertions(+), 689 deletions(-) create mode 100644 lib/data/models/userRegistrationModel/user_registration_model.freezed.dart create mode 100644 lib/data/models/userRegistrationModel/user_registration_model.g.dart diff --git a/lib/app_router.dart b/lib/app_router.dart index 5ca4a54..8f16666 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -16,21 +16,6 @@ import 'package:eatvio_app/presentation/plans/plan_select_screen/plan_select_scr 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'; @@ -60,109 +45,6 @@ class AppRouter { name: 'registrationScreen', builder: (context, state) => const RegistrationScreen(), ), - 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( - 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), - routes: [ - GoRoute( - path: 'favorite-sports-screen', - name: 'favoriteSportsScreen', - builder: (context, state) => FavoriteSportsScreen.builder(context, state.extra), - routes: [ - 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), - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), ], ), ShellRoute( diff --git a/lib/data/models/userRegistrationModel/user_registration_model.dart b/lib/data/models/userRegistrationModel/user_registration_model.dart index baeb3a1..cae81cd 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.dart @@ -1,92 +1,60 @@ -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') + 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 String weight, + required String height, + @JsonKey(name: 'chest_circumference') + required String chestCircumference, + @JsonKey(name: 'waist_circumference') + required String waistCircumference, + @JsonKey(name: 'hip_circumference') + required String hipCircumference, + @JsonKey(name: 'blood_pressure_up') + required String bloodPressureUp, + @JsonKey(name: 'blood_pressure_down') + required String bloodPressureDown, + @JsonKey(name: 'has_hypo') + required String hasHypo, + @JsonKey(name: 'has_hyper') + required String 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') + String 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 0000000..9d00a7d --- /dev/null +++ b/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart @@ -0,0 +1,811 @@ +// 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') + 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; + String get weight => throw _privateConstructorUsedError; + String get height => throw _privateConstructorUsedError; + @JsonKey(name: 'chest_circumference') + String get chestCircumference => throw _privateConstructorUsedError; + @JsonKey(name: 'waist_circumference') + String get waistCircumference => throw _privateConstructorUsedError; + @JsonKey(name: 'hip_circumference') + String get hipCircumference => throw _privateConstructorUsedError; + @JsonKey(name: 'blood_pressure_up') + String get bloodPressureUp => throw _privateConstructorUsedError; + @JsonKey(name: 'blood_pressure_down') + String get bloodPressureDown => throw _privateConstructorUsedError; + @JsonKey(name: 'has_hypo') + String get hasHypo => throw _privateConstructorUsedError; + @JsonKey(name: 'has_hyper') + String 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') + String 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') 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, + String weight, + String height, + @JsonKey(name: 'chest_circumference') String chestCircumference, + @JsonKey(name: 'waist_circumference') String waistCircumference, + @JsonKey(name: 'hip_circumference') String hipCircumference, + @JsonKey(name: 'blood_pressure_up') String bloodPressureUp, + @JsonKey(name: 'blood_pressure_down') String bloodPressureDown, + @JsonKey(name: 'has_hypo') String hasHypo, + @JsonKey(name: 'has_hyper') String 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') String 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 String, + height: null == height + ? _value.height + : height // ignore: cast_nullable_to_non_nullable + as String, + chestCircumference: null == chestCircumference + ? _value.chestCircumference + : chestCircumference // ignore: cast_nullable_to_non_nullable + as String, + waistCircumference: null == waistCircumference + ? _value.waistCircumference + : waistCircumference // ignore: cast_nullable_to_non_nullable + as String, + hipCircumference: null == hipCircumference + ? _value.hipCircumference + : hipCircumference // ignore: cast_nullable_to_non_nullable + as String, + bloodPressureUp: null == bloodPressureUp + ? _value.bloodPressureUp + : bloodPressureUp // ignore: cast_nullable_to_non_nullable + as String, + bloodPressureDown: null == bloodPressureDown + ? _value.bloodPressureDown + : bloodPressureDown // ignore: cast_nullable_to_non_nullable + as String, + hasHypo: null == hasHypo + ? _value.hasHypo + : hasHypo // ignore: cast_nullable_to_non_nullable + as String, + hasHyper: null == hasHyper + ? _value.hasHyper + : hasHyper // ignore: cast_nullable_to_non_nullable + as String, + 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 String, + ) 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') 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, + String weight, + String height, + @JsonKey(name: 'chest_circumference') String chestCircumference, + @JsonKey(name: 'waist_circumference') String waistCircumference, + @JsonKey(name: 'hip_circumference') String hipCircumference, + @JsonKey(name: 'blood_pressure_up') String bloodPressureUp, + @JsonKey(name: 'blood_pressure_down') String bloodPressureDown, + @JsonKey(name: 'has_hypo') String hasHypo, + @JsonKey(name: 'has_hyper') String 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') String 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 String, + height: null == height + ? _value.height + : height // ignore: cast_nullable_to_non_nullable + as String, + chestCircumference: null == chestCircumference + ? _value.chestCircumference + : chestCircumference // ignore: cast_nullable_to_non_nullable + as String, + waistCircumference: null == waistCircumference + ? _value.waistCircumference + : waistCircumference // ignore: cast_nullable_to_non_nullable + as String, + hipCircumference: null == hipCircumference + ? _value.hipCircumference + : hipCircumference // ignore: cast_nullable_to_non_nullable + as String, + bloodPressureUp: null == bloodPressureUp + ? _value.bloodPressureUp + : bloodPressureUp // ignore: cast_nullable_to_non_nullable + as String, + bloodPressureDown: null == bloodPressureDown + ? _value.bloodPressureDown + : bloodPressureDown // ignore: cast_nullable_to_non_nullable + as String, + hasHypo: null == hasHypo + ? _value.hasHypo + : hasHypo // ignore: cast_nullable_to_non_nullable + as String, + hasHyper: null == hasHyper + ? _value.hasHyper + : hasHyper // ignore: cast_nullable_to_non_nullable + as String, + 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 String, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { + const _$UserRegistrationSheetImpl( + {required this.name, + @JsonKey(name: 'first_name') required this.firstName, + @JsonKey(name: 'last') 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') + 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 String weight; + @override + final String height; + @override + @JsonKey(name: 'chest_circumference') + final String chestCircumference; + @override + @JsonKey(name: 'waist_circumference') + final String waistCircumference; + @override + @JsonKey(name: 'hip_circumference') + final String hipCircumference; + @override + @JsonKey(name: 'blood_pressure_up') + final String bloodPressureUp; + @override + @JsonKey(name: 'blood_pressure_down') + final String bloodPressureDown; + @override + @JsonKey(name: 'has_hypo') + final String hasHypo; + @override + @JsonKey(name: 'has_hyper') + final String 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 String 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') 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 String weight, + required final String height, + @JsonKey(name: 'chest_circumference') + required final String chestCircumference, + @JsonKey(name: 'waist_circumference') + required final String waistCircumference, + @JsonKey(name: 'hip_circumference') + required final String hipCircumference, + @JsonKey(name: 'blood_pressure_up') required final String bloodPressureUp, + @JsonKey(name: 'blood_pressure_down') + required final String bloodPressureDown, + @JsonKey(name: 'has_hypo') required final String hasHypo, + @JsonKey(name: 'has_hyper') required final String 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 String 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') + 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 + String get weight; + @override + String get height; + @override + @JsonKey(name: 'chest_circumference') + String get chestCircumference; + @override + @JsonKey(name: 'waist_circumference') + String get waistCircumference; + @override + @JsonKey(name: 'hip_circumference') + String get hipCircumference; + @override + @JsonKey(name: 'blood_pressure_up') + String get bloodPressureUp; + @override + @JsonKey(name: 'blood_pressure_down') + String get bloodPressureDown; + @override + @JsonKey(name: 'has_hypo') + String get hasHypo; + @override + @JsonKey(name: 'has_hyper') + String 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') + String 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 0000000..8eafe71 --- /dev/null +++ b/lib/data/models/userRegistrationModel/user_registration_model.g.dart @@ -0,0 +1,73 @@ +// 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'] 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 String, + height: json['height'] as String, + chestCircumference: json['chest_circumference'] as String, + waistCircumference: json['waist_circumference'] as String, + hipCircumference: json['hip_circumference'] as String, + bloodPressureUp: json['blood_pressure_up'] as String, + bloodPressureDown: json['blood_pressure_down'] as String, + hasHypo: json['has_hypo'] as String, + hasHyper: json['has_hyper'] as String, + 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 String? ?? '1.2', + ); + +Map _$$UserRegistrationSheetImplToJson( + _$UserRegistrationSheetImpl instance) => + { + 'name': instance.name, + 'first_name': instance.firstName, + 'last': 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/registration/presentation/bloc/registration_cubit/registration_cubit.dart b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart index bf421e7..5e59454 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart @@ -4,7 +4,7 @@ import 'package:eatvio_app/features/registration/presentation/bloc/registration_ import 'package:eatvio_app/presentation/registration/language_select_screen/models/language_select_model.dart'; class RegistrationCubit extends Cubit { - RegistrationCubit() : super(RegistrationState.loaded(sheet: LanguageSelectModel().userRegistrationSheet)); + RegistrationCubit() : super(RegistrationState(sheet: LanguageSelectModel().userRegistrationSheet)); - updateSheet(UserRegistrationSheet sheet) => emit(RegistrationState.loaded(sheet: sheet)); + updateSheet(UserRegistrationSheet sheet) => emit(RegistrationState(sheet: sheet)); } diff --git a/lib/features/registration/presentation/bloc/registration_cubit/registration_state.dart b/lib/features/registration/presentation/bloc/registration_cubit/registration_state.dart index b6ea767..d1e2090 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_state.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_state.dart @@ -4,10 +4,8 @@ import 'package:freezed_annotation/freezed_annotation.dart'; part 'registration_state.freezed.dart'; @freezed -abstract class RegistrationState with _$RegistrationState { - const factory RegistrationState() = _RegistrationState; - - const factory RegistrationState.loaded({ +class RegistrationState with _$RegistrationState { + const factory RegistrationState({ required UserRegistrationSheet sheet, - }) = RegistrationStateLoaded; + }) = _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 index 01b2382..dcb4923 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_state.freezed.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_state.freezed.dart @@ -16,43 +16,10 @@ final _privateConstructorUsedError = UnsupportedError( /// @nodoc mixin _$RegistrationState { - @optionalTypeArgs - TResult when( - TResult Function() $default, { - required TResult Function(UserRegistrationSheet sheet) loaded, - }) => - throw _privateConstructorUsedError; - @optionalTypeArgs - TResult? whenOrNull( - TResult? Function()? $default, { - TResult? Function(UserRegistrationSheet sheet)? loaded, - }) => - throw _privateConstructorUsedError; - @optionalTypeArgs - TResult maybeWhen( - TResult Function()? $default, { - TResult Function(UserRegistrationSheet sheet)? loaded, - required TResult orElse(), - }) => - throw _privateConstructorUsedError; - @optionalTypeArgs - TResult map( - TResult Function(_RegistrationState value) $default, { - required TResult Function(RegistrationStateLoaded value) loaded, - }) => - throw _privateConstructorUsedError; - @optionalTypeArgs - TResult? mapOrNull( - TResult? Function(_RegistrationState value)? $default, { - TResult? Function(RegistrationStateLoaded value)? loaded, - }) => - throw _privateConstructorUsedError; - @optionalTypeArgs - TResult maybeMap( - TResult Function(_RegistrationState value)? $default, { - TResult Function(RegistrationStateLoaded value)? loaded, - required TResult orElse(), - }) => + UserRegistrationSheet get sheet => throw _privateConstructorUsedError; + + @JsonKey(ignore: true) + $RegistrationStateCopyWith get copyWith => throw _privateConstructorUsedError; } @@ -61,6 +28,10 @@ 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 @@ -72,13 +43,41 @@ class _$RegistrationStateCopyWithImpl<$Res, $Val extends RegistrationState> 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> { +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 @@ -88,119 +87,13 @@ class __$$RegistrationStateImplCopyWithImpl<$Res> __$$RegistrationStateImplCopyWithImpl(_$RegistrationStateImpl _value, $Res Function(_$RegistrationStateImpl) _then) : super(_value, _then); -} - -/// @nodoc - -class _$RegistrationStateImpl implements _RegistrationState { - const _$RegistrationStateImpl(); - - @override - String toString() { - return 'RegistrationState()'; - } - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is _$RegistrationStateImpl); - } - - @override - int get hashCode => runtimeType.hashCode; - - @override - @optionalTypeArgs - TResult when( - TResult Function() $default, { - required TResult Function(UserRegistrationSheet sheet) loaded, - }) { - return $default(); - } - - @override - @optionalTypeArgs - TResult? whenOrNull( - TResult? Function()? $default, { - TResult? Function(UserRegistrationSheet sheet)? loaded, - }) { - return $default?.call(); - } - - @override - @optionalTypeArgs - TResult maybeWhen( - TResult Function()? $default, { - TResult Function(UserRegistrationSheet sheet)? loaded, - required TResult orElse(), - }) { - if ($default != null) { - return $default(); - } - return orElse(); - } - - @override - @optionalTypeArgs - TResult map( - TResult Function(_RegistrationState value) $default, { - required TResult Function(RegistrationStateLoaded value) loaded, - }) { - return $default(this); - } - - @override - @optionalTypeArgs - TResult? mapOrNull( - TResult? Function(_RegistrationState value)? $default, { - TResult? Function(RegistrationStateLoaded value)? loaded, - }) { - return $default?.call(this); - } - - @override - @optionalTypeArgs - TResult maybeMap( - TResult Function(_RegistrationState value)? $default, { - TResult Function(RegistrationStateLoaded value)? loaded, - required TResult orElse(), - }) { - if ($default != null) { - return $default(this); - } - return orElse(); - } -} - -abstract class _RegistrationState implements RegistrationState { - const factory _RegistrationState() = _$RegistrationStateImpl; -} - -/// @nodoc -abstract class _$$RegistrationStateLoadedImplCopyWith<$Res> { - factory _$$RegistrationStateLoadedImplCopyWith( - _$RegistrationStateLoadedImpl value, - $Res Function(_$RegistrationStateLoadedImpl) then) = - __$$RegistrationStateLoadedImplCopyWithImpl<$Res>; - @useResult - $Res call({UserRegistrationSheet sheet}); -} - -/// @nodoc -class __$$RegistrationStateLoadedImplCopyWithImpl<$Res> - extends _$RegistrationStateCopyWithImpl<$Res, _$RegistrationStateLoadedImpl> - implements _$$RegistrationStateLoadedImplCopyWith<$Res> { - __$$RegistrationStateLoadedImplCopyWithImpl( - _$RegistrationStateLoadedImpl _value, - $Res Function(_$RegistrationStateLoadedImpl) _then) - : super(_value, _then); @pragma('vm:prefer-inline') @override $Res call({ Object? sheet = null, }) { - return _then(_$RegistrationStateLoadedImpl( + return _then(_$RegistrationStateImpl( sheet: null == sheet ? _value.sheet : sheet // ignore: cast_nullable_to_non_nullable @@ -211,22 +104,22 @@ class __$$RegistrationStateLoadedImplCopyWithImpl<$Res> /// @nodoc -class _$RegistrationStateLoadedImpl implements RegistrationStateLoaded { - const _$RegistrationStateLoadedImpl({required this.sheet}); +class _$RegistrationStateImpl implements _RegistrationState { + const _$RegistrationStateImpl({required this.sheet}); @override final UserRegistrationSheet sheet; @override String toString() { - return 'RegistrationState.loaded(sheet: $sheet)'; + return 'RegistrationState(sheet: $sheet)'; } @override bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && - other is _$RegistrationStateLoadedImpl && + other is _$RegistrationStateImpl && (identical(other.sheet, sheet) || other.sheet == sheet)); } @@ -236,80 +129,19 @@ class _$RegistrationStateLoadedImpl implements RegistrationStateLoaded { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$RegistrationStateLoadedImplCopyWith<_$RegistrationStateLoadedImpl> - get copyWith => __$$RegistrationStateLoadedImplCopyWithImpl< - _$RegistrationStateLoadedImpl>(this, _$identity); - - @override - @optionalTypeArgs - TResult when( - TResult Function() $default, { - required TResult Function(UserRegistrationSheet sheet) loaded, - }) { - return loaded(sheet); - } - - @override - @optionalTypeArgs - TResult? whenOrNull( - TResult? Function()? $default, { - TResult? Function(UserRegistrationSheet sheet)? loaded, - }) { - return loaded?.call(sheet); - } - - @override - @optionalTypeArgs - TResult maybeWhen( - TResult Function()? $default, { - TResult Function(UserRegistrationSheet sheet)? loaded, - required TResult orElse(), - }) { - if (loaded != null) { - return loaded(sheet); - } - return orElse(); - } - - @override - @optionalTypeArgs - TResult map( - TResult Function(_RegistrationState value) $default, { - required TResult Function(RegistrationStateLoaded value) loaded, - }) { - return loaded(this); - } - - @override - @optionalTypeArgs - TResult? mapOrNull( - TResult? Function(_RegistrationState value)? $default, { - TResult? Function(RegistrationStateLoaded value)? loaded, - }) { - return loaded?.call(this); - } - - @override - @optionalTypeArgs - TResult maybeMap( - TResult Function(_RegistrationState value)? $default, { - TResult Function(RegistrationStateLoaded value)? loaded, - required TResult orElse(), - }) { - if (loaded != null) { - return loaded(this); - } - return orElse(); - } + _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => + __$$RegistrationStateImplCopyWithImpl<_$RegistrationStateImpl>( + this, _$identity); } -abstract class RegistrationStateLoaded implements RegistrationState { - const factory RegistrationStateLoaded( - {required final UserRegistrationSheet sheet}) = - _$RegistrationStateLoadedImpl; +abstract class _RegistrationState implements RegistrationState { + const factory _RegistrationState( + {required final UserRegistrationSheet sheet}) = _$RegistrationStateImpl; + @override UserRegistrationSheet get sheet; + @override @JsonKey(ignore: true) - _$$RegistrationStateLoadedImplCopyWith<_$RegistrationStateLoadedImpl> - get copyWith => throw _privateConstructorUsedError; + _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/registration/presentation/pages/registration_screen.dart b/lib/features/registration/presentation/pages/registration_screen.dart index d181e3c..3ee6d0c 100644 --- a/lib/features/registration/presentation/pages/registration_screen.dart +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -20,6 +20,7 @@ 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}); @@ -64,7 +65,6 @@ class _RegistrationScreenState extends State { create: (BuildContext context) => RegistrationCubit(), child: BlocBuilder( builder: (BuildContext context, RegistrationState state) { - (state as RegistrationStateLoaded); return PopScope( canPop: false, onPopInvoked: (_) => _showPopDialog(), @@ -112,12 +112,14 @@ class _RegistrationScreenState extends State { ), backgroundColor: appTheme.blueA400, onPressed: () { - setState(() { - pageController.nextPage( - duration: const Duration(milliseconds: 350), - curve: Curves.easeInOut, - ); - }); + if (canGoNext(state)) { + setState(() { + pageController.nextPage( + duration: const Duration(milliseconds: 350), + curve: Curves.easeInOut, + ); + }); + } }, label: Text( 'Продолжить', @@ -169,21 +171,21 @@ class _RegistrationScreenState extends State { }); }, children: [ - LanguageSelectScreen.builder(context), - CredentialsScreen.builder(context, state.sheet), - NameScreen.builder(context, state.sheet), - GenderScreen.builder(context, state.sheet), - DateOfBirthScreen.builder(context, state.sheet), - CityOfLivingScreen.builder(context, state.sheet), - BodyCircumferencesScreen.builder(context, state.sheet), - WeightScreen.builder(context, state.sheet), - HeightScreen.builder(context, state.sheet), - BloodPressureScreen.builder(context, state.sheet), - AllergiesScreen.builder(context, state.sheet), - MedicineIntakeScreen.builder(context, state.sheet), - FavoriteSportsScreen.builder(context, state.sheet), - FavoriteFoodsScreen.builder(context, state.sheet), - AdditionalInformationScreen.builder(context, state.sheet), + LanguageSelectScreen(sheet: context.read().state.sheet), + CredentialsScreen(sheet: context.read().state.sheet), + NameScreen(), + GenderScreen(), + DateOfBirthScreen(), + CityOfLivingScreen(), + BodyCircumferencesScreen(), + WeightScreen(), + HeightScreen(), + BloodPressureScreen(), + AllergiesScreen(), + MedicineIntakeScreen(), + FavoriteSportsScreen(), + FavoriteFoodsScreen(), + AdditionalInformationScreen(), ], ), ), @@ -192,4 +194,71 @@ class _RegistrationScreenState extends State { ), ); } + + bool canGoNext(state) { + switch (step) { + case 2: + List errors = validateFields(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; + } + default: + return true; + } + } + + 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/additional_information_screen/additional_information_screen.dart b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart index b39743e..c12af1f 100644 --- a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart +++ b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart @@ -52,7 +52,7 @@ class AdditionalInformationScreen extends StatelessWidget { onTapFinish(AdditionalInformationState state, BuildContext context) { return () async { UserRegistrationSheet sheet = state.additionalInformationModelObj!.userRegistrationSheet; - sheet.additionalInfo = state.editTextController!.text; + // sheet.additionalInfo = state.editTextController!.text; final response = await http.post( Uri.parse(dotenv.env['SERVER_ROOT']! + '/register'), diff --git a/lib/presentation/registration/allergies_screen/allergies_screen.dart b/lib/presentation/registration/allergies_screen/allergies_screen.dart index 51c5e6a..7a2ac1c 100644 --- a/lib/presentation/registration/allergies_screen/allergies_screen.dart +++ b/lib/presentation/registration/allergies_screen/allergies_screen.dart @@ -68,7 +68,7 @@ class _AllergiesScreenState extends State { onTapContinue(AllergiesState state, BuildContext context) { return () { UserRegistrationSheet sheet = state.allergiesModelObj!.userRegistrationSheet; - sheet.aboutAllergy = state.enterInformationController!.text; + // sheet.aboutAllergy = state.enterInformationController!.text; GoRouter.of(context).goNamed('medicineIntakeScreen', extra: sheet); }; } 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 index 4741654..2fda1b5 100644 --- a/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_bloc.dart +++ b/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_bloc.dart @@ -18,9 +18,9 @@ class BloodPressureBloc extends Bloc { Emitter emit, ) { if (event.value.id == 1) { - state.bloodPressureModelObj!.userRegistrationSheet.hasHyper = '1'; + // state.bloodPressureModelObj!.userRegistrationSheet.hasHyper = '1'; } else { - state.bloodPressureModelObj!.userRegistrationSheet.hasHyper = '0'; + // state.bloodPressureModelObj!.userRegistrationSheet.hasHyper = '0'; } emit(state.copyWith(selectedHyperValue: event.value)); } @@ -30,9 +30,9 @@ class BloodPressureBloc extends Bloc { Emitter emit, ) { if (event.value.id == 1) { - state.bloodPressureModelObj!.userRegistrationSheet.hasHypo = '1'; + // state.bloodPressureModelObj!.userRegistrationSheet.hasHypo = '1'; } else { - state.bloodPressureModelObj!.userRegistrationSheet.hasHypo = '0'; + // state.bloodPressureModelObj!.userRegistrationSheet.hasHypo = '0'; } emit(state.copyWith(selectedHypoValue: event.value)); } diff --git a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart b/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart index 1ad3636..d8efedd 100644 --- a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart +++ b/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart @@ -159,8 +159,8 @@ class _BloodPressureScreenState extends State { 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; + // sheet.bloodPressureUp = state.upPressureController!.text; + // sheet.bloodPressureDown = state.downPressureController!.text; AppRouter.navigatorKey.currentContext?.goNamed('allergiesScreen', extra: sheet); } else { String errorMessage = ''; diff --git a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart b/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart index d9f0861..60733e3 100644 --- a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart +++ b/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart @@ -36,7 +36,7 @@ class _BodyCircumferencesScreenState extends State { child: Column( children: [ Text("initial_measurements".tr, style: theme.textTheme.headlineSmall), - SizedBox(height: 93.v), + SizedBox(height: 16.v), Column( children: [ Text("chest_circumference".tr, style: theme.textTheme.bodyLarge), @@ -94,9 +94,9 @@ class _BodyCircumferencesScreenState extends State { 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; + // 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 = ''; 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 index 71864db..e642961 100644 --- 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 @@ -27,7 +27,7 @@ class CityOfLivingBloc extends Bloc { Emitter emit, ) { emit(state.copyWith(selectedDropDownValue: event.value)); - state.cityOfLivingModelObj?.userRegistrationSheet.country = + // state.cityOfLivingModelObj?.userRegistrationSheet.country = event.value.title; } 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 index 0d35f1f..f5ee8a8 100644 --- 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 @@ -28,7 +28,6 @@ class CityOfLivingScreen extends StatelessWidget { padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 9.v), child: Column( children: [ - SizedBox(height: 39.v), Text("place_of_living".tr, style: theme.textTheme.headlineSmall), SizedBox(height: 39.v), Text("country".tr, style: theme.textTheme.bodyLarge), diff --git a/lib/presentation/registration/credentials_screen/credentials_screen.dart b/lib/presentation/registration/credentials_screen/credentials_screen.dart index d9e15d3..ec7809c 100644 --- a/lib/presentation/registration/credentials_screen/credentials_screen.dart +++ b/lib/presentation/registration/credentials_screen/credentials_screen.dart @@ -1,23 +1,34 @@ -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:validators/validators.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/core/app_export.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(), - ); +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 @@ -34,131 +45,51 @@ class CredentialsScreen extends StatelessWidget { 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); + 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), - BlocSelector( - selector: (state) => state.nameController, - builder: (context, nameController) { - return CustomTextFormField(controller: nameController, textInputAction: TextInputAction.done); + 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), - BlocSelector( - selector: (state) => state.passwordController, - builder: (context, passwordController) { - return CustomTextFormField( - obscureText: true, - controller: passwordController, - ); + 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), - BlocSelector( - selector: (state) => state.passwordConfirmationController, - builder: (context, passwordConfirmationController) { - return CustomTextFormField(obscureText: true, controller: passwordConfirmationController, textInputAction: TextInputAction.done); + CustomTextFormField( + obscureText: true, + controller: passwordConfirmationController, + textInputAction: TextInputAction.done, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(passwordConfirmation: newValue)); }, ), - // 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); - }; - } - - - 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/date_of_birth_screen/date_of_birth_screen.dart b/lib/presentation/registration/date_of_birth_screen/date_of_birth_screen.dart index 432a5be..0952a66 100644 --- 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 @@ -65,7 +65,7 @@ class _DateOfBirthScreenState extends State { onTapContinue(DateOfBirthState state, BuildContext context) { return () { UserRegistrationSheet sheet = state.dateOfBirthModelObj!.userRegistrationSheet; - sheet.birthdate = selectedDate.toString(); + // sheet.birthdate = selectedDate.toString(); GoRouter.of(context).goNamed('cityOfLivingScreen', extra: sheet); }; } diff --git a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart b/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart index a1015d7..0db859d 100644 --- a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart +++ b/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart @@ -81,8 +81,8 @@ class _FavoriteFoodsScreenState extends State { onTapContinue(FavoriteFoodsState state, BuildContext context) { return () { UserRegistrationSheet sheet = state.favoriteFoodsModelObj!.userRegistrationSheet; - sheet.favoriteFoods = state.favoriteFoodsController!.text; - sheet.unfavoriteFoods = state.unfavoriteFoodsController!.text; + // sheet.favoriteFoods = state.favoriteFoodsController!.text; + // sheet.unfavoriteFoods = state.unfavoriteFoodsController!.text; GoRouter.of(context).goNamed('additionalInformationScreen', extra: sheet); }; } diff --git a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart b/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart index 5a8f3f3..5d8be5d 100644 --- a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart +++ b/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart @@ -70,7 +70,7 @@ class _FavoriteSportsScreenState extends State { onTapContinue(FavoriteSportsState state, BuildContext context) { return () { UserRegistrationSheet sheet = state.favoriteSportsModelObj!.userRegistrationSheet; - sheet.aboutSportHobbies = state.enterinformationController!.text; + // sheet.aboutSportHobbies = state.enterinformationController!.text; GoRouter.of(context).goNamed('favoriteFoodsScreen', extra: sheet); }; } diff --git a/lib/presentation/registration/gender_screen/bloc/gender_bloc.dart b/lib/presentation/registration/gender_screen/bloc/gender_bloc.dart index 5f614c2..fe30581 100644 --- a/lib/presentation/registration/gender_screen/bloc/gender_bloc.dart +++ b/lib/presentation/registration/gender_screen/bloc/gender_bloc.dart @@ -24,6 +24,6 @@ class GenderBloc extends Bloc { Emitter emit, ) { emit(state.copyWith(selectedRadioValue: event.value)); - state.genderModelObj?.userRegistrationSheet.gender = event.value; + // state.genderModelObj?.userRegistrationSheet.gender = event.value; } } diff --git a/lib/presentation/registration/gender_screen/gender_screen.dart b/lib/presentation/registration/gender_screen/gender_screen.dart index 72f8f5c..5ffa6be 100644 --- a/lib/presentation/registration/gender_screen/gender_screen.dart +++ b/lib/presentation/registration/gender_screen/gender_screen.dart @@ -80,7 +80,7 @@ class _GenderScreenState extends State { onTapNext(GenderState state, BuildContext context) { return () { UserRegistrationSheet sheet = state.genderModelObj!.userRegistrationSheet; - sheet.gender = state.selectedRadioValue!; + // sheet.gender = state.selectedRadioValue!; GoRouter.of(context).goNamed('dateOfBirthScreen', extra: sheet); }; } diff --git a/lib/presentation/registration/height_screen/height_screen.dart b/lib/presentation/registration/height_screen/height_screen.dart index 66e2762..1e0b88b 100644 --- a/lib/presentation/registration/height_screen/height_screen.dart +++ b/lib/presentation/registration/height_screen/height_screen.dart @@ -31,7 +31,7 @@ class HeightScreen extends StatelessWidget { "height_measurements".tr, style: theme.textTheme.headlineSmall, ), - SizedBox(height: 174.v), + SizedBox(height: 16.v), Column( children: [ Text( 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 index c77ba3a..7604717 100644 --- a/lib/presentation/registration/language_select_screen/bloc/language_select_bloc.dart +++ b/lib/presentation/registration/language_select_screen/bloc/language_select_bloc.dart @@ -24,7 +24,7 @@ class LanguageSelectBloc extends Bloc _changeDropDown(ChangeDropDownEvent event, Emitter emit) { emit(state.copyWith(selectedDropDownValue: event.value)); - state.languageSelectModelObj?.userRegistrationSheet.lang = event.value.title; + // state.languageSelectModelObj?.userRegistrationSheet.lang = event.value.title; } List fillDropdownItemList() { diff --git a/lib/presentation/registration/language_select_screen/language_select_screen.dart b/lib/presentation/registration/language_select_screen/language_select_screen.dart index f2ac257..1a0dc41 100644 --- a/lib/presentation/registration/language_select_screen/language_select_screen.dart +++ b/lib/presentation/registration/language_select_screen/language_select_screen.dart @@ -1,21 +1,29 @@ -import 'bloc/language_select_bloc.dart'; -import 'models/language_select_model.dart'; 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 StatelessWidget { - const LanguageSelectScreen({Key? key}) : super(key: key); +class LanguageSelectScreen extends StatefulWidget { + final UserRegistrationSheet sheet; - static Widget builder(BuildContext context) { - return BlocProvider( - create: (context) => LanguageSelectBloc( - LanguageSelectState( - languageSelectModelObj: LanguageSelectModel(), - ), - )..add(LanguageSelectInitialEvent()), - child: LanguageSelectScreen(), - ); + const LanguageSelectScreen({required this.sheet, super.key}); + + @override + State createState() => _LanguageSelectScreenState(); +} + +class _LanguageSelectScreenState extends State { + final List dropdownItemList = [ + SelectionPopupModel(id: 1, title: "Русский", isSelected: true), + ]; + + late SelectionPopupModel value; + + @override + void initState() { + super.initState(); + value = SelectionPopupModel(title: widget.sheet.lang); } @override @@ -36,56 +44,28 @@ class LanguageSelectScreen extends StatelessWidget { ), ), const SizedBox(height: 32), - 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), - ); - }, + 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, + onChanged: (SelectionPopupModel newValue) => setState(() { + value = newValue; + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(lang: value.title)); + }), ), - // 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 index 465a8ac..c337c55 100644 --- a/lib/presentation/registration/language_select_screen/models/language_select_model.dart +++ b/lib/presentation/registration/language_select_screen/models/language_select_model.dart @@ -8,6 +8,7 @@ import 'package:eatvio_app/data/models/selectionPopupModel/selection_popup_model /// 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: '', diff --git a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart b/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart index 2edc4d6..4934d31 100644 --- a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart +++ b/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart @@ -82,7 +82,7 @@ class _MedicineIntakeScreenState extends State { onTapNext(MedicineIntakeState state, BuildContext context) { return () { UserRegistrationSheet sheet = state.medicineIntakeModelObj!.userRegistrationSheet; - sheet.aboutTakingPils = state.enterInformationController!.text; + // sheet.aboutTakingPils = state.enterInformationController!.text; GoRouter.of(context).goNamed( 'favoriteSportsScreen', extra: sheet, diff --git a/lib/presentation/registration/name_screen/name_screen.dart b/lib/presentation/registration/name_screen/name_screen.dart index be74170..8721d1f 100644 --- a/lib/presentation/registration/name_screen/name_screen.dart +++ b/lib/presentation/registration/name_screen/name_screen.dart @@ -29,7 +29,7 @@ class NameScreen extends StatelessWidget { child: Column( children: [ Text("what_is_your_name".tr, style: theme.textTheme.headlineSmall), - SizedBox(height: 93.v), + SizedBox(height: 16.v), Text("first_name".tr, style: theme.textTheme.bodyLarge), SizedBox(height: 3.v), BlocSelector( diff --git a/lib/presentation/registration/weight_screen/weight_screen.dart b/lib/presentation/registration/weight_screen/weight_screen.dart index 9f0ab8e..2fe886b 100644 --- a/lib/presentation/registration/weight_screen/weight_screen.dart +++ b/lib/presentation/registration/weight_screen/weight_screen.dart @@ -31,7 +31,7 @@ class WeightScreen extends StatelessWidget { "weight_measurements".tr, style: theme.textTheme.headlineSmall, ), - SizedBox(height: 174.v), + SizedBox(height: 16.v), Column( children: [ Text( diff --git a/lib/widgets/app_bar/appbar_title_image.dart b/lib/widgets/app_bar/appbar_title_image.dart index 6242412..429ab4d 100644 --- a/lib/widgets/app_bar/appbar_title_image.dart +++ b/lib/widgets/app_bar/appbar_title_image.dart @@ -3,35 +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: 48, - fit: BoxFit.contain, - ), - ), + return CustomImageView( + imagePath: imagePath, + height: 48, + fit: BoxFit.contain, ); } - - void onTapCall() {} } diff --git a/lib/widgets/custom_drop_down.dart b/lib/widgets/custom_drop_down.dart index 759efc1..09fdbba 100644 --- a/lib/widgets/custom_drop_down.dart +++ b/lib/widgets/custom_drop_down.dart @@ -92,7 +92,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_text_form_field.dart b/lib/widgets/custom_text_form_field.dart index e70b2b5..3d061e9 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!, -- 2.49.1 From 088fe08b377f164187bf27a5deda972a62f20192 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Sun, 14 Jul 2024 16:44:08 +0300 Subject: [PATCH 052/110] feature(registration): refactor 1 --- lib/main.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/main.dart b/lib/main.dart index 7faced2..5cb4e31 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -68,7 +68,7 @@ class MyApp extends StatelessWidget { theme: theme, title: 'Eatvio', routerConfig: AppRouter.appRouter, - debugShowCheckedModeBanner: false, + debugShowCheckedModeBanner: true, localizationsDelegates: [ AppLocalizationDelegate(), GlobalMaterialLocalizations.delegate, -- 2.49.1 From da447d696049f917cd3f42f44c92f60cab1e4a1a Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Sun, 14 Jul 2024 16:45:57 +0300 Subject: [PATCH 053/110] feature(registration): refactor 2 --- lib/main.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/main.dart b/lib/main.dart index 5cb4e31..7faced2 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -68,7 +68,7 @@ class MyApp extends StatelessWidget { theme: theme, title: 'Eatvio', routerConfig: AppRouter.appRouter, - debugShowCheckedModeBanner: true, + debugShowCheckedModeBanner: false, localizationsDelegates: [ AppLocalizationDelegate(), GlobalMaterialLocalizations.delegate, -- 2.49.1 From d49ce2120ac46a057595596492bff9d3089ab01e Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Sun, 14 Jul 2024 22:16:59 +0300 Subject: [PATCH 054/110] feature(registration): refactor i 2. --- .../selection_popup_model.dart | 25 ++- .../selection_popup_model.freezed.dart | 189 ++++++++++++++++++ .../pages/registration_screen.dart | 112 ++++++++--- .../glossary_screen/glossary_screen.dart | 2 +- .../date_of_birth_screen.dart | 155 +++++--------- .../gender_screen/gender_screen.dart | 148 ++++++-------- .../language_select_screen.dart | 20 +- .../registration/name_screen/name_screen.dart | 131 +++--------- lib/widgets/custom_drop_down.dart | 5 +- 9 files changed, 430 insertions(+), 357 deletions(-) create mode 100644 lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart diff --git a/lib/data/models/selectionPopupModel/selection_popup_model.dart b/lib/data/models/selectionPopupModel/selection_popup_model.dart index e9aa2c8..82c519c 100644 --- a/lib/data/models/selectionPopupModel/selection_popup_model.dart +++ b/lib/data/models/selectionPopupModel/selection_popup_model.dart @@ -1,15 +1,14 @@ -///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 0000000..917785c --- /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/features/registration/presentation/pages/registration_screen.dart b/lib/features/registration/presentation/pages/registration_screen.dart index 3ee6d0c..0f6a3bc 100644 --- a/lib/features/registration/presentation/pages/registration_screen.dart +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -171,11 +171,11 @@ class _RegistrationScreenState extends State { }); }, children: [ - LanguageSelectScreen(sheet: context.read().state.sheet), - CredentialsScreen(sheet: context.read().state.sheet), - NameScreen(), - GenderScreen(), - DateOfBirthScreen(), + LanguageSelectScreen(sheet: state.sheet), + CredentialsScreen(sheet: state.sheet), + NameScreen(sheet: state.sheet), + GenderScreen(sheet: state.sheet), + DateOfBirthScreen(sheet: state.sheet), CityOfLivingScreen(), BodyCircumferencesScreen(), WeightScreen(), @@ -197,38 +197,64 @@ class _RegistrationScreenState extends State { bool canGoNext(state) { switch (step) { - case 2: - List errors = validateFields(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 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, state.sheet.lastName); + // 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; + // } default: return true; } } - List validateFields(String email, String name, String password, String passwordConfirmation) { + List validateCredentialsFields(String email, String name, String password, String passwordConfirmation) { List errors = []; if (!isEmail(email)) { @@ -261,4 +287,26 @@ class _RegistrationScreenState extends State { 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/presentation/glossary/glossary_screen/glossary_screen.dart b/lib/presentation/glossary/glossary_screen/glossary_screen.dart index b421b87..35caec2 100644 --- a/lib/presentation/glossary/glossary_screen/glossary_screen.dart +++ b/lib/presentation/glossary/glossary_screen/glossary_screen.dart @@ -175,7 +175,7 @@ class GlossaryScreen extends StatelessWidget { ), CustomDropDown( items: state.productGroups, - defaultValue: state.productGroups?[0], + value: state.productGroups?[0], fillColor: Colors.grey[200]!, hintText: 'Выберите категорию', borderDecoration: OutlineInputBorder( 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 index 0952a66..49118ca 100644 --- 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 @@ -1,82 +1,49 @@ +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:flutter/cupertino.dart'; -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/data/models/userRegistrationModel/user_registration_model.dart'; -import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; class DateOfBirthScreen extends StatefulWidget { - const DateOfBirthScreen({Key? key}) : super(key: key); + final UserRegistrationSheet sheet; - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => DateOfBirthBloc( - DateOfBirthState( - dateOfBirthModelObj: DateOfBirthModel( - userRegistrationSheet: sheet, - ), - ), - )..add(DateOfBirthInitialEvent()), - child: DateOfBirthScreen(), - ); - } + const DateOfBirthScreen({super.key, required this.sheet}); @override State createState() => _DateOfBirthScreenState(); } class _DateOfBirthScreenState extends State { - DateTime selectedDate = DateTime.now(); + 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: BlocBuilder( - builder: (context, state) { - return 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), - // 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), - // ); - // }, - // ), - ], - ), - ); - }, + 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), + ], + ), ), ); } - onTapContinue(DateOfBirthState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.dateOfBirthModelObj!.userRegistrationSheet; - // sheet.birthdate = selectedDate.toString(); - GoRouter.of(context).goNamed('cityOfLivingScreen', extra: sheet); - }; - } - - - Function onTapBack(BuildContext context) { - return () { - onTapArrowLeft(context); - }; - } - /// Section Widget _buildDateInput(BuildContext context) { return Container( @@ -105,14 +72,16 @@ class _DateOfBirthScreenState extends State { onTapCalendar(BuildContext context) { return () { - // openDatePickerDialog(context); _showDialog( CupertinoDatePicker( initialDateTime: DateTime.now(), mode: CupertinoDatePickerMode.date, - onDateTimeChanged: (DateTime newTime) { + onDateTimeChanged: (DateTime newDateTime) { setState(() { - selectedDate = newTime; + selectedDate = newDateTime; + print(selectedDate); + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(birthdate: selectedDate.toString())); }); }, ), @@ -123,50 +92,26 @@ class _DateOfBirthScreenState extends State { 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, - ), - ), + 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, + ), + ), ); } - - /// 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/gender_screen/gender_screen.dart b/lib/presentation/registration/gender_screen/gender_screen.dart index 5ffa6be..803759d 100644 --- a/lib/presentation/registration/gender_screen/gender_screen.dart +++ b/lib/presentation/registration/gender_screen/gender_screen.dart @@ -1,111 +1,79 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/gender_bloc.dart'; -import 'models/gender_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:flutter/material.dart'; class GenderScreen extends StatefulWidget { - const GenderScreen({Key? key}) : super(key: key); + final UserRegistrationSheet sheet; - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => GenderBloc( - GenderState( - genderModelObj: GenderModel(userRegistrationSheet: sheet), - ), - )..add(GenderInitialEvent()), - child: GenderScreen(), - ); - } + 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: BlocBuilder( - builder: (context, state) { - return 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( - 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, - ), - ), - // 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), - // ); - // }, - // ), - ], + 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, + ), + ), + ], + ), ), ); } - - 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')); - }; - } - - - 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/language_select_screen/language_select_screen.dart b/lib/presentation/registration/language_select_screen/language_select_screen.dart index 1a0dc41..c770c0c 100644 --- a/lib/presentation/registration/language_select_screen/language_select_screen.dart +++ b/lib/presentation/registration/language_select_screen/language_select_screen.dart @@ -18,12 +18,14 @@ class _LanguageSelectScreenState extends State { SelectionPopupModel(id: 1, title: "Русский", isSelected: true), ]; - late SelectionPopupModel value; + SelectionPopupModel? value; @override void initState() { super.initState(); - value = SelectionPopupModel(title: widget.sheet.lang); + if (widget.sheet.lang.isNotEmpty) { + value = dropdownItemList.first; + } } @override @@ -45,23 +47,13 @@ class _LanguageSelectScreenState extends State { ), const SizedBox(height: 32), 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, - ), - ), + 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)); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(lang: value!.title)); }), ), ], diff --git a/lib/presentation/registration/name_screen/name_screen.dart b/lib/presentation/registration/name_screen/name_screen.dart index 8721d1f..dfd9a16 100644 --- a/lib/presentation/registration/name_screen/name_screen.dart +++ b/lib/presentation/registration/name_screen/name_screen.dart @@ -1,22 +1,27 @@ -import 'package:go_router/go_router.dart'; -import 'bloc/name_bloc.dart'; -import 'models/name_model.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/core/app_export.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); +class NameScreen extends StatefulWidget { + final UserRegistrationSheet sheet; - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => NameBloc( - NameState( - nameModelObj: NameModel(userRegistrationSheet: sheet), - ), - )..add(NameInitialEvent()), - child: NameScreen(), - ); + 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 @@ -32,101 +37,27 @@ class NameScreen extends StatelessWidget { SizedBox(height: 16.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); + 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), - BlocSelector( - selector: (state) => state.lastNameController, - builder: (context, lastNameController) { - return CustomTextFormField( - controller: lastNameController, - ); + CustomTextFormField( + controller: lastNameController, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(lastName: newValue)); }, - ), - // 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 - // ); - // }, - // ), + ) ], ), ), ); } - - - /// 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/widgets/custom_drop_down.dart b/lib/widgets/custom_drop_down.dart index 09fdbba..ff80bac 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) { -- 2.49.1 From 4780caf38918b2af2299f3b86ff72bb9be57a18f Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Sun, 14 Jul 2024 22:21:30 +0300 Subject: [PATCH 055/110] feature(registration): refactor i 3. --- .../pages/registration_screen.dart | 104 +++++++++--------- 1 file changed, 52 insertions(+), 52 deletions(-) diff --git a/lib/features/registration/presentation/pages/registration_screen.dart b/lib/features/registration/presentation/pages/registration_screen.dart index 0f6a3bc..534ea11 100644 --- a/lib/features/registration/presentation/pages/registration_screen.dart +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -197,58 +197,58 @@ class _RegistrationScreenState extends State { bool canGoNext(state) { 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, state.sheet.lastName); - // 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 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, state.sheet.lastName); + 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; + } default: return true; } -- 2.49.1 From 8cf2388b18284ac8aad8910d64acbe4ecc032ab0 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Mon, 15 Jul 2024 11:19:29 +0300 Subject: [PATCH 056/110] feature(registration): refactor i 4 --- flutter_01.log | 97 +++++++++ .../pages/registration_screen.dart | 64 +++++- .../additional_information_screen.dart | 19 +- .../allergies_screen/allergies_screen.dart | 64 +++--- .../blood_pressure_screen.dart | 10 +- .../body_circumferences_screen.dart | 199 ++++++------------ .../city_of_living_screen.dart | 193 +++++++++-------- .../favorite_foods_screen.dart | 11 +- .../favorite_sports_screen.dart | 11 +- .../height_screen/height_screen.dart | 18 +- .../medicine_intake_screen.dart | 11 +- .../weight_screen/weight_screen.dart | 10 +- 12 files changed, 365 insertions(+), 342 deletions(-) create mode 100644 flutter_01.log diff --git a/flutter_01.log b/flutter_01.log new file mode 100644 index 0000000..f7f3c20 --- /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/features/registration/presentation/pages/registration_screen.dart b/lib/features/registration/presentation/pages/registration_screen.dart index 534ea11..3f3da55 100644 --- a/lib/features/registration/presentation/pages/registration_screen.dart +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -176,16 +176,16 @@ class _RegistrationScreenState extends State { NameScreen(sheet: state.sheet), GenderScreen(sheet: state.sheet), DateOfBirthScreen(sheet: state.sheet), - CityOfLivingScreen(), - BodyCircumferencesScreen(), - WeightScreen(), - HeightScreen(), - BloodPressureScreen(), - AllergiesScreen(), - MedicineIntakeScreen(), - FavoriteSportsScreen(), - FavoriteFoodsScreen(), - AdditionalInformationScreen(), + 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), ], ), ), @@ -234,6 +234,32 @@ class _RegistrationScreenState extends State { 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, state.sheet.waistCircumference, state.sheet.hipCircumference); + if (errors.isEmpty) { + return true; + } else { + String errorMessage = ''; + + for (var error in errors) { + errorMessage += error + '\n\n'; + } + showDialog( context: context, builder: (context) => AlertDialog( @@ -254,6 +280,24 @@ class _RegistrationScreenState extends State { } } + 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 = []; diff --git a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart index c12af1f..32fbd61 100644 --- a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart +++ b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart @@ -1,7 +1,6 @@ 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/custom_text_form_field.dart'; import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; @@ -11,18 +10,16 @@ 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); +class AdditionalInformationScreen extends StatefulWidget { + final UserRegistrationSheet sheet; - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => - AdditionalInformationBloc(AdditionalInformationState(additionalInformationModelObj: AdditionalInformationModel(userRegistrationSheet: sheet))) - ..add(AdditionalInformationInitialEvent()), - child: AdditionalInformationScreen(), - ); - } + const AdditionalInformationScreen({super.key, required this.sheet}); + @override + State createState() => _AdditionalInformationScreenState(); +} + +class _AdditionalInformationScreenState extends State { @override Widget build(BuildContext context) { return SingleChildScrollView( diff --git a/lib/presentation/registration/allergies_screen/allergies_screen.dart b/lib/presentation/registration/allergies_screen/allergies_screen.dart index 7a2ac1c..56702d9 100644 --- a/lib/presentation/registration/allergies_screen/allergies_screen.dart +++ b/lib/presentation/registration/allergies_screen/allergies_screen.dart @@ -1,6 +1,7 @@ import 'package:go_router/go_router.dart'; import 'bloc/allergies_bloc.dart'; +// ignore: unused_import import 'models/allergies_model.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; @@ -8,14 +9,9 @@ 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); + final UserRegistrationSheet sheet; - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => AllergiesBloc(AllergiesState(allergiesModelObj: AllergiesModel(userRegistrationSheet: sheet)))..add(AllergiesInitialEvent()), - child: AllergiesScreen(), - ); - } + const AllergiesScreen({super.key, required this.sheet}); @override State createState() => _AllergiesScreenState(); @@ -27,33 +23,33 @@ class _AllergiesScreenState extends State { 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), - _buildTextFormField(context), - // 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), - // ); - // }, - // ), - ], - ), + 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), + _buildTextFormField(context), + // 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), + // ); + // }, + // ), + ], + ), ), ); } diff --git a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart b/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart index d8efedd..d5c2468 100644 --- a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart +++ b/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart @@ -11,15 +11,9 @@ import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_m import 'package:flutter/material.dart'; class BloodPressureScreen extends StatefulWidget { - const BloodPressureScreen({Key? key}) : super(key: key); + final UserRegistrationSheet sheet; - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => - BloodPressureBloc(BloodPressureState(bloodPressureModelObj: BloodPressureModel(userRegistrationSheet: sheet)))..add(BloodPressureInitialEvent()), - child: BloodPressureScreen(), - ); - } + const BloodPressureScreen({super.key, required this.sheet}); @override State createState() => _BloodPressureScreenState(); diff --git a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart b/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart index 60733e3..60576c8 100644 --- a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart +++ b/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart @@ -1,23 +1,15 @@ -import 'package:go_router/go_router.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.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/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 StatefulWidget { - const BodyCircumferencesScreen({Key? key}) : super(key: key); + final UserRegistrationSheet sheet; - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => BodyCircumferencesBloc(BodyCircumferencesState(bodyCircumferencesModelObj: BodyCircumferencesModel(userRegistrationSheet: sheet))) - ..add(BodyCircumferencesInitialEvent()), - child: BodyCircumferencesScreen(), - ); - } + const BodyCircumferencesScreen({super.key, required this.sheet}); @override State createState() => _BodyCircumferencesScreenState(); @@ -25,139 +17,72 @@ class BodyCircumferencesScreen extends StatefulWidget { class _BodyCircumferencesScreenState extends State { final digitsOnly = FilteringTextInputFormatter.digitsOnly; + final chestCircumferenceController = TextEditingController(); + final waistCircumferenceController = TextEditingController(); + final hipCircumferenceController = TextEditingController(); + + @override + void initState() { + super.initState(); + chestCircumferenceController.text = widget.sheet.chestCircumference; + waistCircumferenceController.text = widget.sheet.waistCircumference; + hipCircumferenceController.text = widget.sheet.hipCircumference; + } @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), - 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, - ); - }, - ), - // 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), - // ); - // }, - // ), - ], - ), + 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: 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: 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: value)); + }, + ), + ], + ), ), ); } - - 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); - }; - } - - - 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/city_of_living_screen/city_of_living_screen.dart b/lib/presentation/registration/city_of_living_screen/city_of_living_screen.dart index f5ee8a8..1e5f01b 100644 --- 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 @@ -1,3 +1,4 @@ +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:go_router/go_router.dart'; import 'bloc/city_of_living_bloc.dart'; @@ -8,108 +9,101 @@ 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); +class CityOfLivingScreen extends StatefulWidget { + final UserRegistrationSheet sheet; - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => - CityOfLivingBloc(CityOfLivingState(cityOfLivingModelObj: CityOfLivingModel(userRegistrationSheet: sheet)))..add(CityOfLivingInitialEvent()), - child: CityOfLivingScreen(), - ); - } + const CityOfLivingScreen({super.key, required this.sheet}); + @override + State createState() => _CityOfLivingScreenState(); +} + +class _CityOfLivingScreenState extends State { @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), - 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), - ), - ); - }, + return BlocProvider( + create: (BuildContext context) => + CityOfLivingBloc(CityOfLivingState(cityOfLivingModelObj: CityOfLivingModel(userRegistrationSheet: widget.sheet)))..add(CityOfLivingInitialEvent()), + child: 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), + 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), + ), + ); + }, + ), ), ), - ), - ); - }, - ); - }, - ), - // 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), - // ); - // }, - // ), - ], + ); + }, + ); + }, + ), + ], + ), ), ), ); @@ -125,10 +119,11 @@ class CityOfLivingScreen extends StatelessWidget { onDropDownChange(BuildContext context) { return (value) { context.read().add(ChangeDropDownEvent(value: value)); + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(country: value)); }; } - Function onTapBack(BuildContext context) { return () { onTapArrowLeft(context); @@ -141,8 +136,10 @@ class CityOfLivingScreen extends StatelessWidget { } } -selectProduct(AutocompleteOnSelected onSelected, String option, CityOfLivingState state) { +selectProduct(AutocompleteOnSelected onSelected, String option, CityOfLivingState state, BuildContext context) { state.cityController?.text = option; + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(city: option)); return () { onSelected(option); }; diff --git a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart b/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart index 0db859d..b4f54d9 100644 --- a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart +++ b/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart @@ -1,22 +1,15 @@ 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/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); + final UserRegistrationSheet sheet; - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => - FavoriteFoodsBloc(FavoriteFoodsState(favoriteFoodsModelObj: FavoriteFoodsModel(userRegistrationSheet: sheet)))..add(FavoriteFoodsInitialEvent()), - child: FavoriteFoodsScreen(), - ); - } + const FavoriteFoodsScreen({super.key, required this.sheet}); @override State createState() => _FavoriteFoodsScreenState(); diff --git a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart b/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart index 5d8be5d..fd3a42f 100644 --- a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart +++ b/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart @@ -1,6 +1,7 @@ import 'package:go_router/go_router.dart'; import 'bloc/favorite_sports_bloc.dart'; +// ignore: unused_import import 'models/favorite_sports_model.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; @@ -8,15 +9,9 @@ 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); + final UserRegistrationSheet sheet; - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => - FavoriteSportsBloc(FavoriteSportsState(favoriteSportsModelObj: FavoriteSportsModel(userRegistrationSheet: sheet)))..add(FavoriteSportsInitialEvent()), - child: FavoriteSportsScreen(), - ); - } + const FavoriteSportsScreen({super.key, required this.sheet}); @override State createState() => _FavoriteSportsScreenState(); diff --git a/lib/presentation/registration/height_screen/height_screen.dart b/lib/presentation/registration/height_screen/height_screen.dart index 1e0b88b..a41dad9 100644 --- a/lib/presentation/registration/height_screen/height_screen.dart +++ b/lib/presentation/registration/height_screen/height_screen.dart @@ -1,23 +1,22 @@ 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/custom_text_form_field.dart'; import 'package:flutter/services.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); +class HeightScreen extends StatefulWidget { + final UserRegistrationSheet sheet; - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => HeightBloc(HeightState(heightModelObj: HeightModel(userRegistrationSheet: sheet)))..add(HeightInitialEvent()), - child: HeightScreen(), - ); - } + const HeightScreen({super.key, required this.sheet}); + @override + State createState() => _HeightScreenState(); +} + +class _HeightScreenState extends State { @override Widget build(BuildContext context) { return SingleChildScrollView( @@ -67,7 +66,6 @@ class HeightScreen extends StatelessWidget { }; } - Function onTapBack(BuildContext context) { return () { onTapArrowLeft(context); diff --git a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart b/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart index 4934d31..5ccc203 100644 --- a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart +++ b/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart @@ -1,22 +1,15 @@ 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/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); + final UserRegistrationSheet sheet; - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => - MedicineIntakeBloc(MedicineIntakeState(medicineIntakeModelObj: MedicineIntakeModel(userRegistrationSheet: sheet)))..add(MedicineIntakeInitialEvent()), - child: MedicineIntakeScreen(), - ); - } + const MedicineIntakeScreen({super.key, required this.sheet}); @override State createState() => _MedicineIntakeScreenState(); diff --git a/lib/presentation/registration/weight_screen/weight_screen.dart b/lib/presentation/registration/weight_screen/weight_screen.dart index 2fe886b..f65f0f3 100644 --- a/lib/presentation/registration/weight_screen/weight_screen.dart +++ b/lib/presentation/registration/weight_screen/weight_screen.dart @@ -1,7 +1,6 @@ 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/custom_text_form_field.dart'; import 'package:flutter/services.dart'; @@ -9,14 +8,9 @@ import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_m import 'package:flutter/material.dart'; class WeightScreen extends StatelessWidget { - const WeightScreen({Key? key}) : super(key: key); + final UserRegistrationSheet sheet; - static Widget builder(BuildContext context, sheet) { - return BlocProvider( - create: (context) => WeightBloc(WeightState(weightModelObj: WeightModel(userRegistrationSheet: sheet)))..add(WeightInitialEvent()), - child: WeightScreen(), - ); - } + const WeightScreen({super.key, required this.sheet}); @override Widget build(BuildContext context) { -- 2.49.1 From b4993c827c64a0e477642e2b9cb570c6210c4817 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Mon, 15 Jul 2024 11:46:32 +0300 Subject: [PATCH 057/110] fix(diary): UI errors fix --- .../diary/presentation/bloc/diary_bloc.dart | 19 +- .../diary/presentation/bloc/diary_event.dart | 8 - .../diary/presentation/bloc/diary_state.dart | 7 +- .../bloc/diary_state.freezed.dart | 397 ++++++++++-------- .../presentation/pages/diary_screen.dart | 28 +- 5 files changed, 248 insertions(+), 211 deletions(-) diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index 9cc1b77..6bef493 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -58,11 +58,19 @@ class DiaryBloc extends Bloc { final int? diaryID = data['id']; final DiaryModel diary = await diaryRepository.getDiary(diaryID ?? 45); final Meal currentMeal = diary.meals[0]; + List portions = [ + SelectionPopupModel(title: "gr"), + SelectionPopupModel(title: "pcs") + ]; emit(DiaryState.loaded( diary: diary, currentMeal: currentMeal, portions: currentMeal.portions, photos: currentMeal.photos, + portionList: portions, + portionController: portions[0], + selectedMood: 3, + selectedSatiety: 3, commentController: TextEditingController(), productNameController: TextEditingController(), productQuantityController: TextEditingController(), @@ -159,7 +167,8 @@ class DiaryBloc extends Bloc { 'Satiety change success! meal_id: ${currentState.currentMeal.id}, mood: ${event.selectedElement}', ); emit(updatedState); // Передаем обновленное состояние в emit - } + } else + print("dad"); } } @@ -435,9 +444,9 @@ class DiaryBloc extends Bloc { var currentState = state as DiaryStateLoaded; var response = await sendPortionData( - currentState.productNameController?.text, - currentState.portionController?.id == 0 ? 'pcs' : 'gr', - int.parse(currentState.productQuantityController!.text), + currentState.productNameController.text, + currentState.portionController.id == 0 ? 'pcs' : 'gr', + int.parse(currentState.productQuantityController.text), currentState.currentMeal.id, currentState.diary.id, ); @@ -623,7 +632,7 @@ class DiaryBloc extends Bloc { currentState.diary.id, currentState.wakeupController, currentState.retireController, - currentState.commentController?.text, + currentState.commentController.text, ); if (response.statusCode == 200) { diff --git a/lib/features/diary/presentation/bloc/diary_event.dart b/lib/features/diary/presentation/bloc/diary_event.dart index 6568873..91445ff 100644 --- a/lib/features/diary/presentation/bloc/diary_event.dart +++ b/lib/features/diary/presentation/bloc/diary_event.dart @@ -20,7 +20,6 @@ class ChangeSatiety extends DiaryEvent { this.selectedElement, ); final int selectedElement; - @override List get props => [selectedElement]; } @@ -30,7 +29,6 @@ class ChangeMood extends DiaryEvent { this.selectedElement, ); final int selectedElement; - @override List get props => [selectedElement]; } @@ -38,7 +36,6 @@ class ChangeMood extends DiaryEvent { class ChangeMealTime extends DiaryEvent { ChangeMealTime(this.time); final TimeOfDay time; - @override List get props => [time]; } @@ -47,7 +44,6 @@ class AddComment extends DiaryEvent { AddComment(this.diaryId, this.comment); final String comment; final int diaryId; - @override List get props => [comment, diaryId]; } @@ -115,7 +111,6 @@ class ProductInput extends DiaryEvent { class ChangeMeal extends DiaryEvent { ChangeMeal({required this.value, required this.meals}); - Meal value; List? meals; @override @@ -124,7 +119,6 @@ class ChangeMeal extends DiaryEvent { class ClearInput extends DiaryEvent { ClearInput({required this.value}); - TextEditingController value; @override List get props => [value]; @@ -132,7 +126,6 @@ class ClearInput extends DiaryEvent { class ChangePortion extends DiaryEvent { ChangePortion({required this.value}); - SelectionPopupModel value; @override List get props => [value]; @@ -140,7 +133,6 @@ class ChangePortion extends DiaryEvent { class FinishDay extends DiaryEvent { FinishDay(); - @override List get props => []; } diff --git a/lib/features/diary/presentation/bloc/diary_state.dart b/lib/features/diary/presentation/bloc/diary_state.dart index 4f32447..957dafc 100644 --- a/lib/features/diary/presentation/bloc/diary_state.dart +++ b/lib/features/diary/presentation/bloc/diary_state.dart @@ -23,8 +23,9 @@ abstract class DiaryState with _$DiaryState { required List consumedChartValues, required List portions, required List photos, + required List portionList, required Meal currentMeal, - SelectionPopupModel? portionController, + required SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, @@ -35,8 +36,8 @@ abstract class DiaryState with _$DiaryState { required TextEditingController fatsController, required TextEditingController proteinsController, required TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + required int selectedMood, + required int selectedSatiety, required bool wakeupExpanded, required bool moderationExpanded, required bool moodExpanded, diff --git a/lib/features/diary/presentation/bloc/diary_state.freezed.dart b/lib/features/diary/presentation/bloc/diary_state.freezed.dart index 6a06e2e..5acd8d2 100644 --- a/lib/features/diary/presentation/bloc/diary_state.freezed.dart +++ b/lib/features/diary/presentation/bloc/diary_state.freezed.dart @@ -28,18 +28,19 @@ mixin _$DiaryState { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, @@ -63,18 +64,19 @@ mixin _$DiaryState { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, @@ -98,18 +100,19 @@ mixin _$DiaryState { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, @@ -215,18 +218,19 @@ class _$DiaryStateImpl implements _DiaryState { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, @@ -253,18 +257,19 @@ class _$DiaryStateImpl implements _DiaryState { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, @@ -291,18 +296,19 @@ class _$DiaryStateImpl implements _DiaryState { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, @@ -410,18 +416,19 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, @@ -448,18 +455,19 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, @@ -486,18 +494,19 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, @@ -571,18 +580,19 @@ abstract class _$$DiaryStateLoadedImplCopyWith<$Res> { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, @@ -613,18 +623,19 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> Object? consumedChartValues = null, Object? portions = null, Object? photos = null, + Object? portionList = null, Object? currentMeal = null, - Object? portionController = freezed, + Object? portionController = null, Object? wakeupController = freezed, Object? retireController = freezed, Object? mealTimeController = freezed, - Object? commentController = freezed, - Object? productNameController = freezed, - Object? productQuantityController = freezed, - Object? caloriesController = freezed, - Object? fatsController = freezed, - Object? proteinsController = freezed, - Object? carbsController = freezed, + Object? commentController = null, + Object? productNameController = null, + Object? productQuantityController = null, + Object? caloriesController = null, + Object? fatsController = null, + Object? proteinsController = null, + Object? carbsController = null, Object? selectedMood = freezed, Object? selectedSatiety = freezed, Object? wakeupExpanded = null, @@ -662,14 +673,18 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> ? _value._photos : photos // ignore: cast_nullable_to_non_nullable as List, + portionList: null == portionList + ? _value._portionList + : portionList // ignore: cast_nullable_to_non_nullable + as List, currentMeal: null == currentMeal ? _value.currentMeal : currentMeal // ignore: cast_nullable_to_non_nullable as Meal, - portionController: freezed == portionController + portionController: null == portionController ? _value.portionController : portionController // ignore: cast_nullable_to_non_nullable - as SelectionPopupModel?, + as SelectionPopupModel, wakeupController: freezed == wakeupController ? _value.wakeupController : wakeupController // ignore: cast_nullable_to_non_nullable @@ -682,34 +697,34 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> ? _value.mealTimeController : mealTimeController // ignore: cast_nullable_to_non_nullable as TimeOfDay?, - commentController: freezed == commentController + commentController: null == commentController ? _value.commentController : commentController // ignore: cast_nullable_to_non_nullable - as TextEditingController?, - productNameController: freezed == productNameController + as TextEditingController, + productNameController: null == productNameController ? _value.productNameController : productNameController // ignore: cast_nullable_to_non_nullable - as TextEditingController?, - productQuantityController: freezed == productQuantityController + as TextEditingController, + productQuantityController: null == productQuantityController ? _value.productQuantityController : productQuantityController // ignore: cast_nullable_to_non_nullable - as TextEditingController?, - caloriesController: freezed == caloriesController + as TextEditingController, + caloriesController: null == caloriesController ? _value.caloriesController : caloriesController // ignore: cast_nullable_to_non_nullable - as TextEditingController?, - fatsController: freezed == fatsController + as TextEditingController, + fatsController: null == fatsController ? _value.fatsController : fatsController // ignore: cast_nullable_to_non_nullable - as TextEditingController?, - proteinsController: freezed == proteinsController + as TextEditingController, + proteinsController: null == proteinsController ? _value.proteinsController : proteinsController // ignore: cast_nullable_to_non_nullable - as TextEditingController?, - carbsController: freezed == carbsController + as TextEditingController, + carbsController: null == carbsController ? _value.carbsController : carbsController // ignore: cast_nullable_to_non_nullable - as TextEditingController?, + as TextEditingController, selectedMood: freezed == selectedMood ? _value.selectedMood : selectedMood // ignore: cast_nullable_to_non_nullable @@ -769,8 +784,9 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { required final List consumedChartValues, required final List portions, required final List photos, + required final List portionList, required this.currentMeal, - this.portionController, + required this.portionController, this.wakeupController, this.retireController, this.mealTimeController, @@ -792,7 +808,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { _recommendedChartValues = recommendedChartValues, _consumedChartValues = consumedChartValues, _portions = portions, - _photos = photos; + _photos = photos, + _portionList = portionList; @override final DiaryModel diary; @@ -841,10 +858,18 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { return EqualUnmodifiableListView(_photos); } + final List _portionList; + @override + List get portionList { + if (_portionList is EqualUnmodifiableListView) return _portionList; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_portionList); + } + @override final Meal currentMeal; @override - final SelectionPopupModel? portionController; + final SelectionPopupModel portionController; @override final TimeOfDay? wakeupController; @override @@ -852,19 +877,19 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { @override final TimeOfDay? mealTimeController; @override - final TextEditingController? commentController; + final TextEditingController commentController; @override - final TextEditingController? productNameController; + final TextEditingController productNameController; @override - final TextEditingController? productQuantityController; + final TextEditingController productQuantityController; @override - final TextEditingController? caloriesController; + final TextEditingController caloriesController; @override - final TextEditingController? fatsController; + final TextEditingController fatsController; @override - final TextEditingController? proteinsController; + final TextEditingController proteinsController; @override - final TextEditingController? carbsController; + final TextEditingController carbsController; @override final int? selectedMood; @override @@ -882,7 +907,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { @override String toString() { - return 'DiaryState.loaded(diary: $diary, diaryDate: $diaryDate, autocompleteList: $autocompleteList, recommendedChartValues: $recommendedChartValues, consumedChartValues: $consumedChartValues, portions: $portions, photos: $photos, currentMeal: $currentMeal, portionController: $portionController, wakeupController: $wakeupController, retireController: $retireController, mealTimeController: $mealTimeController, commentController: $commentController, productNameController: $productNameController, productQuantityController: $productQuantityController, caloriesController: $caloriesController, fatsController: $fatsController, proteinsController: $proteinsController, carbsController: $carbsController, selectedMood: $selectedMood, selectedSatiety: $selectedSatiety, wakeupExpanded: $wakeupExpanded, moderationExpanded: $moderationExpanded, moodExpanded: $moodExpanded, isLoading: $isLoading, isAdded: $isAdded)'; + return 'DiaryState.loaded(diary: $diary, diaryDate: $diaryDate, autocompleteList: $autocompleteList, recommendedChartValues: $recommendedChartValues, consumedChartValues: $consumedChartValues, portions: $portions, photos: $photos, portionList: $portionList, currentMeal: $currentMeal, portionController: $portionController, wakeupController: $wakeupController, retireController: $retireController, mealTimeController: $mealTimeController, commentController: $commentController, productNameController: $productNameController, productQuantityController: $productQuantityController, caloriesController: $caloriesController, fatsController: $fatsController, proteinsController: $proteinsController, carbsController: $carbsController, selectedMood: $selectedMood, selectedSatiety: $selectedSatiety, wakeupExpanded: $wakeupExpanded, moderationExpanded: $moderationExpanded, moodExpanded: $moodExpanded, isLoading: $isLoading, isAdded: $isAdded)'; } @override @@ -901,6 +926,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { .equals(other._consumedChartValues, _consumedChartValues) && const DeepCollectionEquality().equals(other._portions, _portions) && const DeepCollectionEquality().equals(other._photos, _photos) && + const DeepCollectionEquality() + .equals(other._portionList, _portionList) && (identical(other.currentMeal, currentMeal) || other.currentMeal == currentMeal) && (identical(other.portionController, portionController) || @@ -951,6 +978,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { const DeepCollectionEquality().hash(_consumedChartValues), const DeepCollectionEquality().hash(_portions), const DeepCollectionEquality().hash(_photos), + const DeepCollectionEquality().hash(_portionList), currentMeal, portionController, wakeupController, @@ -992,18 +1020,19 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, @@ -1022,6 +1051,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { consumedChartValues, portions, photos, + portionList, currentMeal, portionController, wakeupController, @@ -1056,18 +1086,19 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, @@ -1086,6 +1117,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { consumedChartValues, portions, photos, + portionList, currentMeal, portionController, wakeupController, @@ -1120,18 +1152,19 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, @@ -1152,6 +1185,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { consumedChartValues, portions, photos, + portionList, currentMeal, portionController, wakeupController, @@ -1222,18 +1256,19 @@ abstract class DiaryStateLoaded implements DiaryState { required final List consumedChartValues, required final List portions, required final List photos, + required final List portionList, required final Meal currentMeal, - final SelectionPopupModel? portionController, + required final SelectionPopupModel portionController, final TimeOfDay? wakeupController, final TimeOfDay? retireController, final TimeOfDay? mealTimeController, - required final TextEditingController? commentController, - required final TextEditingController? productNameController, - required final TextEditingController? productQuantityController, - required final TextEditingController? caloriesController, - required final TextEditingController? fatsController, - required final TextEditingController? proteinsController, - required final TextEditingController? carbsController, + required final TextEditingController commentController, + required final TextEditingController productNameController, + required final TextEditingController productQuantityController, + required final TextEditingController caloriesController, + required final TextEditingController fatsController, + required final TextEditingController proteinsController, + required final TextEditingController carbsController, final int? selectedMood, final int? selectedSatiety, required final bool wakeupExpanded, @@ -1249,18 +1284,19 @@ abstract class DiaryStateLoaded implements DiaryState { List get consumedChartValues; List get portions; List get photos; + List get portionList; Meal get currentMeal; - SelectionPopupModel? get portionController; + SelectionPopupModel get portionController; TimeOfDay? get wakeupController; TimeOfDay? get retireController; TimeOfDay? get mealTimeController; - TextEditingController? get commentController; - TextEditingController? get productNameController; - TextEditingController? get productQuantityController; - TextEditingController? get caloriesController; - TextEditingController? get fatsController; - TextEditingController? get proteinsController; - TextEditingController? get carbsController; + TextEditingController get commentController; + TextEditingController get productNameController; + TextEditingController get productQuantityController; + TextEditingController get caloriesController; + TextEditingController get fatsController; + TextEditingController get proteinsController; + TextEditingController get carbsController; int? get selectedMood; int? get selectedSatiety; bool get wakeupExpanded; @@ -1349,18 +1385,19 @@ class _$DiaryStateErrorImpl implements DiaryStateError { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, @@ -1387,18 +1424,19 @@ class _$DiaryStateErrorImpl implements DiaryStateError { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, @@ -1425,18 +1463,19 @@ class _$DiaryStateErrorImpl implements DiaryStateError { List consumedChartValues, List portions, List photos, + List portionList, Meal currentMeal, - SelectionPopupModel? portionController, + SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, - TextEditingController? commentController, - TextEditingController? productNameController, - TextEditingController? productQuantityController, - TextEditingController? caloriesController, - TextEditingController? fatsController, - TextEditingController? proteinsController, - TextEditingController? carbsController, + TextEditingController commentController, + TextEditingController productNameController, + TextEditingController productQuantityController, + TextEditingController caloriesController, + TextEditingController fatsController, + TextEditingController proteinsController, + TextEditingController carbsController, int? selectedMood, int? selectedSatiety, bool wakeupExpanded, diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index af39f0b..8dcdbb7 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -342,9 +342,10 @@ class DiaryScreen extends StatelessWidget { return null; }, builder: (context, diary) { + List meals = mealsToDropdown(diary!.meals); return CustomDropDown( - hintText: "Прием пищи", - items: mealsToDropdown(diary!.meals), + hintText: meals[0].title, + items: meals, contentPadding: EdgeInsets.symmetric( horizontal: 10.h, vertical: 9.v, @@ -442,10 +443,8 @@ class DiaryScreen extends StatelessWidget { }, builder: (context, diary) { return CustomDropDown( - items: [ - SelectionPopupModel(title: "gr"), - SelectionPopupModel(title: "pcs") - ], + items: state.portionList, + defaultValue: state.portionController, onChanged: changePortion(context, state), ); }, @@ -576,11 +575,11 @@ class DiaryScreen extends StatelessWidget { TextButton( onPressed: triggerModeration( context, - state.productNameController!.text, - state.caloriesController!.text, - state.proteinsController!.text, - state.fatsController!.text, - state.carbsController!.text, + state.productNameController.text, + state.caloriesController.text, + state.proteinsController.text, + state.fatsController.text, + state.carbsController.text, dialogContext, ), child: Text('Отправить'), @@ -630,7 +629,7 @@ class DiaryScreen extends StatelessWidget { selectProduct(AutocompleteOnSelected onSelected, String option, DiaryStateLoaded state) { - state.productNameController?.text = option; + state.productNameController.text = option; return () { onSelected(option); }; @@ -638,9 +637,6 @@ class DiaryScreen extends StatelessWidget { getAutocomplete(BuildContext context, FocusNode focusNode) { return (value) { - /*print(state.autocompleteList - ?.map((dynamic item) => item as String) - .toList());*/ if (value.length > 2) { context.read().add(ProductInput(value)); } @@ -663,7 +659,7 @@ class DiaryScreen extends StatelessWidget { }; } - changePortion(BuildContext context, DiaryState state) { + changePortion(BuildContext context, DiaryStateLoaded state) { return (value) { context.read().add(ChangePortion(value: value)); }; -- 2.49.1 From ee37f02d78e1aa0612e0e769762b9cbdca19e62b Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Mon, 15 Jul 2024 12:45:52 +0300 Subject: [PATCH 058/110] feature(registration): refactor i5 --- .../registration_cubit.dart | 14 +- .../pages/registration_screen.dart | 6 +- .../repositories/registration_repository.dart | 16 + .../services/registration_service.dart | 15 + .../services/registration_service.g.dart | 74 ++++ lib/locator_service.dart | 6 + .../additional_information_screen.dart | 146 ++------ .../allergies_screen/allergies_screen.dart | 92 ++--- .../bloc/blood_pressure_bloc.dart | 23 +- .../blood_pressure_screen.dart | 321 +++++++----------- .../favorite_foods_screen.dart | 127 ++----- .../favorite_sports_screen.dart | 93 ++--- .../height_screen/height_screen.dart | 52 ++- .../medicine_intake_screen.dart | 99 ++---- .../weight_screen/weight_screen.dart | 104 +++--- 15 files changed, 470 insertions(+), 718 deletions(-) create mode 100644 lib/features/registration/repositories/registration_repository.dart create mode 100644 lib/features/registration/services/registration_service.dart create mode 100644 lib/features/registration/services/registration_service.g.dart diff --git a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart index 5e59454..e882ead 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart @@ -1,10 +1,22 @@ 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_state.dart'; +import 'package:eatvio_app/features/registration/repositories/registration_repository.dart'; import 'package:eatvio_app/presentation/registration/language_select_screen/models/language_select_model.dart'; class RegistrationCubit extends Cubit { - RegistrationCubit() : super(RegistrationState(sheet: LanguageSelectModel().userRegistrationSheet)); + final RegistrationRepository registrationRepository; + + RegistrationCubit({required this.registrationRepository}) : super(RegistrationState(sheet: LanguageSelectModel().userRegistrationSheet)); updateSheet(UserRegistrationSheet sheet) => emit(RegistrationState(sheet: sheet)); + + tryRegistration() async { + try { + final response = await registrationRepository.tryRegister(state.sheet); + print(response); + } catch (e) { + print(e); + } + } } diff --git a/lib/features/registration/presentation/pages/registration_screen.dart b/lib/features/registration/presentation/pages/registration_screen.dart index 3f3da55..074d67f 100644 --- a/lib/features/registration/presentation/pages/registration_screen.dart +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -1,6 +1,7 @@ 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/locator_service.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'; @@ -62,7 +63,7 @@ class _RegistrationScreenState extends State { @override Widget build(BuildContext context) { return BlocProvider( - create: (BuildContext context) => RegistrationCubit(), + create: (BuildContext context) => sl(), child: BlocBuilder( builder: (BuildContext context, RegistrationState state) { return PopScope( @@ -275,6 +276,9 @@ class _RegistrationScreenState extends State { ); return false; } + case 15: + context.read().tryRegistration(); + return true; default: return true; } diff --git a/lib/features/registration/repositories/registration_repository.dart b/lib/features/registration/repositories/registration_repository.dart new file mode 100644 index 0000000..bbaf43f --- /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}); + + tryRegister(UserRegistrationSheet sheet) async { + try { + return await registrationService.register(sheet: sheet); + } catch (e) { + rethrow; + } + } +} \ No newline at end of file diff --git a/lib/features/registration/services/registration_service.dart b/lib/features/registration/services/registration_service.dart new file mode 100644 index 0000000..f7c41ec --- /dev/null +++ b/lib/features/registration/services/registration_service.dart @@ -0,0 +1,15 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:retrofit/retrofit.dart'; + +part 'registration_service.g.dart'; + +@RestApi() +abstract class RegistrationService { + factory RegistrationService(Dio dio, {String baseUrl}) = _RegistrationService; + + @POST('/register') + Future register({ + @Body() required UserRegistrationSheet 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 0000000..4414079 --- /dev/null +++ b/lib/features/registration/services/registration_service.g.dart @@ -0,0 +1,74 @@ +// 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 UserRegistrationSheet sheet}) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + final _data = sheet; + await _dio.fetch(_setStreamType(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/register', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + } + + 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/locator_service.dart b/lib/locator_service.dart index dfd6198..dc09164 100644 --- a/lib/locator_service.dart +++ b/lib/locator_service.dart @@ -11,6 +11,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: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:flutter_dotenv/flutter_dotenv.dart'; import 'package:get_it/get_it.dart'; @@ -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,11 +34,13 @@ 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( diff --git a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart index 32fbd61..ec4578c 100644 --- a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart +++ b/lib/presentation/registration/additional_information_screen/additional_information_screen.dart @@ -1,14 +1,8 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/additional_information_bloc.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/core/app_export.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 StatefulWidget { final UserRegistrationSheet sheet; @@ -20,6 +14,14 @@ class AdditionalInformationScreen extends StatefulWidget { } class _AdditionalInformationScreenState extends State { + final editTextController = TextEditingController(); + + @override + void initState() { + super.initState(); + editTextController.text = widget.sheet.additionalInfo; + } + @override Widget build(BuildContext context) { return SingleChildScrollView( @@ -29,117 +31,31 @@ class _AdditionalInformationScreenState extends State( - // 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), - // ); - // }, - // ), + 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)); + }, + ), ], ), ), ); } - - 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']); - } - }; - } - - onTapBack(BuildContext context) { - return () { - onTapArrowLeft(context); - }; - } - - /// Section Widget - _buildTextFormField(BuildContext context) { - return SizedBox( - 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/allergies_screen/allergies_screen.dart b/lib/presentation/registration/allergies_screen/allergies_screen.dart index 56702d9..3261c92 100644 --- a/lib/presentation/registration/allergies_screen/allergies_screen.dart +++ b/lib/presentation/registration/allergies_screen/allergies_screen.dart @@ -1,10 +1,6 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/allergies_bloc.dart'; -// ignore: unused_import -import 'models/allergies_model.dart'; 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'; @@ -18,6 +14,14 @@ class AllergiesScreen extends StatefulWidget { } class _AllergiesScreenState extends State { + final enterInformationController = TextEditingController(); + + @override + void initState() { + super.initState(); + enterInformationController.text = widget.sheet.aboutAllergy; + } + @override Widget build(BuildContext context) { return SingleChildScrollView( @@ -29,75 +33,21 @@ class _AllergiesScreenState extends State { children: [ Text("allergies_presence".tr, style: theme.textTheme.headlineSmall), SizedBox(height: 22.v), - _buildTextFormField(context), - // 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), - // ); - // }, - // ), + 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)); + }, + ), ], ), ), ); } - - 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); - }; - } - - 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/blood_pressure_screen/bloc/blood_pressure_bloc.dart b/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_bloc.dart index 2fda1b5..64e3e01 100644 --- a/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_bloc.dart +++ b/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_bloc.dart @@ -2,7 +2,9 @@ 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. @@ -43,7 +45,11 @@ class BloodPressureBloc extends Bloc { id: 1, title: "Да", ), - SelectionPopupModel(id: 2, title: "Нет", isSelected: true), + SelectionPopupModel( + id: 2, + title: "Нет", + isSelected: true, + ), ]; } @@ -51,11 +57,16 @@ class BloodPressureBloc extends Bloc { BloodPressureInitialEvent event, Emitter emit, ) async { - emit(state.copyWith( + emit( + state.copyWith( upPressureController: TextEditingController(), - downPressureController: TextEditingController(),),); - emit(state.copyWith( - bloodPressureModelObj: state.bloodPressureModelObj - ?.copyWith(dropdownItemList: fillDropdownItemList()),),); + downPressureController: TextEditingController(), + ), + ); + emit( + state.copyWith( + bloodPressureModelObj: state.bloodPressureModelObj?.copyWith(dropdownItemList: fillDropdownItemList()), + ), + ); } } diff --git a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart b/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart index d5c2468..3566933 100644 --- a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart +++ b/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart @@ -1,9 +1,5 @@ -import 'package:eatvio_app/app_router.dart'; -import 'package:go_router/go_router.dart'; - -import 'bloc/blood_pressure_bloc.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.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/custom_drop_down.dart'; import 'package:eatvio_app/widgets/custom_text_form_field.dart'; @@ -20,210 +16,147 @@ class BloodPressureScreen extends StatefulWidget { } class _BloodPressureScreenState extends State { + final List selectionPopupList = [ + SelectionPopupModel( + id: 1, + title: "Да", + ), + SelectionPopupModel( + id: 2, + 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; + downPressureController.text = widget.sheet.bloodPressureDown; + if (widget.sheet.hasHyper.isNotEmpty) { + widget.sheet.hasHyper == 'Да' ? selectedPopupHyper = selectionPopupList[0] : selectedPopupHyper = selectionPopupList[1]; + } + if (widget.sheet.hasHypo.isNotEmpty) { + widget.sheet.hasHypo == 'Да' ? 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, - ), + 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), - 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("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: 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), - BlocSelector( - selector: (state) => state.downPressureController, - builder: (context, downPressureController) { - return CustomTextFormField(inputFormatters: [digitsOnly], controller: downPressureController, 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), + CustomTextFormField( + inputFormatters: [digitsOnly], + controller: downPressureController, + hintText: "90".tr, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(bloodPressureDown: 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: 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_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.title)); + }); + }, ), - 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), - ); - }, + ), + 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.title)); + }); + }, ), - // 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('allergiesScreen', 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)); - }; - } - - - 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/favorite_foods_screen/favorite_foods_screen.dart b/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart index b4f54d9..b26f0c2 100644 --- a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart +++ b/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart @@ -1,6 +1,4 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/favorite_foods_bloc.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; import 'package:eatvio_app/widgets/custom_text_form_field.dart'; @@ -16,6 +14,16 @@ class FavoriteFoodsScreen extends StatefulWidget { } 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( @@ -37,100 +45,33 @@ class _FavoriteFoodsScreenState extends State { ), ), SizedBox(height: 13.v), - _buildTextFormFieldFav(context), + 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), - _buildTextFormFieldUnfav(context), - // 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), - // ); - // }, - // ), + 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)); + }, + ), ], ), ), ); } - - 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); - }; - } - - - 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_sports_screen/favorite_sports_screen.dart b/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart index fd3a42f..86c7d24 100644 --- a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart +++ b/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart @@ -1,8 +1,4 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/favorite_sports_bloc.dart'; -// ignore: unused_import -import 'models/favorite_sports_model.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; import 'package:eatvio_app/widgets/custom_text_form_field.dart'; @@ -18,6 +14,14 @@ class FavoriteSportsScreen extends StatefulWidget { } class _FavoriteSportsScreenState extends State { + final enterInformationController = TextEditingController(); + + @override + void initState() { + super.initState(); + enterInformationController.text = widget.sheet.aboutSportHobbies; + } + @override Widget build(BuildContext context) { return SingleChildScrollView( @@ -30,76 +34,21 @@ class _FavoriteSportsScreenState extends State { children: [ Text("your_favorite_sports".tr, style: theme.textTheme.headlineSmall), SizedBox(height: 22.v), - _buildTextFormFieldSection(context), - // 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), - // ); - // }, - // ), + 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)); + }, + ), ], ), ), ); } - - 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); - }; - } - - - 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/height_screen/height_screen.dart b/lib/presentation/registration/height_screen/height_screen.dart index a41dad9..9936418 100644 --- a/lib/presentation/registration/height_screen/height_screen.dart +++ b/lib/presentation/registration/height_screen/height_screen.dart @@ -1,6 +1,4 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/height_bloc.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/widgets/custom_text_form_field.dart'; import 'package:flutter/services.dart'; @@ -17,6 +15,14 @@ class HeightScreen extends StatefulWidget { } class _HeightScreenState extends State { + final heightController = TextEditingController(); + + @override + void initState() { + super.initState(); + heightController.text = widget.sheet.height; + } + @override Widget build(BuildContext context) { return SingleChildScrollView( @@ -38,17 +44,17 @@ class _HeightScreenState extends State { 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, - ], - ); + 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: newValue)); }, ), ], @@ -58,22 +64,4 @@ class _HeightScreenState extends State { ), ); } - - onTapNext(HeightState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.heightModelObj!.userRegistrationSheet; - GoRouter.of(context).goNamed('bloodPressureScreen', extra: sheet); - }; - } - - 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/medicine_intake_screen/medicine_intake_screen.dart b/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart index 5ccc203..1e6f4ff 100644 --- a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart +++ b/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart @@ -1,6 +1,4 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/medicine_intake_bloc.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/widgets/custom_text_form_field.dart'; import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; @@ -16,6 +14,14 @@ class MedicineIntakeScreen extends StatefulWidget { } class _MedicineIntakeScreenState extends State { + final enterInformationController = TextEditingController(); + + @override + void initState() { + super.initState(); + enterInformationController.text = widget.sheet.aboutTakingPils; + } + @override Widget build(BuildContext context) { return SingleChildScrollView( @@ -36,83 +42,22 @@ class _MedicineIntakeScreenState extends State { style: theme.textTheme.headlineSmall, ), ), - SizedBox(height: 86.v), - _buildTextFormField(context), - // 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), - // ); - // }, - // ), + 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)); + }, + ), ], ), ), ); } - - onTapSkip(MedicineIntakeState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.medicineIntakeModelObj!.userRegistrationSheet; - GoRouter.of(context).goNamed( - 'favoriteSportsScreen', - extra: sheet, - ); - }; - } - - onTapNext(MedicineIntakeState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.medicineIntakeModelObj!.userRegistrationSheet; - // sheet.aboutTakingPils = state.enterInformationController!.text; - GoRouter.of(context).goNamed( - 'favoriteSportsScreen', - extra: sheet, - ); - }; - } - - - 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/weight_screen/weight_screen.dart b/lib/presentation/registration/weight_screen/weight_screen.dart index f65f0f3..a8a59ca 100644 --- a/lib/presentation/registration/weight_screen/weight_screen.dart +++ b/lib/presentation/registration/weight_screen/weight_screen.dart @@ -1,75 +1,67 @@ -import 'package:go_router/go_router.dart'; - -import 'bloc/weight_bloc.dart'; +import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/widgets/custom_text_form_field.dart'; import 'package:flutter/services.dart'; import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; import 'package:flutter/material.dart'; -class WeightScreen extends StatelessWidget { +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(); + weightController.text = widget.sheet.weight; + } + @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), - BlocBuilder( - builder: (context, state) { - return CustomTextFormField( - width: 150.h, - textInputAction: TextInputAction.done, - controller: state.weightController, - keyboardType: TextInputType.number, - inputFormatters: [ - FilteringTextInputFormatter.digitsOnly, - ], - ); - }, - ), - ], - ), - ], - ), + 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: newValue)); + }, + ), + ], + ), + ], + ), ), ); } - - onTapNext(WeightState state, BuildContext context) { - return () { - UserRegistrationSheet sheet = state.weightModelObj!.userRegistrationSheet; - GoRouter.of(context).goNamed('heightScreen', extra: sheet); - }; - } - - - Function onTapBack(BuildContext context) { - return () { - onTapArrowLeft(context); - }; - } - - /// Navigates to the previous screen. - onTapArrowLeft(BuildContext context) { - GoRouter.of(context).pop(); - } } -- 2.49.1 From b8227a492d6494b497da9c2264f9b233f98fc255 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Mon, 15 Jul 2024 15:06:14 +0300 Subject: [PATCH 059/110] fix(diary): Satiety and mood change API method call fix --- .../diary/presentation/bloc/diary_bloc.dart | 131 ++++-------------- .../bloc/diary_state.freezed.dart | 92 ++++++------ .../diary/repositories/diary_repository.dart | 29 ++++ .../diary/services/diary_service.dart | 20 +-- .../diary/services/diary_service.g.dart | 28 ++-- 5 files changed, 127 insertions(+), 173 deletions(-) diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index 6bef493..4691b34 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -18,8 +18,7 @@ part 'diary_event.dart'; class DiaryBloc extends Bloc { final DiaryRepository diaryRepository; - DiaryBloc({required this.diaryRepository}) - : super(const DiaryState.loading()) { + DiaryBloc({required this.diaryRepository}) : super(const DiaryState.loading()) { on(loadDiary); on(_changeSatiety); // пользователь нажимает на шкалу сытости on(_changeMood); // пользователь нажимает на шкалу настроения @@ -58,10 +57,7 @@ class DiaryBloc extends Bloc { final int? diaryID = data['id']; final DiaryModel diary = await diaryRepository.getDiary(diaryID ?? 45); final Meal currentMeal = diary.meals[0]; - List portions = [ - SelectionPopupModel(title: "gr"), - SelectionPopupModel(title: "pcs") - ]; + List portions = [SelectionPopupModel(title: "gr"), SelectionPopupModel(title: "pcs")]; emit(DiaryState.loaded( diary: diary, currentMeal: currentMeal, @@ -69,8 +65,8 @@ class DiaryBloc extends Bloc { photos: currentMeal.photos, portionList: portions, portionController: portions[0], - selectedMood: 3, - selectedSatiety: 3, + selectedMood: currentMeal.mood, + selectedSatiety: currentMeal.satiety, commentController: TextEditingController(), productNameController: TextEditingController(), productQuantityController: TextEditingController(), @@ -88,7 +84,6 @@ class DiaryBloc extends Bloc { consumedChartValues: [1, 1, 1, 1])); } catch (e) { emit(DiaryState.error(errorMessage: e.toString())); - print(e); } } @@ -110,22 +105,14 @@ class DiaryBloc extends Bloc { if (responseChart.statusCode == 200) { final responseBody = jsonDecode(responseChart.body); - final recommendedChartValues = - responseBody['dailyNutritionRecommendation'] - .values - .map((value) => convertToInt(value)) - .toList(); + final recommendedChartValues = responseBody['dailyNutritionRecommendation'].values.map((value) => convertToInt(value)).toList(); - final consumedChartValues = responseBody['dailyNutritionIntake'] - .values - .map((value) => convertToInt(value)) - .toList(); + final consumedChartValues = responseBody['dailyNutritionIntake'].values.map((value) => convertToInt(value)).toList(); print([recommendedChartValues, consumedChartValues]); return [recommendedChartValues, consumedChartValues]; } else { - emit(DiaryStateError( - errorMessage: 'Ошибка при декодировании данных КБЖУ')); + emit(DiaryStateError(errorMessage: 'Ошибка при декодировании данных КБЖУ')); print('fail'); return [[], []]; // Return empty lists instead of -1 } @@ -152,69 +139,23 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = - currentState.copyWith(selectedMood: event.selectedElement); - - // Отправляем данные по HTTP маршруту и ждем ответ - var response = await sendSatietyData( - event.selectedElement, - currentState.currentMeal.id, - currentState.diary.id, - ); - - if (response.statusCode == 200) { - print( - 'Satiety change success! meal_id: ${currentState.currentMeal.id}, mood: ${event.selectedElement}', - ); - emit(updatedState); // Передаем обновленное состояние в emit - } else - print("dad"); + var updatedState = currentState.copyWith(selectedSatiety: event.selectedElement); + diaryRepository.changeSatiety(event.selectedElement, currentState.currentMeal.id, currentState.diary.id); + emit(updatedState); } } - Future sendSatietyData( - int selectedSatiety, - int? mealID, - int diaryID, - ) async { - String url = dotenv.env['SERVER_ROOT']! + - '/diary/$diaryID/meal/$mealID/satiety/fill'; - final Map credentials = { - 'satiety': selectedSatiety, - }; - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - }, - body: json.encode(credentials), - encoding: utf8, - ); - return response; - } - Future _changeMood( ChangeMood event, Emitter emit, ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = - currentState.copyWith(selectedMood: event.selectedElement); + var updatedState = currentState.copyWith(selectedMood: event.selectedElement); - // Отправляем данные по HTTP маршруту и ждем ответ - var response = await sendMoodData( - event.selectedElement, - currentState.currentMeal.id, - currentState.diary.id, - ); + diaryRepository.changeMood(event.selectedElement, currentState.currentMeal.id, currentState.diary.id); - if (response.statusCode == 200) { - print( - 'Mood change success! meal_id: ${currentState.currentMeal.id}, mood: ${event.selectedElement}', - ); - emit(updatedState); // Передаем обновленное состояние в emit - } + emit(updatedState); // Передаем обновленное состояние в emit } } @@ -223,8 +164,7 @@ class DiaryBloc extends Bloc { int? mealID, int diaryID, ) async { - String url = - dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/meal/$mealID/mood/fill'; + String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/meal/$mealID/mood/fill'; final Map credentials = { 'mood': selectedMood, }; @@ -253,8 +193,7 @@ class DiaryBloc extends Bloc { ); if (response.statusCode == 200) { await reloadScreen(event, emit); - var updatedState = - currentState.copyWith(wakeupController: event.selectedTime); + var updatedState = currentState.copyWith(wakeupController: event.selectedTime); print("Wakeup time changed to ${event.selectedTime}"); emit(updatedState); // Передаем обновленное состояние в emit } else @@ -274,8 +213,7 @@ class DiaryBloc extends Bloc { ); if (response.statusCode == 200) { await reloadScreen(event, emit); - var updatedState = - currentState.copyWith(retireController: event.selectedTime); + var updatedState = currentState.copyWith(retireController: event.selectedTime); print("Retire time changed to ${event.selectedTime}"); emit(updatedState); // Передаем обновленное состояние в emit } else @@ -289,8 +227,7 @@ class DiaryBloc extends Bloc { ) async { String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/wakeUp/fill'; final formatter = DateFormat('HH:mm'); - final wakeupString = - formatter.format(DateTime(2022, 1, 1, wakeup.hour, wakeup.minute)); + final wakeupString = formatter.format(DateTime(2022, 1, 1, wakeup.hour, wakeup.minute)); final Map credentials = { 'wakeUp': wakeupString, }; @@ -313,8 +250,7 @@ class DiaryBloc extends Bloc { ) async { String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill'; final formatter = DateFormat('HH:mm'); - final retireString = - formatter.format(DateTime(2022, 1, 1, retire.hour, retire.minute)); + final retireString = formatter.format(DateTime(2022, 1, 1, retire.hour, retire.minute)); final Map credentials = { 'retire': retireString, }; @@ -375,8 +311,7 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - Meal? meal = - currentState.diary.meals.firstWhere((meal) => meal.id == event.value); + Meal? meal = currentState.diary.meals.firstWhere((meal) => meal.id == event.value); DiaryStateLoaded updatedState = currentState.copyWith( currentMeal: event.value, @@ -469,8 +404,7 @@ class DiaryBloc extends Bloc { int? mealID, int diaryID, ) async { - String url = - '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/create'; + String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/create'; final Map credentials = { 'product_name': name, @@ -509,16 +443,13 @@ class DiaryBloc extends Bloc { }, ); - final productNutritionalValues = - jsonDecode(response.body)['product_nutritional_value']; + final productNutritionalValues = jsonDecode(response.body)['product_nutritional_value']; if (productNutritionalValues is List) { // Create a new controller with the input text and update the autocomplete list var updatedState = currentState.copyWith( productNameController: TextEditingController(text: event.input), - autocompleteList: productNutritionalValues - .map((product) => product['name']) - .toList(), + autocompleteList: productNutritionalValues.map((product) => product['name']).toList(), ); if (event.input.length > 3) { updatedState = updatedState.copyWith(moderationExpanded: true); @@ -538,8 +469,7 @@ class DiaryBloc extends Bloc { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - int? mealId = - currentState.currentMeal.id; // Rename id to mealId for clarity + int? mealId = currentState.currentMeal.id; // Rename id to mealId for clarity var response = await sendRemovePortion( event.portionId, @@ -562,8 +492,7 @@ class DiaryBloc extends Bloc { int? mealID, int diaryID, ) async { - String url = - '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete'; + String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete'; var response = await http.delete( Uri.parse(url), @@ -606,8 +535,7 @@ class DiaryBloc extends Bloc { int? mealID, int diaryID, ) async { - String url = - '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete'; + String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete'; final Map credentials = { 'id': photoID, 'path': path, @@ -648,10 +576,8 @@ class DiaryBloc extends Bloc { String? comment, ) async { final formatter = DateFormat('HH:mm'); - final wakeupString = - formatter.format(DateTime(2022, 1, 1, wakeup!.hour, wakeup.minute)); - final retireString = - formatter.format(DateTime(2022, 1, 1, retire!.hour, retire.minute)); + final wakeupString = formatter.format(DateTime(2022, 1, 1, wakeup!.hour, wakeup.minute)); + final retireString = formatter.format(DateTime(2022, 1, 1, retire!.hour, retire.minute)); final Map credentials = { 'wakeup': wakeupString, @@ -695,8 +621,7 @@ class DiaryBloc extends Bloc { int diaryID, int mealId, ) async { - String url = - '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload'; + String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload'; var request = http.MultipartRequest('POST', Uri.parse(url)); diff --git a/lib/features/diary/presentation/bloc/diary_state.freezed.dart b/lib/features/diary/presentation/bloc/diary_state.freezed.dart index 5acd8d2..3293104 100644 --- a/lib/features/diary/presentation/bloc/diary_state.freezed.dart +++ b/lib/features/diary/presentation/bloc/diary_state.freezed.dart @@ -41,8 +41,8 @@ mixin _$DiaryState { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, @@ -77,8 +77,8 @@ mixin _$DiaryState { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, @@ -113,8 +113,8 @@ mixin _$DiaryState { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, @@ -231,8 +231,8 @@ class _$DiaryStateImpl implements _DiaryState { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, @@ -270,8 +270,8 @@ class _$DiaryStateImpl implements _DiaryState { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, @@ -309,8 +309,8 @@ class _$DiaryStateImpl implements _DiaryState { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, @@ -429,8 +429,8 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, @@ -468,8 +468,8 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, @@ -507,8 +507,8 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, @@ -593,8 +593,8 @@ abstract class _$$DiaryStateLoadedImplCopyWith<$Res> { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, @@ -636,8 +636,8 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> Object? fatsController = null, Object? proteinsController = null, Object? carbsController = null, - Object? selectedMood = freezed, - Object? selectedSatiety = freezed, + Object? selectedMood = null, + Object? selectedSatiety = null, Object? wakeupExpanded = null, Object? moderationExpanded = null, Object? moodExpanded = null, @@ -725,14 +725,14 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> ? _value.carbsController : carbsController // ignore: cast_nullable_to_non_nullable as TextEditingController, - selectedMood: freezed == selectedMood + selectedMood: null == selectedMood ? _value.selectedMood : selectedMood // ignore: cast_nullable_to_non_nullable - as int?, - selectedSatiety: freezed == selectedSatiety + as int, + selectedSatiety: null == selectedSatiety ? _value.selectedSatiety : selectedSatiety // ignore: cast_nullable_to_non_nullable - as int?, + as int, wakeupExpanded: null == wakeupExpanded ? _value.wakeupExpanded : wakeupExpanded // ignore: cast_nullable_to_non_nullable @@ -797,8 +797,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { required this.fatsController, required this.proteinsController, required this.carbsController, - this.selectedMood, - this.selectedSatiety, + required this.selectedMood, + required this.selectedSatiety, required this.wakeupExpanded, required this.moderationExpanded, required this.moodExpanded, @@ -891,9 +891,9 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { @override final TextEditingController carbsController; @override - final int? selectedMood; + final int selectedMood; @override - final int? selectedSatiety; + final int selectedSatiety; @override final bool wakeupExpanded; @override @@ -1033,8 +1033,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, @@ -1099,8 +1099,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, @@ -1165,8 +1165,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, @@ -1269,8 +1269,8 @@ abstract class DiaryStateLoaded implements DiaryState { required final TextEditingController fatsController, required final TextEditingController proteinsController, required final TextEditingController carbsController, - final int? selectedMood, - final int? selectedSatiety, + required final int selectedMood, + required final int selectedSatiety, required final bool wakeupExpanded, required final bool moderationExpanded, required final bool moodExpanded, @@ -1297,8 +1297,8 @@ abstract class DiaryStateLoaded implements DiaryState { TextEditingController get fatsController; TextEditingController get proteinsController; TextEditingController get carbsController; - int? get selectedMood; - int? get selectedSatiety; + int get selectedMood; + int get selectedSatiety; bool get wakeupExpanded; bool get moderationExpanded; bool get moodExpanded; @@ -1398,8 +1398,8 @@ class _$DiaryStateErrorImpl implements DiaryStateError { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, @@ -1437,8 +1437,8 @@ class _$DiaryStateErrorImpl implements DiaryStateError { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, @@ -1476,8 +1476,8 @@ class _$DiaryStateErrorImpl implements DiaryStateError { TextEditingController fatsController, TextEditingController proteinsController, TextEditingController carbsController, - int? selectedMood, - int? selectedSatiety, + int selectedMood, + int selectedSatiety, bool wakeupExpanded, bool moderationExpanded, bool moodExpanded, diff --git a/lib/features/diary/repositories/diary_repository.dart b/lib/features/diary/repositories/diary_repository.dart index 25903f1..c915d60 100644 --- a/lib/features/diary/repositories/diary_repository.dart +++ b/lib/features/diary/repositories/diary_repository.dart @@ -1,5 +1,10 @@ +import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:eatvio_app/features/diary/models/meal.dart'; +import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.dart'; +import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/services/diary_service.dart'; +import 'package:flutter/widgets.dart'; class DiaryRepository { final DiaryService diaryService; @@ -21,4 +26,28 @@ class DiaryRepository { rethrow; } } + + Future changeSatiety(int satiety, int mealID, int diaryID) async { + try { + await diaryService.sendSatietyData( + diaryID, + mealID, + satiety, + ); + } catch (e) { + rethrow; + } + } + + Future changeMood(int mood, int mealID, int diaryID) async { + try { + await diaryService.sendMoodData( + diaryID, + mealID, + mood, + ); + } catch (e) { + rethrow; + } + } } diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart index e047b5e..ad02539 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -18,18 +18,18 @@ abstract class DiaryService { @GET('/diary/{id}/dailyNutritionData/') Future getChart(@Path() String id); - @POST('/diary/{diaryID}/meal/{mealID}/satiety/fill') - Future sendSatiety( - @Path() String diaryID, - String mealID, - int satiety, + @POST('/diary/{diary_id}/meal/{meal_id}/satiety/fill') + Future> sendSatietyData( + @Path() int diary_id, + @Path() int meal_id, + @Query('satiety') int satiety, ); - @POST('/diary/{diaryID}/meal/{mealID}/mood/fill') - Future sendMood( - @Path() String diaryID, - String mealID, - int mood, + @POST('/diary/{diary_id}/meal/{meal_id}/mood/fill') + Future> sendMoodData( + @Path() int diary_id, + @Path() int meal_id, + @Query('mood') int mood, ); @POST('/diary/{diaryID}/wakeup/fill') diff --git a/lib/features/diary/services/diary_service.g.dart b/lib/features/diary/services/diary_service.g.dart index 3ea7bd1..ddbf219 100644 --- a/lib/features/diary/services/diary_service.g.dart +++ b/lib/features/diary/services/diary_service.g.dart @@ -101,24 +101,24 @@ class _DiaryService implements DiaryService { } @override - Future sendSatiety( - String diaryID, - String mealID, + Future> sendSatietyData( + int diary_id, + int meal_id, int satiety, ) async { final _extra = {}; - final queryParameters = {}; + final queryParameters = {r'satiety': satiety}; final _headers = {}; const Map? _data = null; final _result = await _dio - .fetch>(_setStreamType(Options( + .fetch>(_setStreamType>(Options( method: 'POST', headers: _headers, extra: _extra, ) .compose( _dio.options, - '/diary/${diaryID}/meal/{mealID}/satiety/fill', + '/diary/${diary_id}/meal/${meal_id}/satiety/fill', queryParameters: queryParameters, data: _data, ) @@ -127,29 +127,29 @@ class _DiaryService implements DiaryService { _dio.options.baseUrl, baseUrl, )))); - final _value = DiaryModel.fromJson(_result.data!); + final _value = _result.data!.cast(); return _value; } @override - Future sendMood( - String diaryID, - String mealID, + Future> sendMoodData( + int diary_id, + int meal_id, int mood, ) async { final _extra = {}; - final queryParameters = {}; + final queryParameters = {r'mood': mood}; final _headers = {}; const Map? _data = null; final _result = await _dio - .fetch>(_setStreamType(Options( + .fetch>(_setStreamType>(Options( method: 'POST', headers: _headers, extra: _extra, ) .compose( _dio.options, - '/diary/${diaryID}/meal/{mealID}/mood/fill', + '/diary/${diary_id}/meal/${meal_id}/mood/fill', queryParameters: queryParameters, data: _data, ) @@ -158,7 +158,7 @@ class _DiaryService implements DiaryService { _dio.options.baseUrl, baseUrl, )))); - final _value = DiaryModel.fromJson(_result.data!); + final _value = _result.data!.cast(); return _value; } -- 2.49.1 From 76c1effe122b208cf7466ee1d317997c28d8368c Mon Sep 17 00:00:00 2001 From: maxxkim Date: Mon, 15 Jul 2024 15:37:18 +0300 Subject: [PATCH 060/110] fix(diary): Wakeup and retire time API method call fix --- .../diary/presentation/bloc/diary_bloc.dart | 130 ++---------------- .../diary/presentation/bloc/diary_event.dart | 3 +- .../diary/repositories/diary_repository.dart | 33 ++++- .../diary/services/diary_service.dart | 17 +-- .../diary/services/diary_service.g.dart | 20 ++- 5 files changed, 60 insertions(+), 143 deletions(-) diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index 4691b34..8cebe1a 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -159,45 +159,20 @@ class DiaryBloc extends Bloc { } } - Future sendMoodData( - int selectedMood, - int? mealID, - int diaryID, - ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/meal/$mealID/mood/fill'; - final Map credentials = { - 'mood': selectedMood, - }; - - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - FutureOr _changeWakeup( WakeupEvent event, Emitter emit, ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var response = await sendWakeupData( - event.selectedTime, + var updatedState = currentState.copyWith(wakeupController: event.selectedTime); + final DateFormat formatter = DateFormat('HH:mm'); + final String wakeupString = formatter.format(DateTime(2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); + await diaryRepository.changeWakeup( currentState.diary.id, + wakeupString, ); - if (response.statusCode == 200) { - await reloadScreen(event, emit); - var updatedState = currentState.copyWith(wakeupController: event.selectedTime); - print("Wakeup time changed to ${event.selectedTime}"); - emit(updatedState); // Передаем обновленное состояние в emit - } else - print("Wakeup time change error"); + emit(updatedState); } } @@ -207,66 +182,17 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var response = await sendRetireData( - event.selectedTime, + var updatedState = currentState.copyWith(retireController: event.selectedTime); + final DateFormat formatter = DateFormat('HH:mm'); + final String retireString = formatter.format(DateTime(2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); + await diaryRepository.changeRetire( currentState.diary.id, + retireString, ); - if (response.statusCode == 200) { - await reloadScreen(event, emit); - var updatedState = currentState.copyWith(retireController: event.selectedTime); - print("Retire time changed to ${event.selectedTime}"); - emit(updatedState); // Передаем обновленное состояние в emit - } else - print("Retire time change error"); + emit(updatedState); } } - Future sendWakeupData( - TimeOfDay wakeup, - int diaryID, - ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/wakeUp/fill'; - final formatter = DateFormat('HH:mm'); - final wakeupString = formatter.format(DateTime(2022, 1, 1, wakeup.hour, wakeup.minute)); - final Map credentials = { - 'wakeUp': wakeupString, - }; - - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - - Future sendRetireData( - TimeOfDay retire, - int diaryID, - ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill'; - final formatter = DateFormat('HH:mm'); - final retireString = formatter.format(DateTime(2022, 1, 1, retire.hour, retire.minute)); - final Map credentials = { - 'retire': retireString, - }; - - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - FutureOr _changeMealTime( ChangeMealTime event, Emitter emit, @@ -274,53 +200,27 @@ class DiaryBloc extends Bloc { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; var updatedState = currentState.copyWith(mealTimeController: event.time); - emit(updatedState); } } - Future sendMealTimeData( - String? token, - TimeOfDay mealTime, - int? mealID, - int diaryID, - ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/???'; - final Map credentials = { - 'time': mealTime, - 'meal_id': mealID, - 'diary_id': diaryID, - }; - - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - FutureOr _changeMeal( ChangeMeal event, Emitter emit, ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - Meal? meal = currentState.diary.meals.firstWhere((meal) => meal.id == event.value); + Meal? meal = currentState.diary.meals.firstWhere((meal) => meal.id == event.value.id); DiaryStateLoaded updatedState = currentState.copyWith( - currentMeal: event.value, + currentMeal: meal, portions: meal.portions, photos: meal.photos, mealTimeController: toTime(meal.time), selectedMood: meal.mood, selectedSatiety: meal.satiety, ); + print(updatedState.currentMeal.id); emit(updatedState); } } diff --git a/lib/features/diary/presentation/bloc/diary_event.dart b/lib/features/diary/presentation/bloc/diary_event.dart index 91445ff..eb4742e 100644 --- a/lib/features/diary/presentation/bloc/diary_event.dart +++ b/lib/features/diary/presentation/bloc/diary_event.dart @@ -158,6 +158,5 @@ class SendModeration extends DiaryEvent { 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/features/diary/repositories/diary_repository.dart b/lib/features/diary/repositories/diary_repository.dart index c915d60..68511c7 100644 --- a/lib/features/diary/repositories/diary_repository.dart +++ b/lib/features/diary/repositories/diary_repository.dart @@ -1,10 +1,5 @@ -import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/features/diary/models/diary_model.dart'; -import 'package:eatvio_app/features/diary/models/meal.dart'; -import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.dart'; -import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/features/diary/services/diary_service.dart'; -import 'package:flutter/widgets.dart'; class DiaryRepository { final DiaryService diaryService; @@ -50,4 +45,32 @@ class DiaryRepository { rethrow; } } + + Future changeWakeup( + int diaryID, + String wakeup, + ) async { + try { + await diaryService.sendWakeupData( + diaryID, + wakeup, + ); + } catch (e) { + rethrow; + } + } + + Future changeRetire( + int diaryID, + String retire, + ) async { + try { + await diaryService.sendWakeupData( + diaryID, + retire, + ); + } catch (e) { + rethrow; + } + } } diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart index ad02539..b412594 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -1,6 +1,5 @@ import 'package:dio/dio.dart'; import 'package:eatvio_app/features/diary/models/diary_model.dart'; -import 'package:flutter/material.dart'; import 'package:retrofit/retrofit.dart'; part 'diary_service.g.dart'; @@ -32,17 +31,15 @@ abstract class DiaryService { @Query('mood') int mood, ); - @POST('/diary/{diaryID}/wakeup/fill') - Future sendWakeup( - @Path() String diaryID, - String mealID, - TimeOfDay wakeup, + @POST('/diary/{diary_id}/wakeup/fill') + Future sendWakeupData( + @Path() int diary_id, + @Query('wakeup') String wakeup, ); - @POST('/diary/{diaryID}/retire/fill') + @POST('/diary/{diary_id}/retire/fill') Future sendRetire( - @Path() String diaryID, - String mealID, - TimeOfDay retire, + @Path() int diary_id, + @Query('retire') String retire, ); } diff --git a/lib/features/diary/services/diary_service.g.dart b/lib/features/diary/services/diary_service.g.dart index ddbf219..a33a19e 100644 --- a/lib/features/diary/services/diary_service.g.dart +++ b/lib/features/diary/services/diary_service.g.dart @@ -163,13 +163,12 @@ class _DiaryService implements DiaryService { } @override - Future sendWakeup( - String diaryID, - String mealID, - TimeOfDay wakeup, + Future sendWakeupData( + int diary_id, + String wakeup, ) async { final _extra = {}; - final queryParameters = {}; + final queryParameters = {r'wakeup': wakeup}; final _headers = {}; const Map? _data = null; final _result = await _dio @@ -180,7 +179,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/${diaryID}/wakeup/fill', + '/diary/${diary_id}/wakeup/fill', queryParameters: queryParameters, data: _data, ) @@ -195,12 +194,11 @@ class _DiaryService implements DiaryService { @override Future sendRetire( - String diaryID, - String mealID, - TimeOfDay retire, + int diary_id, + String retire, ) async { final _extra = {}; - final queryParameters = {}; + final queryParameters = {r'retire': retire}; final _headers = {}; const Map? _data = null; final _result = await _dio @@ -211,7 +209,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/${diaryID}/retire/fill', + '/diary/${diary_id}/retire/fill', queryParameters: queryParameters, data: _data, ) -- 2.49.1 From 726b74a236bf52ac2698c41648d233f22ffc54f0 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Mon, 15 Jul 2024 16:33:33 +0300 Subject: [PATCH 061/110] feature(registration): iter6 --- .env | 3 +- .../user_registration_model.dart | 24 +- .../user_registration_model.freezed.dart | 177 ++- .../user_registration_model.g.dart | 25 +- .../registration/consts/cities_list.dart} | 159 +-- .../registration_cubit.dart | 35 +- .../pages}/additional_information_screen.dart | 0 .../presentation/pages}/allergies_screen.dart | 0 .../pages}/blood_pressure_screen.dart | 22 +- .../pages}/body_circumferences_screen.dart | 12 +- .../pages/city_of_living_screen.dart | 88 ++ .../pages}/credentials_screen.dart | 0 .../pages}/date_of_birth_screen.dart | 0 .../pages}/favorite_foods_screen.dart | 0 .../pages}/favorite_sports_screen.dart | 0 .../presentation/pages}/gender_screen.dart | 0 .../presentation/pages}/height_screen.dart | 4 +- .../pages}/language_select_screen.dart | 0 .../pages}/medicine_intake_screen.dart | 0 .../presentation/pages}/name_screen.dart | 0 .../pages/registration_screen.dart | 46 +- .../presentation/pages}/weight_screen.dart | 4 +- .../repositories/registration_repository.dart | 4 +- .../services/registration_service.dart | 3 +- .../services/registration_service.g.dart | 5 +- .../auth/auth_screen/auth_screen.dart | 115 +- .../bloc/additional_information_bloc.dart | 22 - .../bloc/additional_information_event.dart | 16 - .../bloc/additional_information_state.dart | 31 - .../models/additional_information_model.dart | 20 - .../allergies_screen/bloc/allergies_bloc.dart | 20 - .../bloc/allergies_event.dart | 16 - .../bloc/allergies_state.dart | 31 - .../models/allergies_model.dart | 20 - .../app_navigation_screen.dart | 233 ---- .../bloc/app_navigation_bloc.dart | 18 - .../bloc/app_navigation_event.dart | 16 - .../bloc/app_navigation_state.dart | 21 - .../models/app_navigation_model.dart | 16 - .../bloc/blood_pressure_bloc.dart | 72 - .../bloc/blood_pressure_event.dart | 39 - .../bloc/blood_pressure_state.dart | 50 - .../models/blood_pressure_model.dart | 25 - .../bloc/body_circumferences_bloc.dart | 25 - .../bloc/body_circumferences_event.dart | 16 - .../bloc/body_circumferences_state.dart | 46 - .../models/body_circumferences_model.dart | 20 - .../bloc/city_of_living_bloc.dart | 37 - .../bloc/city_of_living_event.dart | 28 - .../bloc/city_of_living_state.dart | 37 - .../models/city_of_living_model.dart | 1153 ----------------- .../bloc/credentials_bloc.dart | 24 - .../bloc/credentials_event.dart | 16 - .../bloc/credentials_state.dart | 49 - .../models/credentials_model.dart | 22 - .../bloc/date_of_birth_bloc.dart | 18 - .../bloc/date_of_birth_event.dart | 16 - .../bloc/date_of_birth_state.dart | 20 - .../models/date_of_birth_model.dart | 21 - .../bloc/favorite_foods_bloc.dart | 22 - .../bloc/favorite_foods_event.dart | 16 - .../bloc/favorite_foods_state.dart | 39 - .../models/favorite_foods_model.dart | 20 - .../bloc/favorite_sports_bloc.dart | 21 - .../bloc/favorite_sports_event.dart | 16 - .../bloc/favorite_sports_state.dart | 32 - .../models/favorite_sports_model.dart | 20 - .../gender_screen/bloc/gender_bloc.dart | 29 - .../gender_screen/bloc/gender_event.dart | 26 - .../gender_screen/bloc/gender_state.dart | 30 - .../gender_screen/models/gender_model.dart | 20 - .../height_screen/bloc/height_bloc.dart | 22 - .../height_screen/bloc/height_event.dart | 16 - .../height_screen/bloc/height_state.dart | 30 - .../height_screen/models/height_model.dart | 25 - .../bloc/language_select_bloc.dart | 35 - .../bloc/language_select_event.dart | 28 - .../bloc/language_select_state.dart | 32 - .../models/language_select_model.dart | 51 - .../bloc/medicine_intake_bloc.dart | 21 - .../bloc/medicine_intake_event.dart | 16 - .../bloc/medicine_intake_state.dart | 32 - .../models/medicine_intake_model.dart | 20 - .../name_screen/bloc/name_bloc.dart | 22 - .../name_screen/bloc/name_event.dart | 16 - .../name_screen/bloc/name_state.dart | 36 - .../name_screen/models/name_model.dart | 21 - .../splash_screen/bloc/splash_bloc.dart | 26 - .../splash_screen/bloc/splash_event.dart | 16 - .../splash_screen/bloc/splash_state.dart | 20 - .../splash_screen/models/splash_model.dart | 16 - .../splash_screen/splash_screen.dart | 36 - .../weight_screen/bloc/weight_bloc.dart | 22 - .../weight_screen/bloc/weight_event.dart | 16 - .../weight_screen/bloc/weight_state.dart | 30 - .../weight_screen/models/weight_model.dart | 25 - 96 files changed, 358 insertions(+), 3503 deletions(-) rename lib/{presentation/registration/city_of_living_screen/city_of_living_screen.dart => features/registration/consts/cities_list.dart} (79%) rename lib/{presentation/registration/additional_information_screen => features/registration/presentation/pages}/additional_information_screen.dart (100%) rename lib/{presentation/registration/allergies_screen => features/registration/presentation/pages}/allergies_screen.dart (100%) rename lib/{presentation/registration/blood_pressure_screen => features/registration/presentation/pages}/blood_pressure_screen.dart (89%) rename lib/{presentation/registration/body_circumferences_screen => features/registration/presentation/pages}/body_circumferences_screen.dart (85%) create mode 100644 lib/features/registration/presentation/pages/city_of_living_screen.dart rename lib/{presentation/registration/credentials_screen => features/registration/presentation/pages}/credentials_screen.dart (100%) rename lib/{presentation/registration/date_of_birth_screen => features/registration/presentation/pages}/date_of_birth_screen.dart (100%) rename lib/{presentation/registration/favorite_foods_screen => features/registration/presentation/pages}/favorite_foods_screen.dart (100%) rename lib/{presentation/registration/favorite_sports_screen => features/registration/presentation/pages}/favorite_sports_screen.dart (100%) rename lib/{presentation/registration/gender_screen => features/registration/presentation/pages}/gender_screen.dart (100%) rename lib/{presentation/registration/height_screen => features/registration/presentation/pages}/height_screen.dart (93%) rename lib/{presentation/registration/language_select_screen => features/registration/presentation/pages}/language_select_screen.dart (100%) rename lib/{presentation/registration/medicine_intake_screen => features/registration/presentation/pages}/medicine_intake_screen.dart (100%) rename lib/{presentation/registration/name_screen => features/registration/presentation/pages}/name_screen.dart (100%) rename lib/{presentation/registration/weight_screen => features/registration/presentation/pages}/weight_screen.dart (93%) delete mode 100644 lib/presentation/registration/additional_information_screen/bloc/additional_information_bloc.dart delete mode 100644 lib/presentation/registration/additional_information_screen/bloc/additional_information_event.dart delete mode 100644 lib/presentation/registration/additional_information_screen/bloc/additional_information_state.dart delete mode 100644 lib/presentation/registration/additional_information_screen/models/additional_information_model.dart delete mode 100644 lib/presentation/registration/allergies_screen/bloc/allergies_bloc.dart delete mode 100644 lib/presentation/registration/allergies_screen/bloc/allergies_event.dart delete mode 100644 lib/presentation/registration/allergies_screen/bloc/allergies_state.dart delete mode 100644 lib/presentation/registration/allergies_screen/models/allergies_model.dart delete mode 100644 lib/presentation/registration/app_navigation_screen/app_navigation_screen.dart delete mode 100644 lib/presentation/registration/app_navigation_screen/bloc/app_navigation_bloc.dart delete mode 100644 lib/presentation/registration/app_navigation_screen/bloc/app_navigation_event.dart delete mode 100644 lib/presentation/registration/app_navigation_screen/bloc/app_navigation_state.dart delete mode 100644 lib/presentation/registration/app_navigation_screen/models/app_navigation_model.dart delete mode 100644 lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_bloc.dart delete mode 100644 lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_event.dart delete mode 100644 lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_state.dart delete mode 100644 lib/presentation/registration/blood_pressure_screen/models/blood_pressure_model.dart delete mode 100644 lib/presentation/registration/body_circumferences_screen/bloc/body_circumferences_bloc.dart delete mode 100644 lib/presentation/registration/body_circumferences_screen/bloc/body_circumferences_event.dart delete mode 100644 lib/presentation/registration/body_circumferences_screen/bloc/body_circumferences_state.dart delete mode 100644 lib/presentation/registration/body_circumferences_screen/models/body_circumferences_model.dart delete mode 100644 lib/presentation/registration/city_of_living_screen/bloc/city_of_living_bloc.dart delete mode 100644 lib/presentation/registration/city_of_living_screen/bloc/city_of_living_event.dart delete mode 100644 lib/presentation/registration/city_of_living_screen/bloc/city_of_living_state.dart delete mode 100644 lib/presentation/registration/city_of_living_screen/models/city_of_living_model.dart delete mode 100644 lib/presentation/registration/credentials_screen/bloc/credentials_bloc.dart delete mode 100644 lib/presentation/registration/credentials_screen/bloc/credentials_event.dart delete mode 100644 lib/presentation/registration/credentials_screen/bloc/credentials_state.dart delete mode 100644 lib/presentation/registration/credentials_screen/models/credentials_model.dart delete mode 100644 lib/presentation/registration/date_of_birth_screen/bloc/date_of_birth_bloc.dart delete mode 100644 lib/presentation/registration/date_of_birth_screen/bloc/date_of_birth_event.dart delete mode 100644 lib/presentation/registration/date_of_birth_screen/bloc/date_of_birth_state.dart delete mode 100644 lib/presentation/registration/date_of_birth_screen/models/date_of_birth_model.dart delete mode 100644 lib/presentation/registration/favorite_foods_screen/bloc/favorite_foods_bloc.dart delete mode 100644 lib/presentation/registration/favorite_foods_screen/bloc/favorite_foods_event.dart delete mode 100644 lib/presentation/registration/favorite_foods_screen/bloc/favorite_foods_state.dart delete mode 100644 lib/presentation/registration/favorite_foods_screen/models/favorite_foods_model.dart delete mode 100644 lib/presentation/registration/favorite_sports_screen/bloc/favorite_sports_bloc.dart delete mode 100644 lib/presentation/registration/favorite_sports_screen/bloc/favorite_sports_event.dart delete mode 100644 lib/presentation/registration/favorite_sports_screen/bloc/favorite_sports_state.dart delete mode 100644 lib/presentation/registration/favorite_sports_screen/models/favorite_sports_model.dart delete mode 100644 lib/presentation/registration/gender_screen/bloc/gender_bloc.dart delete mode 100644 lib/presentation/registration/gender_screen/bloc/gender_event.dart delete mode 100644 lib/presentation/registration/gender_screen/bloc/gender_state.dart delete mode 100644 lib/presentation/registration/gender_screen/models/gender_model.dart delete mode 100644 lib/presentation/registration/height_screen/bloc/height_bloc.dart delete mode 100644 lib/presentation/registration/height_screen/bloc/height_event.dart delete mode 100644 lib/presentation/registration/height_screen/bloc/height_state.dart delete mode 100644 lib/presentation/registration/height_screen/models/height_model.dart delete mode 100644 lib/presentation/registration/language_select_screen/bloc/language_select_bloc.dart delete mode 100644 lib/presentation/registration/language_select_screen/bloc/language_select_event.dart delete mode 100644 lib/presentation/registration/language_select_screen/bloc/language_select_state.dart delete mode 100644 lib/presentation/registration/language_select_screen/models/language_select_model.dart delete mode 100644 lib/presentation/registration/medicine_intake_screen/bloc/medicine_intake_bloc.dart delete mode 100644 lib/presentation/registration/medicine_intake_screen/bloc/medicine_intake_event.dart delete mode 100644 lib/presentation/registration/medicine_intake_screen/bloc/medicine_intake_state.dart delete mode 100644 lib/presentation/registration/medicine_intake_screen/models/medicine_intake_model.dart delete mode 100644 lib/presentation/registration/name_screen/bloc/name_bloc.dart delete mode 100644 lib/presentation/registration/name_screen/bloc/name_event.dart delete mode 100644 lib/presentation/registration/name_screen/bloc/name_state.dart delete mode 100644 lib/presentation/registration/name_screen/models/name_model.dart delete mode 100644 lib/presentation/registration/splash_screen/bloc/splash_bloc.dart delete mode 100644 lib/presentation/registration/splash_screen/bloc/splash_event.dart delete mode 100644 lib/presentation/registration/splash_screen/bloc/splash_state.dart delete mode 100644 lib/presentation/registration/splash_screen/models/splash_model.dart delete mode 100644 lib/presentation/registration/splash_screen/splash_screen.dart delete mode 100644 lib/presentation/registration/weight_screen/bloc/weight_bloc.dart delete mode 100644 lib/presentation/registration/weight_screen/bloc/weight_event.dart delete mode 100644 lib/presentation/registration/weight_screen/bloc/weight_state.dart delete mode 100644 lib/presentation/registration/weight_screen/models/weight_model.dart diff --git a/.env b/.env index e223a35..0f129f5 100644 --- a/.env +++ b/.env @@ -1,2 +1,3 @@ SERVER_ROOT='https://mobile-stage.eatvio.ru/api' -STORAGE_URL='https://mobile-stage.eatvio.ru/storage/' \ No newline at end of file +STORAGE_URL='https://mobile-stage.eatvio.ru/storage/' +OFERTA='https://mobile-stage.eatvio.ru/oferta_bs.pdf' \ No newline at end of file diff --git a/lib/data/models/userRegistrationModel/user_registration_model.dart b/lib/data/models/userRegistrationModel/user_registration_model.dart index cae81cd..686d206 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.dart @@ -9,7 +9,7 @@ class UserRegistrationSheet with _$UserRegistrationSheet { required String name, @JsonKey(name: 'first_name') required String firstName, - @JsonKey(name: 'last') + @JsonKey(name: 'last_name') required String lastName, required String email, required String password, @@ -23,22 +23,22 @@ class UserRegistrationSheet with _$UserRegistrationSheet { required String country, required String city, required String lang, - required String weight, - required String height, + required int weight, + required int height, @JsonKey(name: 'chest_circumference') - required String chestCircumference, + required int chestCircumference, @JsonKey(name: 'waist_circumference') - required String waistCircumference, + required int waistCircumference, @JsonKey(name: 'hip_circumference') - required String hipCircumference, + required int hipCircumference, @JsonKey(name: 'blood_pressure_up') - required String bloodPressureUp, + required int bloodPressureUp, @JsonKey(name: 'blood_pressure_down') - required String bloodPressureDown, + required int bloodPressureDown, @JsonKey(name: 'has_hypo') - required String hasHypo, + required int hasHypo, @JsonKey(name: 'has_hyper') - required String hasHyper, + required int hasHyper, @JsonKey(name: 'about_alergy') required String aboutAllergy, @JsonKey(name: 'about_taking_pils') @@ -51,9 +51,9 @@ class UserRegistrationSheet with _$UserRegistrationSheet { required String unfavoriteFoods, @JsonKey(name: 'additional_info') required String additionalInfo, - @Default('1.2') + @Default(1.2) @JsonKey(name: 'activity_coefficient') - String activityCoefficient, + 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 index 9d00a7d..4aa91df 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart @@ -24,7 +24,7 @@ mixin _$UserRegistrationSheet { String get name => throw _privateConstructorUsedError; @JsonKey(name: 'first_name') String get firstName => throw _privateConstructorUsedError; - @JsonKey(name: 'last') + @JsonKey(name: 'last_name') String get lastName => throw _privateConstructorUsedError; String get email => throw _privateConstructorUsedError; String get password => throw _privateConstructorUsedError; @@ -37,22 +37,22 @@ mixin _$UserRegistrationSheet { String get country => throw _privateConstructorUsedError; String get city => throw _privateConstructorUsedError; String get lang => throw _privateConstructorUsedError; - String get weight => throw _privateConstructorUsedError; - String get height => throw _privateConstructorUsedError; + int get weight => throw _privateConstructorUsedError; + int get height => throw _privateConstructorUsedError; @JsonKey(name: 'chest_circumference') - String get chestCircumference => throw _privateConstructorUsedError; + int get chestCircumference => throw _privateConstructorUsedError; @JsonKey(name: 'waist_circumference') - String get waistCircumference => throw _privateConstructorUsedError; + int get waistCircumference => throw _privateConstructorUsedError; @JsonKey(name: 'hip_circumference') - String get hipCircumference => throw _privateConstructorUsedError; + int get hipCircumference => throw _privateConstructorUsedError; @JsonKey(name: 'blood_pressure_up') - String get bloodPressureUp => throw _privateConstructorUsedError; + int get bloodPressureUp => throw _privateConstructorUsedError; @JsonKey(name: 'blood_pressure_down') - String get bloodPressureDown => throw _privateConstructorUsedError; + int get bloodPressureDown => throw _privateConstructorUsedError; @JsonKey(name: 'has_hypo') - String get hasHypo => throw _privateConstructorUsedError; + int get hasHypo => throw _privateConstructorUsedError; @JsonKey(name: 'has_hyper') - String get hasHyper => throw _privateConstructorUsedError; + int get hasHyper => throw _privateConstructorUsedError; @JsonKey(name: 'about_alergy') String get aboutAllergy => throw _privateConstructorUsedError; @JsonKey(name: 'about_taking_pils') @@ -66,7 +66,7 @@ mixin _$UserRegistrationSheet { @JsonKey(name: 'additional_info') String get additionalInfo => throw _privateConstructorUsedError; @JsonKey(name: 'activity_coefficient') - String get activityCoefficient => throw _privateConstructorUsedError; + double get activityCoefficient => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -83,7 +83,7 @@ abstract class $UserRegistrationSheetCopyWith<$Res> { $Res call( {String name, @JsonKey(name: 'first_name') String firstName, - @JsonKey(name: 'last') String lastName, + @JsonKey(name: 'last_name') String lastName, String email, String password, @JsonKey(name: 'password_confirmation') String passwordConfirmation, @@ -93,22 +93,22 @@ abstract class $UserRegistrationSheetCopyWith<$Res> { String country, String city, String lang, - String weight, - String height, - @JsonKey(name: 'chest_circumference') String chestCircumference, - @JsonKey(name: 'waist_circumference') String waistCircumference, - @JsonKey(name: 'hip_circumference') String hipCircumference, - @JsonKey(name: 'blood_pressure_up') String bloodPressureUp, - @JsonKey(name: 'blood_pressure_down') String bloodPressureDown, - @JsonKey(name: 'has_hypo') String hasHypo, - @JsonKey(name: 'has_hyper') String hasHyper, + 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') String activityCoefficient}); + @JsonKey(name: 'activity_coefficient') double activityCoefficient}); } /// @nodoc @@ -206,39 +206,39 @@ class _$UserRegistrationSheetCopyWithImpl<$Res, weight: null == weight ? _value.weight : weight // ignore: cast_nullable_to_non_nullable - as String, + as int, height: null == height ? _value.height : height // ignore: cast_nullable_to_non_nullable - as String, + as int, chestCircumference: null == chestCircumference ? _value.chestCircumference : chestCircumference // ignore: cast_nullable_to_non_nullable - as String, + as int, waistCircumference: null == waistCircumference ? _value.waistCircumference : waistCircumference // ignore: cast_nullable_to_non_nullable - as String, + as int, hipCircumference: null == hipCircumference ? _value.hipCircumference : hipCircumference // ignore: cast_nullable_to_non_nullable - as String, + as int, bloodPressureUp: null == bloodPressureUp ? _value.bloodPressureUp : bloodPressureUp // ignore: cast_nullable_to_non_nullable - as String, + as int, bloodPressureDown: null == bloodPressureDown ? _value.bloodPressureDown : bloodPressureDown // ignore: cast_nullable_to_non_nullable - as String, + as int, hasHypo: null == hasHypo ? _value.hasHypo : hasHypo // ignore: cast_nullable_to_non_nullable - as String, + as int, hasHyper: null == hasHyper ? _value.hasHyper : hasHyper // ignore: cast_nullable_to_non_nullable - as String, + as int, aboutAllergy: null == aboutAllergy ? _value.aboutAllergy : aboutAllergy // ignore: cast_nullable_to_non_nullable @@ -266,7 +266,7 @@ class _$UserRegistrationSheetCopyWithImpl<$Res, activityCoefficient: null == activityCoefficient ? _value.activityCoefficient : activityCoefficient // ignore: cast_nullable_to_non_nullable - as String, + as double, ) as $Val); } } @@ -283,7 +283,7 @@ abstract class _$$UserRegistrationSheetImplCopyWith<$Res> $Res call( {String name, @JsonKey(name: 'first_name') String firstName, - @JsonKey(name: 'last') String lastName, + @JsonKey(name: 'last_name') String lastName, String email, String password, @JsonKey(name: 'password_confirmation') String passwordConfirmation, @@ -293,22 +293,22 @@ abstract class _$$UserRegistrationSheetImplCopyWith<$Res> String country, String city, String lang, - String weight, - String height, - @JsonKey(name: 'chest_circumference') String chestCircumference, - @JsonKey(name: 'waist_circumference') String waistCircumference, - @JsonKey(name: 'hip_circumference') String hipCircumference, - @JsonKey(name: 'blood_pressure_up') String bloodPressureUp, - @JsonKey(name: 'blood_pressure_down') String bloodPressureDown, - @JsonKey(name: 'has_hypo') String hasHypo, - @JsonKey(name: 'has_hyper') String hasHyper, + 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') String activityCoefficient}); + @JsonKey(name: 'activity_coefficient') double activityCoefficient}); } /// @nodoc @@ -404,39 +404,39 @@ class __$$UserRegistrationSheetImplCopyWithImpl<$Res> weight: null == weight ? _value.weight : weight // ignore: cast_nullable_to_non_nullable - as String, + as int, height: null == height ? _value.height : height // ignore: cast_nullable_to_non_nullable - as String, + as int, chestCircumference: null == chestCircumference ? _value.chestCircumference : chestCircumference // ignore: cast_nullable_to_non_nullable - as String, + as int, waistCircumference: null == waistCircumference ? _value.waistCircumference : waistCircumference // ignore: cast_nullable_to_non_nullable - as String, + as int, hipCircumference: null == hipCircumference ? _value.hipCircumference : hipCircumference // ignore: cast_nullable_to_non_nullable - as String, + as int, bloodPressureUp: null == bloodPressureUp ? _value.bloodPressureUp : bloodPressureUp // ignore: cast_nullable_to_non_nullable - as String, + as int, bloodPressureDown: null == bloodPressureDown ? _value.bloodPressureDown : bloodPressureDown // ignore: cast_nullable_to_non_nullable - as String, + as int, hasHypo: null == hasHypo ? _value.hasHypo : hasHypo // ignore: cast_nullable_to_non_nullable - as String, + as int, hasHyper: null == hasHyper ? _value.hasHyper : hasHyper // ignore: cast_nullable_to_non_nullable - as String, + as int, aboutAllergy: null == aboutAllergy ? _value.aboutAllergy : aboutAllergy // ignore: cast_nullable_to_non_nullable @@ -464,7 +464,7 @@ class __$$UserRegistrationSheetImplCopyWithImpl<$Res> activityCoefficient: null == activityCoefficient ? _value.activityCoefficient : activityCoefficient // ignore: cast_nullable_to_non_nullable - as String, + as double, )); } } @@ -475,7 +475,7 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { const _$UserRegistrationSheetImpl( {required this.name, @JsonKey(name: 'first_name') required this.firstName, - @JsonKey(name: 'last') required this.lastName, + @JsonKey(name: 'last_name') required this.lastName, required this.email, required this.password, @JsonKey(name: 'password_confirmation') @@ -501,7 +501,7 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @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'}); + @JsonKey(name: 'activity_coefficient') this.activityCoefficient = 1.2}); factory _$UserRegistrationSheetImpl.fromJson(Map json) => _$$UserRegistrationSheetImplFromJson(json); @@ -512,7 +512,7 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @JsonKey(name: 'first_name') final String firstName; @override - @JsonKey(name: 'last') + @JsonKey(name: 'last_name') final String lastName; @override final String email; @@ -535,30 +535,30 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @override final String lang; @override - final String weight; + final int weight; @override - final String height; + final int height; @override @JsonKey(name: 'chest_circumference') - final String chestCircumference; + final int chestCircumference; @override @JsonKey(name: 'waist_circumference') - final String waistCircumference; + final int waistCircumference; @override @JsonKey(name: 'hip_circumference') - final String hipCircumference; + final int hipCircumference; @override @JsonKey(name: 'blood_pressure_up') - final String bloodPressureUp; + final int bloodPressureUp; @override @JsonKey(name: 'blood_pressure_down') - final String bloodPressureDown; + final int bloodPressureDown; @override @JsonKey(name: 'has_hypo') - final String hasHypo; + final int hasHypo; @override @JsonKey(name: 'has_hyper') - final String hasHyper; + final int hasHyper; @override @JsonKey(name: 'about_alergy') final String aboutAllergy; @@ -579,7 +579,7 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { final String additionalInfo; @override @JsonKey(name: 'activity_coefficient') - final String activityCoefficient; + final double activityCoefficient; @override String toString() { @@ -693,7 +693,7 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { const factory _UserRegistrationSheet( {required final String name, @JsonKey(name: 'first_name') required final String firstName, - @JsonKey(name: 'last') required final String lastName, + @JsonKey(name: 'last_name') required final String lastName, required final String email, required final String password, @JsonKey(name: 'password_confirmation') @@ -704,19 +704,18 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { required final String country, required final String city, required final String lang, - required final String weight, - required final String height, + required final int weight, + required final int height, @JsonKey(name: 'chest_circumference') - required final String chestCircumference, + required final int chestCircumference, @JsonKey(name: 'waist_circumference') - required final String waistCircumference, - @JsonKey(name: 'hip_circumference') - required final String hipCircumference, - @JsonKey(name: 'blood_pressure_up') required final String bloodPressureUp, + 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 String bloodPressureDown, - @JsonKey(name: 'has_hypo') required final String hasHypo, - @JsonKey(name: 'has_hyper') required final String hasHyper, + 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') @@ -725,7 +724,7 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { @JsonKey(name: 'unfavorite_foods') required final String unfavoriteFoods, @JsonKey(name: 'additional_info') required final String additionalInfo, @JsonKey(name: 'activity_coefficient') - final String activityCoefficient}) = _$UserRegistrationSheetImpl; + final double activityCoefficient}) = _$UserRegistrationSheetImpl; factory _UserRegistrationSheet.fromJson(Map json) = _$UserRegistrationSheetImpl.fromJson; @@ -736,7 +735,7 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { @JsonKey(name: 'first_name') String get firstName; @override - @JsonKey(name: 'last') + @JsonKey(name: 'last_name') String get lastName; @override String get email; @@ -759,30 +758,30 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { @override String get lang; @override - String get weight; + int get weight; @override - String get height; + int get height; @override @JsonKey(name: 'chest_circumference') - String get chestCircumference; + int get chestCircumference; @override @JsonKey(name: 'waist_circumference') - String get waistCircumference; + int get waistCircumference; @override @JsonKey(name: 'hip_circumference') - String get hipCircumference; + int get hipCircumference; @override @JsonKey(name: 'blood_pressure_up') - String get bloodPressureUp; + int get bloodPressureUp; @override @JsonKey(name: 'blood_pressure_down') - String get bloodPressureDown; + int get bloodPressureDown; @override @JsonKey(name: 'has_hypo') - String get hasHypo; + int get hasHypo; @override @JsonKey(name: 'has_hyper') - String get hasHyper; + int get hasHyper; @override @JsonKey(name: 'about_alergy') String get aboutAllergy; @@ -803,7 +802,7 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { String get additionalInfo; @override @JsonKey(name: 'activity_coefficient') - String get activityCoefficient; + double get activityCoefficient; @override @JsonKey(ignore: true) _$$UserRegistrationSheetImplCopyWith<_$UserRegistrationSheetImpl> diff --git a/lib/data/models/userRegistrationModel/user_registration_model.g.dart b/lib/data/models/userRegistrationModel/user_registration_model.g.dart index 8eafe71..132240b 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.g.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.g.dart @@ -11,7 +11,7 @@ _$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson( _$UserRegistrationSheetImpl( name: json['name'] as String, firstName: json['first_name'] as String, - lastName: json['last'] as String, + lastName: json['last_name'] as String, email: json['email'] as String, password: json['password'] as String, passwordConfirmation: json['password_confirmation'] as String, @@ -21,22 +21,23 @@ _$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson( country: json['country'] as String, city: json['city'] as String, lang: json['lang'] as String, - weight: json['weight'] as String, - height: json['height'] as String, - chestCircumference: json['chest_circumference'] as String, - waistCircumference: json['waist_circumference'] as String, - hipCircumference: json['hip_circumference'] as String, - bloodPressureUp: json['blood_pressure_up'] as String, - bloodPressureDown: json['blood_pressure_down'] as String, - hasHypo: json['has_hypo'] as String, - hasHyper: json['has_hyper'] 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 String? ?? '1.2', + activityCoefficient: + (json['activity_coefficient'] as num?)?.toDouble() ?? 1.2, ); Map _$$UserRegistrationSheetImplToJson( @@ -44,7 +45,7 @@ Map _$$UserRegistrationSheetImplToJson( { 'name': instance.name, 'first_name': instance.firstName, - 'last': instance.lastName, + 'last_name': instance.lastName, 'email': instance.email, 'password': instance.password, 'password_confirmation': instance.passwordConfirmation, diff --git a/lib/presentation/registration/city_of_living_screen/city_of_living_screen.dart b/lib/features/registration/consts/cities_list.dart similarity index 79% rename from lib/presentation/registration/city_of_living_screen/city_of_living_screen.dart rename to lib/features/registration/consts/cities_list.dart index 1e5f01b..728024d 100644 --- a/lib/presentation/registration/city_of_living_screen/city_of_living_screen.dart +++ b/lib/features/registration/consts/cities_list.dart @@ -1,159 +1,4 @@ -import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; -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/custom_drop_down.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 StatefulWidget { - final UserRegistrationSheet sheet; - - const CityOfLivingScreen({super.key, required this.sheet}); - - @override - State createState() => _CityOfLivingScreenState(); -} - -class _CityOfLivingScreenState extends State { - @override - Widget build(BuildContext context) { - return BlocProvider( - create: (BuildContext context) => - CityOfLivingBloc(CityOfLivingState(cityOfLivingModelObj: CityOfLivingModel(userRegistrationSheet: widget.sheet)))..add(CityOfLivingInitialEvent()), - child: 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), - 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), - ), - ); - }, - ), - ), - ), - ); - }, - ); - }, - ), - ], - ), - ), - ), - ); - } - - 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)); - final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(country: value)); - }; - } - - 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, BuildContext context) { - state.cityController?.text = option; - final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(city: option)); - return () { - onSelected(option); - }; -} - -buildOptions(List _options) { - return (TextEditingValue textEditingValue) { - return _options.where((String option) { - return true; - }); - }; -} - -const List _options = const [ +const List citiesList = const [ "Абаза", "Абакан", "Абдулино", @@ -1271,4 +1116,4 @@ const List _options = const [ "Ясногорск", "Ясный", "Яхрома", -]; +]; \ No newline at end of file diff --git a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart index e882ead..c39f834 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart @@ -2,12 +2,43 @@ 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_state.dart'; import 'package:eatvio_app/features/registration/repositories/registration_repository.dart'; -import 'package:eatvio_app/presentation/registration/language_select_screen/models/language_select_model.dart'; class RegistrationCubit extends Cubit { final RegistrationRepository registrationRepository; - RegistrationCubit({required this.registrationRepository}) : super(RegistrationState(sheet: LanguageSelectModel().userRegistrationSheet)); + 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)); diff --git a/lib/presentation/registration/additional_information_screen/additional_information_screen.dart b/lib/features/registration/presentation/pages/additional_information_screen.dart similarity index 100% rename from lib/presentation/registration/additional_information_screen/additional_information_screen.dart rename to lib/features/registration/presentation/pages/additional_information_screen.dart diff --git a/lib/presentation/registration/allergies_screen/allergies_screen.dart b/lib/features/registration/presentation/pages/allergies_screen.dart similarity index 100% rename from lib/presentation/registration/allergies_screen/allergies_screen.dart rename to lib/features/registration/presentation/pages/allergies_screen.dart diff --git a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart b/lib/features/registration/presentation/pages/blood_pressure_screen.dart similarity index 89% rename from lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart rename to lib/features/registration/presentation/pages/blood_pressure_screen.dart index 3566933..c423666 100644 --- a/lib/presentation/registration/blood_pressure_screen/blood_pressure_screen.dart +++ b/lib/features/registration/presentation/pages/blood_pressure_screen.dart @@ -22,7 +22,7 @@ class _BloodPressureScreenState extends State { title: "Да", ), SelectionPopupModel( - id: 2, + id: 0, title: "Нет", ), ]; @@ -39,14 +39,10 @@ class _BloodPressureScreenState extends State { super.initState(); selectedPopupHypo = selectionPopupList[1]; selectedPopupHyper = selectionPopupList[1]; - upPressureController.text = widget.sheet.bloodPressureUp; - downPressureController.text = widget.sheet.bloodPressureDown; - if (widget.sheet.hasHyper.isNotEmpty) { - widget.sheet.hasHyper == 'Да' ? selectedPopupHyper = selectionPopupList[0] : selectedPopupHyper = selectionPopupList[1]; - } - if (widget.sheet.hasHypo.isNotEmpty) { - widget.sheet.hasHypo == 'Да' ? selectedPopupHypo = selectionPopupList[0] : selectedPopupHypo = 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 @@ -82,7 +78,7 @@ class _BloodPressureScreenState extends State { hintText: "90".tr, onChanged: (newValue) { final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(bloodPressureUp: newValue)); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(bloodPressureUp: int.parse(newValue))); }, ), ], @@ -102,7 +98,7 @@ class _BloodPressureScreenState extends State { hintText: "90".tr, onChanged: (newValue) { final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(bloodPressureDown: newValue)); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(bloodPressureDown: int.parse(newValue))); }, ), ], @@ -126,7 +122,7 @@ class _BloodPressureScreenState extends State { setState(() { selectedPopupHypo = newPopup; final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(hasHypo: selectedPopupHypo.title)); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(hasHypo: selectedPopupHypo.id!)); }); }, ), @@ -149,7 +145,7 @@ class _BloodPressureScreenState extends State { setState(() { selectedPopupHyper = newPopup; final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(hasHyper: selectedPopupHyper.title)); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(hasHyper: selectedPopupHyper.id!)); }); }, ), diff --git a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart b/lib/features/registration/presentation/pages/body_circumferences_screen.dart similarity index 85% rename from lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart rename to lib/features/registration/presentation/pages/body_circumferences_screen.dart index 60576c8..06417c8 100644 --- a/lib/presentation/registration/body_circumferences_screen/body_circumferences_screen.dart +++ b/lib/features/registration/presentation/pages/body_circumferences_screen.dart @@ -24,9 +24,9 @@ class _BodyCircumferencesScreenState extends State { @override void initState() { super.initState(); - chestCircumferenceController.text = widget.sheet.chestCircumference; - waistCircumferenceController.text = widget.sheet.waistCircumference; - hipCircumferenceController.text = widget.sheet.hipCircumference; + 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 @@ -50,7 +50,7 @@ class _BodyCircumferencesScreenState extends State { hintText: "90".tr, onChanged: (value) { final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(chestCircumference: value)); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(chestCircumference: int.parse(value))); }, ), ], @@ -64,7 +64,7 @@ class _BodyCircumferencesScreenState extends State { hintText: "60".tr, onChanged: (value) { final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(waistCircumference: value)); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(waistCircumference: int.parse(value))); }, ), SizedBox(height: 21.v), @@ -77,7 +77,7 @@ class _BodyCircumferencesScreenState extends State { textInputAction: TextInputAction.done, onChanged: (value) { final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(hipCircumference: value)); + 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 0000000..b183ec9 --- /dev/null +++ b/lib/features/registration/presentation/pages/city_of_living_screen.dart @@ -0,0 +1,88 @@ +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/core/app_export.dart'; +import 'package:eatvio_app/widgets/custom_drop_down.dart'; +import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.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/presentation/registration/credentials_screen/credentials_screen.dart b/lib/features/registration/presentation/pages/credentials_screen.dart similarity index 100% rename from lib/presentation/registration/credentials_screen/credentials_screen.dart rename to lib/features/registration/presentation/pages/credentials_screen.dart diff --git a/lib/presentation/registration/date_of_birth_screen/date_of_birth_screen.dart b/lib/features/registration/presentation/pages/date_of_birth_screen.dart similarity index 100% rename from lib/presentation/registration/date_of_birth_screen/date_of_birth_screen.dart rename to lib/features/registration/presentation/pages/date_of_birth_screen.dart diff --git a/lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart b/lib/features/registration/presentation/pages/favorite_foods_screen.dart similarity index 100% rename from lib/presentation/registration/favorite_foods_screen/favorite_foods_screen.dart rename to lib/features/registration/presentation/pages/favorite_foods_screen.dart diff --git a/lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart b/lib/features/registration/presentation/pages/favorite_sports_screen.dart similarity index 100% rename from lib/presentation/registration/favorite_sports_screen/favorite_sports_screen.dart rename to lib/features/registration/presentation/pages/favorite_sports_screen.dart diff --git a/lib/presentation/registration/gender_screen/gender_screen.dart b/lib/features/registration/presentation/pages/gender_screen.dart similarity index 100% rename from lib/presentation/registration/gender_screen/gender_screen.dart rename to lib/features/registration/presentation/pages/gender_screen.dart diff --git a/lib/presentation/registration/height_screen/height_screen.dart b/lib/features/registration/presentation/pages/height_screen.dart similarity index 93% rename from lib/presentation/registration/height_screen/height_screen.dart rename to lib/features/registration/presentation/pages/height_screen.dart index 9936418..a2f47e0 100644 --- a/lib/presentation/registration/height_screen/height_screen.dart +++ b/lib/features/registration/presentation/pages/height_screen.dart @@ -20,7 +20,7 @@ class _HeightScreenState extends State { @override void initState() { super.initState(); - heightController.text = widget.sheet.height; + if (widget.sheet.height != 0) heightController.text = widget.sheet.height.toString(); } @override @@ -54,7 +54,7 @@ class _HeightScreenState extends State { ], onChanged: (newValue) { final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(height: newValue)); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(height: int.parse(newValue))); }, ), ], diff --git a/lib/presentation/registration/language_select_screen/language_select_screen.dart b/lib/features/registration/presentation/pages/language_select_screen.dart similarity index 100% rename from lib/presentation/registration/language_select_screen/language_select_screen.dart rename to lib/features/registration/presentation/pages/language_select_screen.dart diff --git a/lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart b/lib/features/registration/presentation/pages/medicine_intake_screen.dart similarity index 100% rename from lib/presentation/registration/medicine_intake_screen/medicine_intake_screen.dart rename to lib/features/registration/presentation/pages/medicine_intake_screen.dart diff --git a/lib/presentation/registration/name_screen/name_screen.dart b/lib/features/registration/presentation/pages/name_screen.dart similarity index 100% rename from lib/presentation/registration/name_screen/name_screen.dart rename to lib/features/registration/presentation/pages/name_screen.dart diff --git a/lib/features/registration/presentation/pages/registration_screen.dart b/lib/features/registration/presentation/pages/registration_screen.dart index 074d67f..30eb759 100644 --- a/lib/features/registration/presentation/pages/registration_screen.dart +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -1,22 +1,22 @@ 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/allergies_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/city_of_living_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/favorite_foods_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/height_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/name_screen.dart'; import 'package:eatvio_app/locator_service.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/registration/presentation/pages/additional_information_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/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_sports_screen.dart'; +import 'package:eatvio_app/features/registration/presentation/pages/gender_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/weight_screen.dart'; import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -34,6 +34,7 @@ class _RegistrationScreenState extends State { double progressValue = 1 / 15; int step = 1; final pageController = PageController(); + final RegistrationCubit registrationCubit = sl(); _showPopDialog() { showDialog( @@ -63,7 +64,7 @@ class _RegistrationScreenState extends State { @override Widget build(BuildContext context) { return BlocProvider( - create: (BuildContext context) => sl(), + create: (BuildContext context) => registrationCubit, child: BlocBuilder( builder: (BuildContext context, RegistrationState state) { return PopScope( @@ -225,7 +226,10 @@ class _RegistrationScreenState extends State { return false; } case 3: - List errors = validateNameFields(state.sheet.firstName, state.sheet.lastName); + List errors = validateNameFields( + state.sheet.firstName.toString(), + state.sheet.lastName.toString(), + ); if (errors.isEmpty) { return true; } else { @@ -251,7 +255,11 @@ class _RegistrationScreenState extends State { return false; } case 7: - List errors = validateCircumferencesFields(state.sheet.chestCircumference, state.sheet.waistCircumference, state.sheet.hipCircumference); + List errors = validateCircumferencesFields( + state.sheet.chestCircumference.toString(), + state.sheet.waistCircumference.toString(), + state.sheet.hipCircumference.toString(), + ); if (errors.isEmpty) { return true; } else { @@ -277,7 +285,7 @@ class _RegistrationScreenState extends State { return false; } case 15: - context.read().tryRegistration(); + registrationCubit.tryRegistration(); return true; default: return true; diff --git a/lib/presentation/registration/weight_screen/weight_screen.dart b/lib/features/registration/presentation/pages/weight_screen.dart similarity index 93% rename from lib/presentation/registration/weight_screen/weight_screen.dart rename to lib/features/registration/presentation/pages/weight_screen.dart index a8a59ca..6c64ad1 100644 --- a/lib/presentation/registration/weight_screen/weight_screen.dart +++ b/lib/features/registration/presentation/pages/weight_screen.dart @@ -20,7 +20,7 @@ class _WeightScreenState extends State { @override void initState() { super.initState(); - weightController.text = widget.sheet.weight; + if (widget.sheet.weight != 0) weightController.text = widget.sheet.weight.toString(); } @override @@ -54,7 +54,7 @@ class _WeightScreenState extends State { ], onChanged: (newValue) { final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(weight: newValue)); + 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 index bbaf43f..8642094 100644 --- a/lib/features/registration/repositories/registration_repository.dart +++ b/lib/features/registration/repositories/registration_repository.dart @@ -8,9 +8,9 @@ class RegistrationRepository { tryRegister(UserRegistrationSheet sheet) async { try { - return await registrationService.register(sheet: sheet); + return await registrationService.register(sheet: sheet.copyWith(country: 'Россия', city: 'Москва').toJson()); } catch (e) { rethrow; } } -} \ No newline at end of file +} diff --git a/lib/features/registration/services/registration_service.dart b/lib/features/registration/services/registration_service.dart index f7c41ec..9ff8108 100644 --- a/lib/features/registration/services/registration_service.dart +++ b/lib/features/registration/services/registration_service.dart @@ -1,5 +1,4 @@ import 'package:dio/dio.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; import 'package:retrofit/retrofit.dart'; part 'registration_service.g.dart'; @@ -10,6 +9,6 @@ abstract class RegistrationService { @POST('/register') Future register({ - @Body() required UserRegistrationSheet sheet, + @Body() required Map sheet, }); } diff --git a/lib/features/registration/services/registration_service.g.dart b/lib/features/registration/services/registration_service.g.dart index 4414079..0a7fc8f 100644 --- a/lib/features/registration/services/registration_service.g.dart +++ b/lib/features/registration/services/registration_service.g.dart @@ -19,11 +19,12 @@ class _RegistrationService implements RegistrationService { String? baseUrl; @override - Future register({required UserRegistrationSheet sheet}) async { + Future register({required Map sheet}) async { final _extra = {}; final queryParameters = {}; final _headers = {}; - final _data = sheet; + final _data = {}; + _data.addAll(sheet); await _dio.fetch(_setStreamType(Options( method: 'POST', headers: _headers, diff --git a/lib/presentation/auth/auth_screen/auth_screen.dart b/lib/presentation/auth/auth_screen/auth_screen.dart index c299013..ad32b70 100644 --- a/lib/presentation/auth/auth_screen/auth_screen.dart +++ b/lib/presentation/auth/auth_screen/auth_screen.dart @@ -1,5 +1,6 @@ import 'package:eatvio_app/core/token_storage.dart'; import 'package:go_router/go_router.dart'; +import 'package:url_launcher/url_launcher.dart'; import 'bloc/auth_bloc.dart'; import 'models/auth_model.dart'; @@ -33,43 +34,46 @@ class AuthScreen extends StatelessWidget { 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 +85,27 @@ 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), + ); + }, + ), + TextButton( + onPressed: () async { + await launchUrl(Uri.parse(dotenv.env['OFERTA']!)); + }, + child: Text('Пользовательское соглашение'), + ), + ], + ), + ), + ), + ); } onTapAuth(AuthState state, BuildContext context) { @@ -99,8 +116,12 @@ 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(dotenv.env['SERVER_ROOT']! + '/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); 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 b2405c5..0000000 --- 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 71494f8..0000000 --- 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 08dd10c..0000000 --- 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 ff001d9..0000000 --- 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/bloc/allergies_bloc.dart b/lib/presentation/registration/allergies_screen/bloc/allergies_bloc.dart deleted file mode 100644 index f4cf7a2..0000000 --- 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 8892cc3..0000000 --- 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 a63c52d..0000000 --- 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 ebd2006..0000000 --- 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 cbf92f0..0000000 --- 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 adb5110..0000000 --- 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 649738e..0000000 --- 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 2ee3346..0000000 --- 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 73fd71d..0000000 --- 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 64e3e01..0000000 --- a/lib/presentation/registration/blood_pressure_screen/bloc/blood_pressure_bloc.dart +++ /dev/null @@ -1,72 +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 677d243..0000000 --- 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 d1db1c4..0000000 --- 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/models/blood_pressure_model.dart b/lib/presentation/registration/blood_pressure_screen/models/blood_pressure_model.dart deleted file mode 100644 index 2d8463e..0000000 --- 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 871ff8d..0000000 --- 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 d164270..0000000 --- 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 df28755..0000000 --- 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/models/body_circumferences_model.dart b/lib/presentation/registration/body_circumferences_screen/models/body_circumferences_model.dart deleted file mode 100644 index 2af76f9..0000000 --- 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 e642961..0000000 --- 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 d841812..0000000 --- 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 5179b21..0000000 --- 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/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 24eb6d9..0000000 --- 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 f0d45cc..0000000 --- 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 3001076..0000000 --- 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 e127da6..0000000 --- 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/models/credentials_model.dart b/lib/presentation/registration/credentials_screen/models/credentials_model.dart deleted file mode 100644 index ae6c320..0000000 --- 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 78dec54..0000000 --- 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 0d6938b..0000000 --- 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 e54b82c..0000000 --- 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/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 121b10d..0000000 --- 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 b949491..0000000 --- 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 f930b8e..0000000 --- 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 aa4fc3b..0000000 --- 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/models/favorite_foods_model.dart b/lib/presentation/registration/favorite_foods_screen/models/favorite_foods_model.dart deleted file mode 100644 index 3aeeee2..0000000 --- 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 7857f8b..0000000 --- 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 ae9a018..0000000 --- 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 c44cb2a..0000000 --- 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/models/favorite_sports_model.dart b/lib/presentation/registration/favorite_sports_screen/models/favorite_sports_model.dart deleted file mode 100644 index 2548170..0000000 --- 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 fe30581..0000000 --- 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 f6b9f69..0000000 --- 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 996082e..0000000 --- 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/models/gender_model.dart b/lib/presentation/registration/gender_screen/models/gender_model.dart deleted file mode 100644 index 69779b4..0000000 --- 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 223f719..0000000 --- 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 1d65dd8..0000000 --- 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 aa10592..0000000 --- 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/models/height_model.dart b/lib/presentation/registration/height_screen/models/height_model.dart deleted file mode 100644 index 3a56580..0000000 --- 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 7604717..0000000 --- a/lib/presentation/registration/language_select_screen/bloc/language_select_bloc.dart +++ /dev/null @@ -1,35 +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 5c39a95..0000000 --- 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 602a4ad..0000000 --- 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/models/language_select_model.dart b/lib/presentation/registration/language_select_screen/models/language_select_model.dart deleted file mode 100644 index c337c55..0000000 --- a/lib/presentation/registration/language_select_screen/models/language_select_model.dart +++ /dev/null @@ -1,51 +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 bd87876..0000000 --- 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 0300b28..0000000 --- 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 8d7958f..0000000 --- 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/models/medicine_intake_model.dart b/lib/presentation/registration/medicine_intake_screen/models/medicine_intake_model.dart deleted file mode 100644 index f6634de..0000000 --- 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 e4a5143..0000000 --- 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 7e10299..0000000 --- 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 b3e0980..0000000 --- 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 6fa44b0..0000000 --- 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/splash_screen/bloc/splash_bloc.dart b/lib/presentation/registration/splash_screen/bloc/splash_bloc.dart deleted file mode 100644 index bdd396f..0000000 --- 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 a78a25b..0000000 --- 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 e47ce03..0000000 --- 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 6ad8f8f..0000000 --- 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 f8355f0..0000000 --- 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 f03c8c3..0000000 --- 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 1b554c5..0000000 --- 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 5d782df..0000000 --- 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 d5edd07..0000000 --- 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]; -} -- 2.49.1 From d859a15cfdaf5975f16910cf9c44bfc7bd013e6a Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Mon, 15 Jul 2024 17:06:13 +0300 Subject: [PATCH 062/110] feature(registration): remove .env --- .env | 3 - .gitea/workflows/build.yml | 1 - .gitea/workflows/test.yml | 1 - .gitignore | 1 - lib/app_router.dart | 10 +- lib/core/app_export.dart | 5 +- lib/core/constants/constants.dart | 2 +- lib/core/errors/exceptions.dart | 5 +- .../initialization_state.freezed.dart | 90 ++--- lib/core/utils/image_constant.dart | 18 +- lib/core/utils/progress_dialog_utils.dart | 23 +- lib/core/utils/size_utils.dart | 6 +- .../selection_popup_model.dart | 3 +- .../selection_popup_model.freezed.dart | 43 +-- lib/data/models/tokenModel/token_model.dart | 1 + .../user_registration_model.dart | 56 +-- .../user_registration_model.freezed.dart | 120 ++----- .../user_registration_model.g.dart | 11 +- .../blog_post/models/blog_post_model.dart | 3 +- .../models/blog_post_model.freezed.dart | 58 +-- .../blog_post/models/blog_post_model.g.dart | 6 +- .../presentation/bloc/blog_post_cubit.dart | 3 +- .../bloc/blog_post_state.freezed.dart | 82 ++--- .../presentation/pages/blog_post_screen.dart | 18 +- .../blog_post/services/blog_post_service.dart | 2 +- .../services/blog_post_service.g.dart | 29 +- .../blog_post_create_credentials_model.dart | 1 + .../pages/blog_post_create_screen.dart | 38 +- .../repositories/blog_repository.dart | 3 +- .../services/blog_service.dart | 7 +- .../services/blog_service.g.dart | 32 +- .../new_messages_state.freezed.dart | 86 ++--- .../notifications_state.freezed.dart | 89 ++--- .../widgets/bottom_navigation_bar_widget.dart | 4 +- .../chat/models/chat_message_model.dart | 1 - .../models/chat_message_model.freezed.dart | 59 ++-- .../chat/models/chat_message_model.g.dart | 8 +- .../chat/models/chat_messages_model.dart | 1 - .../models/chat_messages_model.freezed.dart | 62 +--- .../chat/models/chat_messages_model.g.dart | 12 +- lib/features/chat/models/chat_meta_model.dart | 1 - .../chat/models/chat_meta_model.freezed.dart | 49 +-- .../chat/models/chat_meta_model.g.dart | 6 +- lib/features/chat/models/chat_room_model.dart | 1 - .../chat/models/chat_room_model.freezed.dart | 68 +--- .../chat/models/chat_room_model.g.dart | 12 +- .../chat/models/chat_room_settings_model.dart | 1 - .../chat_room_settings_model.freezed.dart | 65 ++-- .../models/chat_room_settings_model.g.dart | 8 +- lib/features/chat/models/chat_user_model.dart | 7 +- .../chat/models/chat_user_model.freezed.dart | 67 ++-- .../chat/models/chat_user_model.g.dart | 6 +- .../chat/models/websocket_info_model.dart | 4 +- .../models/websocket_info_model.freezed.dart | 68 ++-- .../chat/models/websocket_info_model.g.dart | 8 +- .../chat_room_state.freezed.dart | 161 +++------ .../chat/presentation/pages/chat_screen.dart | 6 +- .../bloc/chat_select_bloc.dart | 10 +- .../bloc/chat_select_state.dart | 3 +- .../chat_select_screen/chat_search_view.dart | 2 +- .../chat_select_screen.dart | 9 +- .../widgets/chat_entry_widget.dart | 2 +- .../presentation/pages/photo_view_screen.dart | 3 +- .../widgets/chat_bubble_widget.dart | 10 +- lib/features/chat/services/chat_service.dart | 10 +- .../chat/services/chat_service.g.dart | 84 ++--- .../diary/models/diary_model.freezed.dart | 58 +-- lib/features/diary/models/diary_model.g.dart | 10 +- .../diary/presentation/bloc/diary_cubit.dart | 2 +- .../diary/presentation/bloc/diary_state.dart | 2 +- .../presentation/pages/diary_screen.dart | 6 +- .../diary/repositories/diary_repository.dart | 2 +- .../diary/services/diary_service.dart | 4 +- .../models/feed_blog_post_model.freezed.dart | 51 +-- .../feed/models/feed_blog_post_model.g.dart | 8 +- .../models/feed_blog_post_settings_model.dart | 3 +- ...feed_blog_post_settings_model.freezed.dart | 63 +--- .../feed_blog_post_settings_model.g.dart | 12 +- .../bloc/feed_cubit/feed_state.freezed.dart | 95 ++--- .../feed/presentation/pages/feed_screen.dart | 15 +- lib/features/feed/services/feed_service.dart | 2 +- .../feed/services/feed_service.g.dart | 29 +- .../registration/consts/cities_list.dart | 2 +- .../registration_state.freezed.dart | 37 +- .../pages/additional_information_screen.dart | 4 +- .../pages/blood_pressure_screen.dart | 6 +- .../pages/body_circumferences_screen.dart | 5 +- .../pages/city_of_living_screen.dart | 4 +- .../pages/credentials_screen.dart | 2 +- .../pages/date_of_birth_screen.dart | 40 +-- .../pages/favorite_foods_screen.dart | 2 +- .../pages/favorite_sports_screen.dart | 5 +- .../presentation/pages/gender_screen.dart | 4 +- .../presentation/pages/height_screen.dart | 6 +- .../pages/medicine_intake_screen.dart | 4 +- .../presentation/pages/name_screen.dart | 2 +- .../pages/registration_screen.dart | 12 +- .../presentation/pages/weight_screen.dart | 6 +- .../services/registration_service.dart | 2 +- .../services/registration_service.g.dart | 6 +- lib/localization/app_localization.dart | 22 +- .../en_us/en_us_translations.dart | 9 +- lib/localization/ru/ru_translations.dart | 6 +- lib/locator_service.dart | 4 +- lib/main.dart | 9 +- .../auth/auth_screen/auth_screen.dart | 40 +-- .../auth/auth_screen/bloc/auth_bloc.dart | 4 +- .../bloc/diary_edit_bloc.dart | 55 +-- .../bloc/diary_edit_event.dart | 17 +- .../diary_edit_screen/diary_edit_screen.dart | 22 +- .../models/diary_edit_model.dart | 2 +- .../bloc/diet_create_bloc.dart | 37 +- .../bloc/diet_create_state.dart | 3 +- .../diet_create_screen.dart | 95 ++--- .../diet_edit_screen/bloc/diet_edit_bloc.dart | 25 +- .../bloc/diet_edit_state.dart | 12 +- .../diet_edit_screen/diet_edit_screen.dart | 15 +- .../bloc/diet_select_bloc.dart | 34 +- .../bloc/diet_select_state.dart | 6 +- .../diet_select_screen.dart | 98 +++--- .../diet_show_screen/bloc/diet_show_bloc.dart | 13 +- .../bloc/diet_show_state.dart | 6 +- .../diet_show_screen/diet_show_screen.dart | 84 ++--- .../bloc/blog_post_create_bloc.dart | 17 +- .../bloc/blog_post_create_state.dart | 6 +- ...post_create_credentials_model.freezed.dart | 81 ++--- .../blog_post_create_credentials_model.g.dart | 18 +- .../models/blog_post_create_model.dart | 3 +- .../bloc/blog_post_edit_bloc.dart | 25 +- .../bloc/blog_post_edit_state.dart | 6 +- .../blog_post_edit_screen.dart | 20 +- .../models/blog_post_model.dart | 2 +- .../models/comment_model.dart | 13 +- .../widgets/comment_widget.dart | 27 +- .../feed_screen/widgets/feed_scroll_item.dart | 2 +- .../feed_screen/widgets/feed_search_view.dart | 61 ++-- .../bloc/glossary_screen_bloc.dart | 53 ++- .../bloc/glossary_screen_state.dart | 28 +- .../glossary_screen/glossary_screen.dart | 195 +++++----- .../widgets/glossary_scroll_item.dart | 2 +- .../widgets/glossary_search_widget.dart | 61 ++-- .../bloc/plan_create_bloc.dart | 40 ++- .../bloc/plan_create_state.dart | 3 +- .../plan_create_screen.dart | 49 +-- .../plan_edit_screen/bloc/plan_edit_bloc.dart | 27 +- .../bloc/plan_edit_state.dart | 12 +- .../plan_edit_screen/plan_edit_screen.dart | 15 +- .../bloc/plan_select_bloc.dart | 34 +- .../bloc/plan_select_state.dart | 6 +- .../plan_select_screen.dart | 19 +- .../plan_show_screen/bloc/plan_show_bloc.dart | 13 +- .../bloc/plan_show_state.dart | 6 +- .../plan_show_screen/plan_show_screen.dart | 85 ++--- .../bloc/my_profile_bloc.dart | 18 +- .../bloc/my_profile_state.dart | 122 +++---- .../my_profile_screen/my_profile_screen.dart | 32 +- .../my_profile_screen/my_settings_screen.dart | 73 ++-- .../bloc/recipe_create_bloc.dart | 81 +++-- .../bloc/recipe_create_state.dart | 39 +- .../recipe_create_screen.dart | 333 +++++++++--------- .../bloc/recipe_edit_bloc.dart | 15 +- .../bloc/recipe_edit_state.dart | 29 +- .../recipe_edit_screen.dart | 312 ++++++++-------- .../bloc/recipe_select_bloc.dart | 12 +- .../recipe_select_screen.dart | 99 +++--- .../bloc/recipe_show_bloc.dart | 23 +- .../bloc/recipe_show_state.dart | 41 +-- .../recipe_show_screen.dart | 255 +++++++------- .../widgets/comment_widget.dart | 27 +- .../bloc/subscribers_bloc.dart | 14 +- .../bloc/subscribers_state.dart | 6 +- .../subscribers_screen.dart | 35 +- lib/theme/app_decoration.dart | 2 +- lib/theme/bloc/theme_bloc.dart | 2 + lib/theme/custom_text_style.dart | 1 + lib/theme/theme_helper.dart | 1 + lib/widgets/chart_axis.dart | 2 +- lib/widgets/chart_bars.dart | 2 +- lib/widgets/custom_about_list.dart | 12 +- lib/widgets/custom_expandable_list.dart | 299 ++++++++-------- lib/widgets/custom_hyper_switch.dart | 7 +- lib/widgets/custom_hypo_switch.dart | 7 +- lib/widgets/custom_icon_button.dart | 3 +- lib/widgets/custom_navigation_menu.dart | 5 +- lib/widgets/custom_navigation_menu_item.dart | 2 +- lib/widgets/custom_notification_screen.dart | 7 +- lib/widgets/custom_text_form_field.dart | 2 +- pubspec.yaml | 4 +- 188 files changed, 2509 insertions(+), 3147 deletions(-) delete mode 100644 .env diff --git a/.env b/.env deleted file mode 100644 index 0f129f5..0000000 --- a/.env +++ /dev/null @@ -1,3 +0,0 @@ -SERVER_ROOT='https://mobile-stage.eatvio.ru/api' -STORAGE_URL='https://mobile-stage.eatvio.ru/storage/' -OFERTA='https://mobile-stage.eatvio.ru/oferta_bs.pdf' \ No newline at end of file diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 955d74d..e8e1609 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 a21834f..54d180c 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 9d9b1ce..4a5c4e7 100644 --- a/.gitignore +++ b/.gitignore @@ -6,5 +6,4 @@ /.flutter-plugins /.flutter-plugins-dependencies /.packages -/.env /node_modules/ diff --git a/lib/app_router.dart b/lib/app_router.dart index 8f16666..9c23dd0 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -1,23 +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/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'; diff --git a/lib/core/app_export.dart b/lib/core/app_export.dart index ae95a22..76a7955 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 8b13789..c0353c4 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 d7d4de8..7cbb3f1 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_state.freezed.dart b/lib/core/initialization_cubit/initialization_state.freezed.dart index 3364e44..b5e8e4d 100644 --- a/lib/core/initialization_cubit/initialization_state.freezed.dart +++ b/lib/core/initialization_cubit/initialization_state.freezed.dart @@ -70,14 +70,12 @@ mixin _$InitializationState { /// @nodoc abstract class $InitializationStateCopyWith<$Res> { - factory $InitializationStateCopyWith( - InitializationState value, $Res Function(InitializationState) then) = + factory $InitializationStateCopyWith(InitializationState value, $Res Function(InitializationState) then) = _$InitializationStateCopyWithImpl<$Res, InitializationState>; } /// @nodoc -class _$InitializationStateCopyWithImpl<$Res, $Val extends InitializationState> - implements $InitializationStateCopyWith<$Res> { +class _$InitializationStateCopyWithImpl<$Res, $Val extends InitializationState> implements $InitializationStateCopyWith<$Res> { _$InitializationStateCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -88,18 +86,14 @@ class _$InitializationStateCopyWithImpl<$Res, $Val extends InitializationState> /// @nodoc abstract class _$$InitializationStateImplCopyWith<$Res> { - factory _$$InitializationStateImplCopyWith(_$InitializationStateImpl value, - $Res Function(_$InitializationStateImpl) then) = + factory _$$InitializationStateImplCopyWith(_$InitializationStateImpl value, $Res Function(_$InitializationStateImpl) then) = __$$InitializationStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$InitializationStateImplCopyWithImpl<$Res> - extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateImpl> +class __$$InitializationStateImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateImpl> implements _$$InitializationStateImplCopyWith<$Res> { - __$$InitializationStateImplCopyWithImpl(_$InitializationStateImpl _value, - $Res Function(_$InitializationStateImpl) _then) - : super(_value, _then); + __$$InitializationStateImplCopyWithImpl(_$InitializationStateImpl _value, $Res Function(_$InitializationStateImpl) _then) : super(_value, _then); } /// @nodoc @@ -114,9 +108,7 @@ class _$InitializationStateImpl implements _InitializationState { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$InitializationStateImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$InitializationStateImpl); } @override @@ -203,20 +195,14 @@ abstract class _InitializationState implements InitializationState { /// @nodoc abstract class _$$InitializationStateLoadingImplCopyWith<$Res> { - factory _$$InitializationStateLoadingImplCopyWith( - _$InitializationStateLoadingImpl value, - $Res Function(_$InitializationStateLoadingImpl) then) = + factory _$$InitializationStateLoadingImplCopyWith(_$InitializationStateLoadingImpl value, $Res Function(_$InitializationStateLoadingImpl) then) = __$$InitializationStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$InitializationStateLoadingImplCopyWithImpl<$Res> - extends _$InitializationStateCopyWithImpl<$Res, - _$InitializationStateLoadingImpl> +class __$$InitializationStateLoadingImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateLoadingImpl> implements _$$InitializationStateLoadingImplCopyWith<$Res> { - __$$InitializationStateLoadingImplCopyWithImpl( - _$InitializationStateLoadingImpl _value, - $Res Function(_$InitializationStateLoadingImpl) _then) + __$$InitializationStateLoadingImplCopyWithImpl(_$InitializationStateLoadingImpl _value, $Res Function(_$InitializationStateLoadingImpl) _then) : super(_value, _then); } @@ -232,9 +218,7 @@ class _$InitializationStateLoadingImpl implements InitializationStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$InitializationStateLoadingImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$InitializationStateLoadingImpl); } @override @@ -321,22 +305,16 @@ abstract class InitializationStateLoading implements InitializationState { /// @nodoc abstract class _$$InitializationStateSuccessImplCopyWith<$Res> { - factory _$$InitializationStateSuccessImplCopyWith( - _$InitializationStateSuccessImpl value, - $Res Function(_$InitializationStateSuccessImpl) then) = + factory _$$InitializationStateSuccessImplCopyWith(_$InitializationStateSuccessImpl value, $Res Function(_$InitializationStateSuccessImpl) then) = __$$InitializationStateSuccessImplCopyWithImpl<$Res>; @useResult $Res call({PusherChannelsClient client}); } /// @nodoc -class __$$InitializationStateSuccessImplCopyWithImpl<$Res> - extends _$InitializationStateCopyWithImpl<$Res, - _$InitializationStateSuccessImpl> +class __$$InitializationStateSuccessImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateSuccessImpl> implements _$$InitializationStateSuccessImplCopyWith<$Res> { - __$$InitializationStateSuccessImplCopyWithImpl( - _$InitializationStateSuccessImpl _value, - $Res Function(_$InitializationStateSuccessImpl) _then) + __$$InitializationStateSuccessImplCopyWithImpl(_$InitializationStateSuccessImpl _value, $Res Function(_$InitializationStateSuccessImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -369,9 +347,7 @@ class _$InitializationStateSuccessImpl implements InitializationStateSuccess { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$InitializationStateSuccessImpl && - (identical(other.client, client) || other.client == client)); + (other.runtimeType == runtimeType && other is _$InitializationStateSuccessImpl && (identical(other.client, client) || other.client == client)); } @override @@ -380,9 +356,8 @@ class _$InitializationStateSuccessImpl implements InitializationStateSuccess { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> - get copyWith => __$$InitializationStateSuccessImplCopyWithImpl< - _$InitializationStateSuccessImpl>(this, _$identity); + _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> get copyWith => + __$$InitializationStateSuccessImplCopyWithImpl<_$InitializationStateSuccessImpl>(this, _$identity); @override @optionalTypeArgs @@ -460,34 +435,25 @@ class _$InitializationStateSuccessImpl implements InitializationStateSuccess { } abstract class InitializationStateSuccess implements InitializationState { - const factory InitializationStateSuccess( - {required final PusherChannelsClient client}) = - _$InitializationStateSuccessImpl; + const factory InitializationStateSuccess({required final PusherChannelsClient client}) = _$InitializationStateSuccessImpl; PusherChannelsClient get client; @JsonKey(ignore: true) - _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> - get copyWith => throw _privateConstructorUsedError; + _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$InitializationStateErrorImplCopyWith<$Res> { - factory _$$InitializationStateErrorImplCopyWith( - _$InitializationStateErrorImpl value, - $Res Function(_$InitializationStateErrorImpl) then) = + factory _$$InitializationStateErrorImplCopyWith(_$InitializationStateErrorImpl value, $Res Function(_$InitializationStateErrorImpl) then) = __$$InitializationStateErrorImplCopyWithImpl<$Res>; @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$InitializationStateErrorImplCopyWithImpl<$Res> - extends _$InitializationStateCopyWithImpl<$Res, - _$InitializationStateErrorImpl> +class __$$InitializationStateErrorImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateErrorImpl> implements _$$InitializationStateErrorImplCopyWith<$Res> { - __$$InitializationStateErrorImplCopyWithImpl( - _$InitializationStateErrorImpl _value, - $Res Function(_$InitializationStateErrorImpl) _then) + __$$InitializationStateErrorImplCopyWithImpl(_$InitializationStateErrorImpl _value, $Res Function(_$InitializationStateErrorImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -522,8 +488,7 @@ class _$InitializationStateErrorImpl implements InitializationStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$InitializationStateErrorImpl && - (identical(other.errorMessage, errorMessage) || - other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); } @override @@ -532,9 +497,8 @@ class _$InitializationStateErrorImpl implements InitializationStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> - get copyWith => __$$InitializationStateErrorImplCopyWithImpl< - _$InitializationStateErrorImpl>(this, _$identity); + _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> get copyWith => + __$$InitializationStateErrorImplCopyWithImpl<_$InitializationStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -612,11 +576,9 @@ class _$InitializationStateErrorImpl implements InitializationStateError { } abstract class InitializationStateError implements InitializationState { - const factory InitializationStateError({required final String errorMessage}) = - _$InitializationStateErrorImpl; + const factory InitializationStateError({required final String errorMessage}) = _$InitializationStateErrorImpl; String get errorMessage; @JsonKey(ignore: true) - _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> - get copyWith => throw _privateConstructorUsedError; + _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/core/utils/image_constant.dart b/lib/core/utils/image_constant.dart index 07aa9ab..6a7785a 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 98cdac0..ced3347 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 5595377..04f09c8 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 82c519c..f304e8d 100644 --- a/lib/data/models/selectionPopupModel/selection_popup_model.dart +++ b/lib/data/models/selectionPopupModel/selection_popup_model.dart @@ -8,7 +8,6 @@ class SelectionPopupModel with _$SelectionPopupModel { int? id, required String title, dynamic value, - @Default(false) - bool isSelected, + @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 index 917785c..85c5d00 100644 --- a/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart +++ b/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart @@ -22,22 +22,19 @@ mixin _$SelectionPopupModel { bool get isSelected => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $SelectionPopupModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $SelectionPopupModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $SelectionPopupModelCopyWith<$Res> { - factory $SelectionPopupModelCopyWith( - SelectionPopupModel value, $Res Function(SelectionPopupModel) then) = + 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> { +class _$SelectionPopupModelCopyWithImpl<$Res, $Val extends SelectionPopupModel> implements $SelectionPopupModelCopyWith<$Res> { _$SelectionPopupModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -75,10 +72,8 @@ class _$SelectionPopupModelCopyWithImpl<$Res, $Val extends SelectionPopupModel> } /// @nodoc -abstract class _$$SelectionPopupModelImplCopyWith<$Res> - implements $SelectionPopupModelCopyWith<$Res> { - factory _$$SelectionPopupModelImplCopyWith(_$SelectionPopupModelImpl value, - $Res Function(_$SelectionPopupModelImpl) then) = +abstract class _$$SelectionPopupModelImplCopyWith<$Res> implements $SelectionPopupModelCopyWith<$Res> { + factory _$$SelectionPopupModelImplCopyWith(_$SelectionPopupModelImpl value, $Res Function(_$SelectionPopupModelImpl) then) = __$$SelectionPopupModelImplCopyWithImpl<$Res>; @override @useResult @@ -86,12 +81,9 @@ abstract class _$$SelectionPopupModelImplCopyWith<$Res> } /// @nodoc -class __$$SelectionPopupModelImplCopyWithImpl<$Res> - extends _$SelectionPopupModelCopyWithImpl<$Res, _$SelectionPopupModelImpl> +class __$$SelectionPopupModelImplCopyWithImpl<$Res> extends _$SelectionPopupModelCopyWithImpl<$Res, _$SelectionPopupModelImpl> implements _$$SelectionPopupModelImplCopyWith<$Res> { - __$$SelectionPopupModelImplCopyWithImpl(_$SelectionPopupModelImpl _value, - $Res Function(_$SelectionPopupModelImpl) _then) - : super(_value, _then); + __$$SelectionPopupModelImplCopyWithImpl(_$SelectionPopupModelImpl _value, $Res Function(_$SelectionPopupModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -125,8 +117,7 @@ class __$$SelectionPopupModelImplCopyWithImpl<$Res> /// @nodoc class _$SelectionPopupModelImpl implements _SelectionPopupModel { - const _$SelectionPopupModelImpl( - {this.id, required this.title, this.value, this.isSelected = false}); + const _$SelectionPopupModelImpl({this.id, required this.title, this.value, this.isSelected = false}); @override final int? id; @@ -151,28 +142,21 @@ class _$SelectionPopupModelImpl implements _SelectionPopupModel { (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)); + (identical(other.isSelected, isSelected) || other.isSelected == isSelected)); } @override - int get hashCode => Object.hash(runtimeType, id, title, - const DeepCollectionEquality().hash(value), isSelected); + 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); + __$$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; + const factory _SelectionPopupModel({final int? id, required final String title, final dynamic value, final bool isSelected}) = _$SelectionPopupModelImpl; @override int? get id; @@ -184,6 +168,5 @@ abstract class _SelectionPopupModel implements SelectionPopupModel { bool get isSelected; @override @JsonKey(ignore: true) - _$$SelectionPopupModelImplCopyWith<_$SelectionPopupModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$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 3aa1d3f..ce310e2 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 686d206..5e30818 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.dart @@ -7,17 +7,12 @@ part 'user_registration_model.g.dart'; class UserRegistrationSheet with _$UserRegistrationSheet { const factory UserRegistrationSheet({ required String name, - @JsonKey(name: 'first_name') - required String firstName, - @JsonKey(name: 'last_name') - required String lastName, + @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, + @JsonKey(name: 'password_confirmation') required String passwordConfirmation, + @Default('accepted') @JsonKey(name: 'terms') String termsAccepted, required String birthdate, required String gender, required String country, @@ -25,35 +20,20 @@ class UserRegistrationSheet with _$UserRegistrationSheet { 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, + @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 index 4aa91df..6c44566 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart +++ b/lib/data/models/userRegistrationModel/user_registration_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'); -UserRegistrationSheet _$UserRegistrationSheetFromJson( - Map json) { +UserRegistrationSheet _$UserRegistrationSheetFromJson(Map json) { return _UserRegistrationSheet.fromJson(json); } @@ -70,14 +69,12 @@ mixin _$UserRegistrationSheet { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $UserRegistrationSheetCopyWith get copyWith => - throw _privateConstructorUsedError; + $UserRegistrationSheetCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $UserRegistrationSheetCopyWith<$Res> { - factory $UserRegistrationSheetCopyWith(UserRegistrationSheet value, - $Res Function(UserRegistrationSheet) then) = + factory $UserRegistrationSheetCopyWith(UserRegistrationSheet value, $Res Function(UserRegistrationSheet) then) = _$UserRegistrationSheetCopyWithImpl<$Res, UserRegistrationSheet>; @useResult $Res call( @@ -112,9 +109,7 @@ abstract class $UserRegistrationSheetCopyWith<$Res> { } /// @nodoc -class _$UserRegistrationSheetCopyWithImpl<$Res, - $Val extends UserRegistrationSheet> - implements $UserRegistrationSheetCopyWith<$Res> { +class _$UserRegistrationSheetCopyWithImpl<$Res, $Val extends UserRegistrationSheet> implements $UserRegistrationSheetCopyWith<$Res> { _$UserRegistrationSheetCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -272,11 +267,8 @@ class _$UserRegistrationSheetCopyWithImpl<$Res, } /// @nodoc -abstract class _$$UserRegistrationSheetImplCopyWith<$Res> - implements $UserRegistrationSheetCopyWith<$Res> { - factory _$$UserRegistrationSheetImplCopyWith( - _$UserRegistrationSheetImpl value, - $Res Function(_$UserRegistrationSheetImpl) then) = +abstract class _$$UserRegistrationSheetImplCopyWith<$Res> implements $UserRegistrationSheetCopyWith<$Res> { + factory _$$UserRegistrationSheetImplCopyWith(_$UserRegistrationSheetImpl value, $Res Function(_$UserRegistrationSheetImpl) then) = __$$UserRegistrationSheetImplCopyWithImpl<$Res>; @override @useResult @@ -312,13 +304,9 @@ abstract class _$$UserRegistrationSheetImplCopyWith<$Res> } /// @nodoc -class __$$UserRegistrationSheetImplCopyWithImpl<$Res> - extends _$UserRegistrationSheetCopyWithImpl<$Res, - _$UserRegistrationSheetImpl> +class __$$UserRegistrationSheetImplCopyWithImpl<$Res> extends _$UserRegistrationSheetCopyWithImpl<$Res, _$UserRegistrationSheetImpl> implements _$$UserRegistrationSheetImplCopyWith<$Res> { - __$$UserRegistrationSheetImplCopyWithImpl(_$UserRegistrationSheetImpl _value, - $Res Function(_$UserRegistrationSheetImpl) _then) - : super(_value, _then); + __$$UserRegistrationSheetImplCopyWithImpl(_$UserRegistrationSheetImpl _value, $Res Function(_$UserRegistrationSheetImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -478,8 +466,7 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @JsonKey(name: 'last_name') required this.lastName, required this.email, required this.password, - @JsonKey(name: 'password_confirmation') - required this.passwordConfirmation, + @JsonKey(name: 'password_confirmation') required this.passwordConfirmation, @JsonKey(name: 'terms') this.termsAccepted = 'accepted', required this.birthdate, required this.gender, @@ -503,8 +490,7 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @JsonKey(name: 'additional_info') required this.additionalInfo, @JsonKey(name: 'activity_coefficient') this.activityCoefficient = 1.2}); - factory _$UserRegistrationSheetImpl.fromJson(Map json) => - _$$UserRegistrationSheetImplFromJson(json); + factory _$UserRegistrationSheetImpl.fromJson(Map json) => _$$UserRegistrationSheetImplFromJson(json); @override final String name; @@ -592,52 +578,33 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { (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.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.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.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)); + (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) @@ -677,9 +644,8 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$UserRegistrationSheetImplCopyWith<_$UserRegistrationSheetImpl> - get copyWith => __$$UserRegistrationSheetImplCopyWithImpl< - _$UserRegistrationSheetImpl>(this, _$identity); + _$$UserRegistrationSheetImplCopyWith<_$UserRegistrationSheetImpl> get copyWith => + __$$UserRegistrationSheetImplCopyWithImpl<_$UserRegistrationSheetImpl>(this, _$identity); @override Map toJson() { @@ -696,8 +662,7 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { @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: 'password_confirmation') required final String passwordConfirmation, @JsonKey(name: 'terms') final String termsAccepted, required final String birthdate, required final String gender, @@ -706,28 +671,22 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { 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: '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: '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: '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; + @JsonKey(name: 'activity_coefficient') final double activityCoefficient}) = _$UserRegistrationSheetImpl; - factory _UserRegistrationSheet.fromJson(Map json) = - _$UserRegistrationSheetImpl.fromJson; + factory _UserRegistrationSheet.fromJson(Map json) = _$UserRegistrationSheetImpl.fromJson; @override String get name; @@ -805,6 +764,5 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { double get activityCoefficient; @override @JsonKey(ignore: true) - _$$UserRegistrationSheetImplCopyWith<_$UserRegistrationSheetImpl> - get copyWith => throw _privateConstructorUsedError; + _$$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 index 132240b..7827901 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.g.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.g.dart @@ -6,9 +6,7 @@ part of 'user_registration_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson( - Map json) => - _$UserRegistrationSheetImpl( +_$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson(Map json) => _$UserRegistrationSheetImpl( name: json['name'] as String, firstName: json['first_name'] as String, lastName: json['last_name'] as String, @@ -36,13 +34,10 @@ _$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson( 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, + activityCoefficient: (json['activity_coefficient'] as num?)?.toDouble() ?? 1.2, ); -Map _$$UserRegistrationSheetImplToJson( - _$UserRegistrationSheetImpl instance) => - { +Map _$$UserRegistrationSheetImplToJson(_$UserRegistrationSheetImpl instance) => { 'name': instance.name, 'first_name': instance.firstName, 'last_name': instance.lastName, diff --git a/lib/features/blog_post/models/blog_post_model.dart b/lib/features/blog_post/models/blog_post_model.dart index df39fe1..1a428e0 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/models/blog_post_model.freezed.dart b/lib/features/blog_post/models/blog_post_model.freezed.dart index 7c0a750..06f768a 100644 --- a/lib/features/blog_post/models/blog_post_model.freezed.dart +++ b/lib/features/blog_post/models/blog_post_model.freezed.dart @@ -36,15 +36,12 @@ mixin _$BlogPostModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $BlogPostModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $BlogPostModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $BlogPostModelCopyWith<$Res> { - factory $BlogPostModelCopyWith( - BlogPostModel value, $Res Function(BlogPostModel) then) = - _$BlogPostModelCopyWithImpl<$Res, BlogPostModel>; + factory $BlogPostModelCopyWith(BlogPostModel value, $Res Function(BlogPostModel) then) = _$BlogPostModelCopyWithImpl<$Res, BlogPostModel>; @useResult $Res call( {int id, @@ -60,8 +57,7 @@ abstract class $BlogPostModelCopyWith<$Res> { } /// @nodoc -class _$BlogPostModelCopyWithImpl<$Res, $Val extends BlogPostModel> - implements $BlogPostModelCopyWith<$Res> { +class _$BlogPostModelCopyWithImpl<$Res, $Val extends BlogPostModel> implements $BlogPostModelCopyWith<$Res> { _$BlogPostModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -129,11 +125,8 @@ class _$BlogPostModelCopyWithImpl<$Res, $Val extends BlogPostModel> } /// @nodoc -abstract class _$$BlogPostModelImplCopyWith<$Res> - implements $BlogPostModelCopyWith<$Res> { - factory _$$BlogPostModelImplCopyWith( - _$BlogPostModelImpl value, $Res Function(_$BlogPostModelImpl) then) = - __$$BlogPostModelImplCopyWithImpl<$Res>; +abstract class _$$BlogPostModelImplCopyWith<$Res> implements $BlogPostModelCopyWith<$Res> { + factory _$$BlogPostModelImplCopyWith(_$BlogPostModelImpl value, $Res Function(_$BlogPostModelImpl) then) = __$$BlogPostModelImplCopyWithImpl<$Res>; @override @useResult $Res call( @@ -150,12 +143,8 @@ abstract class _$$BlogPostModelImplCopyWith<$Res> } /// @nodoc -class __$$BlogPostModelImplCopyWithImpl<$Res> - extends _$BlogPostModelCopyWithImpl<$Res, _$BlogPostModelImpl> - implements _$$BlogPostModelImplCopyWith<$Res> { - __$$BlogPostModelImplCopyWithImpl( - _$BlogPostModelImpl _value, $Res Function(_$BlogPostModelImpl) _then) - : super(_value, _then); +class __$$BlogPostModelImplCopyWithImpl<$Res> extends _$BlogPostModelCopyWithImpl<$Res, _$BlogPostModelImpl> implements _$$BlogPostModelImplCopyWith<$Res> { + __$$BlogPostModelImplCopyWithImpl(_$BlogPostModelImpl _value, $Res Function(_$BlogPostModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -231,8 +220,7 @@ class _$BlogPostModelImpl implements _BlogPostModel { @JsonKey(name: "updated_at") required this.updatedAt, required this.title}); - factory _$BlogPostModelImpl.fromJson(Map json) => - _$$BlogPostModelImplFromJson(json); + factory _$BlogPostModelImpl.fromJson(Map json) => _$$BlogPostModelImplFromJson(json); @override final int id; @@ -271,31 +259,23 @@ class _$BlogPostModelImpl implements _BlogPostModel { (identical(other.id, id) || other.id == id) && (identical(other.state, state) || other.state == state) && (identical(other.image, image) || other.image == image) && - (identical(other.description, description) || - other.description == description) && - (identical(other.author_name, author_name) || - other.author_name == author_name) && - (identical(other.author_avatar_path, author_avatar_path) || - other.author_avatar_path == author_avatar_path) && - (identical(other.youtubeUrl, youtubeUrl) || - other.youtubeUrl == youtubeUrl) && - (identical(other.createdAt, createdAt) || - other.createdAt == createdAt) && - (identical(other.updatedAt, updatedAt) || - other.updatedAt == updatedAt) && + (identical(other.description, description) || other.description == description) && + (identical(other.author_name, author_name) || other.author_name == author_name) && + (identical(other.author_avatar_path, author_avatar_path) || other.author_avatar_path == author_avatar_path) && + (identical(other.youtubeUrl, youtubeUrl) || other.youtubeUrl == youtubeUrl) && + (identical(other.createdAt, createdAt) || other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt) && (identical(other.title, title) || other.title == title)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, state, image, description, - author_name, author_avatar_path, youtubeUrl, createdAt, updatedAt, title); + int get hashCode => Object.hash(runtimeType, id, state, image, description, author_name, author_avatar_path, youtubeUrl, createdAt, updatedAt, title); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => - __$$BlogPostModelImplCopyWithImpl<_$BlogPostModelImpl>(this, _$identity); + _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => __$$BlogPostModelImplCopyWithImpl<_$BlogPostModelImpl>(this, _$identity); @override Map toJson() { @@ -318,8 +298,7 @@ abstract class _BlogPostModel implements BlogPostModel { @JsonKey(name: "updated_at") required final DateTime updatedAt, required final String title}) = _$BlogPostModelImpl; - factory _BlogPostModel.fromJson(Map json) = - _$BlogPostModelImpl.fromJson; + factory _BlogPostModel.fromJson(Map json) = _$BlogPostModelImpl.fromJson; @override int get id; @@ -346,6 +325,5 @@ abstract class _BlogPostModel implements BlogPostModel { String get title; @override @JsonKey(ignore: true) - _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/blog_post/models/blog_post_model.g.dart b/lib/features/blog_post/models/blog_post_model.g.dart index 2e3233c..137652f 100644 --- a/lib/features/blog_post/models/blog_post_model.g.dart +++ b/lib/features/blog_post/models/blog_post_model.g.dart @@ -6,8 +6,7 @@ part of 'blog_post_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$BlogPostModelImpl _$$BlogPostModelImplFromJson(Map json) => - _$BlogPostModelImpl( +_$BlogPostModelImpl _$$BlogPostModelImplFromJson(Map json) => _$BlogPostModelImpl( id: (json['id'] as num).toInt(), state: json['state'] as String, image: json['image'] as String?, @@ -20,8 +19,7 @@ _$BlogPostModelImpl _$$BlogPostModelImplFromJson(Map json) => title: json['title'] as String, ); -Map _$$BlogPostModelImplToJson(_$BlogPostModelImpl instance) => - { +Map _$$BlogPostModelImplToJson(_$BlogPostModelImpl instance) => { 'id': instance.id, 'state': instance.state, 'image': instance.image, 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 90520c9..301e0ef 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/bloc/blog_post_state.freezed.dart b/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart index 4f99a3c..d204df1 100644 --- a/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart +++ b/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart @@ -70,14 +70,11 @@ mixin _$BlogPostState { /// @nodoc abstract class $BlogPostStateCopyWith<$Res> { - factory $BlogPostStateCopyWith( - BlogPostState value, $Res Function(BlogPostState) then) = - _$BlogPostStateCopyWithImpl<$Res, BlogPostState>; + factory $BlogPostStateCopyWith(BlogPostState value, $Res Function(BlogPostState) then) = _$BlogPostStateCopyWithImpl<$Res, BlogPostState>; } /// @nodoc -class _$BlogPostStateCopyWithImpl<$Res, $Val extends BlogPostState> - implements $BlogPostStateCopyWith<$Res> { +class _$BlogPostStateCopyWithImpl<$Res, $Val extends BlogPostState> implements $BlogPostStateCopyWith<$Res> { _$BlogPostStateCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -88,18 +85,12 @@ class _$BlogPostStateCopyWithImpl<$Res, $Val extends BlogPostState> /// @nodoc abstract class _$$BlogPostStateImplCopyWith<$Res> { - factory _$$BlogPostStateImplCopyWith( - _$BlogPostStateImpl value, $Res Function(_$BlogPostStateImpl) then) = - __$$BlogPostStateImplCopyWithImpl<$Res>; + factory _$$BlogPostStateImplCopyWith(_$BlogPostStateImpl value, $Res Function(_$BlogPostStateImpl) then) = __$$BlogPostStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$BlogPostStateImplCopyWithImpl<$Res> - extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateImpl> - implements _$$BlogPostStateImplCopyWith<$Res> { - __$$BlogPostStateImplCopyWithImpl( - _$BlogPostStateImpl _value, $Res Function(_$BlogPostStateImpl) _then) - : super(_value, _then); +class __$$BlogPostStateImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateImpl> implements _$$BlogPostStateImplCopyWith<$Res> { + __$$BlogPostStateImplCopyWithImpl(_$BlogPostStateImpl _value, $Res Function(_$BlogPostStateImpl) _then) : super(_value, _then); } /// @nodoc @@ -114,8 +105,7 @@ class _$BlogPostStateImpl implements _BlogPostState { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is _$BlogPostStateImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$BlogPostStateImpl); } @override @@ -202,18 +192,14 @@ abstract class _BlogPostState implements BlogPostState { /// @nodoc abstract class _$$BlogPostStateLoadingImplCopyWith<$Res> { - factory _$$BlogPostStateLoadingImplCopyWith(_$BlogPostStateLoadingImpl value, - $Res Function(_$BlogPostStateLoadingImpl) then) = + factory _$$BlogPostStateLoadingImplCopyWith(_$BlogPostStateLoadingImpl value, $Res Function(_$BlogPostStateLoadingImpl) then) = __$$BlogPostStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$BlogPostStateLoadingImplCopyWithImpl<$Res> - extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadingImpl> +class __$$BlogPostStateLoadingImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadingImpl> implements _$$BlogPostStateLoadingImplCopyWith<$Res> { - __$$BlogPostStateLoadingImplCopyWithImpl(_$BlogPostStateLoadingImpl _value, - $Res Function(_$BlogPostStateLoadingImpl) _then) - : super(_value, _then); + __$$BlogPostStateLoadingImplCopyWithImpl(_$BlogPostStateLoadingImpl _value, $Res Function(_$BlogPostStateLoadingImpl) _then) : super(_value, _then); } /// @nodoc @@ -228,9 +214,7 @@ class _$BlogPostStateLoadingImpl implements BlogPostStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$BlogPostStateLoadingImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$BlogPostStateLoadingImpl); } @override @@ -317,8 +301,7 @@ abstract class BlogPostStateLoading implements BlogPostState { /// @nodoc abstract class _$$BlogPostStateLoadedImplCopyWith<$Res> { - factory _$$BlogPostStateLoadedImplCopyWith(_$BlogPostStateLoadedImpl value, - $Res Function(_$BlogPostStateLoadedImpl) then) = + factory _$$BlogPostStateLoadedImplCopyWith(_$BlogPostStateLoadedImpl value, $Res Function(_$BlogPostStateLoadedImpl) then) = __$$BlogPostStateLoadedImplCopyWithImpl<$Res>; @useResult $Res call({BlogPostModel blogPost}); @@ -327,12 +310,9 @@ abstract class _$$BlogPostStateLoadedImplCopyWith<$Res> { } /// @nodoc -class __$$BlogPostStateLoadedImplCopyWithImpl<$Res> - extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadedImpl> +class __$$BlogPostStateLoadedImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadedImpl> implements _$$BlogPostStateLoadedImplCopyWith<$Res> { - __$$BlogPostStateLoadedImplCopyWithImpl(_$BlogPostStateLoadedImpl _value, - $Res Function(_$BlogPostStateLoadedImpl) _then) - : super(_value, _then); + __$$BlogPostStateLoadedImplCopyWithImpl(_$BlogPostStateLoadedImpl _value, $Res Function(_$BlogPostStateLoadedImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -372,10 +352,7 @@ class _$BlogPostStateLoadedImpl implements BlogPostStateLoaded { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$BlogPostStateLoadedImpl && - (identical(other.blogPost, blogPost) || - other.blogPost == blogPost)); + (other.runtimeType == runtimeType && other is _$BlogPostStateLoadedImpl && (identical(other.blogPost, blogPost) || other.blogPost == blogPost)); } @override @@ -385,8 +362,7 @@ class _$BlogPostStateLoadedImpl implements BlogPostStateLoaded { @override @pragma('vm:prefer-inline') _$$BlogPostStateLoadedImplCopyWith<_$BlogPostStateLoadedImpl> get copyWith => - __$$BlogPostStateLoadedImplCopyWithImpl<_$BlogPostStateLoadedImpl>( - this, _$identity); + __$$BlogPostStateLoadedImplCopyWithImpl<_$BlogPostStateLoadedImpl>(this, _$identity); @override @optionalTypeArgs @@ -464,31 +440,25 @@ class _$BlogPostStateLoadedImpl implements BlogPostStateLoaded { } abstract class BlogPostStateLoaded implements BlogPostState { - const factory BlogPostStateLoaded({required final BlogPostModel blogPost}) = - _$BlogPostStateLoadedImpl; + const factory BlogPostStateLoaded({required final BlogPostModel blogPost}) = _$BlogPostStateLoadedImpl; BlogPostModel get blogPost; @JsonKey(ignore: true) - _$$BlogPostStateLoadedImplCopyWith<_$BlogPostStateLoadedImpl> get copyWith => - throw _privateConstructorUsedError; + _$$BlogPostStateLoadedImplCopyWith<_$BlogPostStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$BlogPostStateErrorImplCopyWith<$Res> { - factory _$$BlogPostStateErrorImplCopyWith(_$BlogPostStateErrorImpl value, - $Res Function(_$BlogPostStateErrorImpl) then) = + factory _$$BlogPostStateErrorImplCopyWith(_$BlogPostStateErrorImpl value, $Res Function(_$BlogPostStateErrorImpl) then) = __$$BlogPostStateErrorImplCopyWithImpl<$Res>; @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$BlogPostStateErrorImplCopyWithImpl<$Res> - extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateErrorImpl> +class __$$BlogPostStateErrorImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateErrorImpl> implements _$$BlogPostStateErrorImplCopyWith<$Res> { - __$$BlogPostStateErrorImplCopyWithImpl(_$BlogPostStateErrorImpl _value, - $Res Function(_$BlogPostStateErrorImpl) _then) - : super(_value, _then); + __$$BlogPostStateErrorImplCopyWithImpl(_$BlogPostStateErrorImpl _value, $Res Function(_$BlogPostStateErrorImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -522,8 +492,7 @@ class _$BlogPostStateErrorImpl implements BlogPostStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$BlogPostStateErrorImpl && - (identical(other.errorMessage, errorMessage) || - other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); } @override @@ -533,8 +502,7 @@ class _$BlogPostStateErrorImpl implements BlogPostStateError { @override @pragma('vm:prefer-inline') _$$BlogPostStateErrorImplCopyWith<_$BlogPostStateErrorImpl> get copyWith => - __$$BlogPostStateErrorImplCopyWithImpl<_$BlogPostStateErrorImpl>( - this, _$identity); + __$$BlogPostStateErrorImplCopyWithImpl<_$BlogPostStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -612,11 +580,9 @@ class _$BlogPostStateErrorImpl implements BlogPostStateError { } abstract class BlogPostStateError implements BlogPostState { - const factory BlogPostStateError({required final String errorMessage}) = - _$BlogPostStateErrorImpl; + const factory BlogPostStateError({required final String errorMessage}) = _$BlogPostStateErrorImpl; String get errorMessage; @JsonKey(ignore: true) - _$$BlogPostStateErrorImplCopyWith<_$BlogPostStateErrorImpl> get copyWith => - throw _privateConstructorUsedError; + _$$BlogPostStateErrorImplCopyWith<_$BlogPostStateErrorImpl> get copyWith => throw _privateConstructorUsedError; } 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 f9fc969..c46c8b1 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 a406a7f..00d8e56 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 c99e785..bed4199 100644 --- a/lib/features/blog_post/services/blog_post_service.g.dart +++ b/lib/features/blog_post/services/blog_post_service.g.dart @@ -24,31 +24,28 @@ class _BlogPostService implements BlogPostService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType(Options( + final _result = await _dio.fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/feed/show/${id}', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/feed/show/${id}', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = BlogPostModel.fromJson(_result.data!); return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && - !(requestOptions.responseType == ResponseType.bytes || - requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { 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 e961471..ba68b46 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 4bedcf5..755ce12 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 e11bce9..25b7082 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 1291c9a..142682f 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 71ca211..d30d7d8 100644 --- a/lib/features/blog_post_create/services/blog_service.g.dart +++ b/lib/features/blog_post_create/services/blog_service.g.dart @@ -19,37 +19,33 @@ class _BlogService implements BlogService { String? baseUrl; @override - Future createBlogPost( - BlogPostCreateCredentialsModel model) async { + Future createBlogPost(BlogPostCreateCredentialsModel model) async { final _extra = {}; final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>( - _setStreamType(Options( + final _result = await _dio.fetch>(_setStreamType(Options( method: 'POST', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/blog_post/create', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/blog_post/create', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = BlogPostCreateCredentialsModel.fromJson(_result.data!); return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && - !(requestOptions.responseType == ResponseType.bytes || - requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart index 02a1c4b..68714d7 100644 --- a/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart +++ b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart @@ -70,14 +70,11 @@ mixin _$NewMessagesState { /// @nodoc abstract class $NewMessagesStateCopyWith<$Res> { - factory $NewMessagesStateCopyWith( - NewMessagesState value, $Res Function(NewMessagesState) then) = - _$NewMessagesStateCopyWithImpl<$Res, NewMessagesState>; + factory $NewMessagesStateCopyWith(NewMessagesState value, $Res Function(NewMessagesState) then) = _$NewMessagesStateCopyWithImpl<$Res, NewMessagesState>; } /// @nodoc -class _$NewMessagesStateCopyWithImpl<$Res, $Val extends NewMessagesState> - implements $NewMessagesStateCopyWith<$Res> { +class _$NewMessagesStateCopyWithImpl<$Res, $Val extends NewMessagesState> implements $NewMessagesStateCopyWith<$Res> { _$NewMessagesStateCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -88,18 +85,14 @@ class _$NewMessagesStateCopyWithImpl<$Res, $Val extends NewMessagesState> /// @nodoc abstract class _$$NewMessagesStateImplCopyWith<$Res> { - factory _$$NewMessagesStateImplCopyWith(_$NewMessagesStateImpl value, - $Res Function(_$NewMessagesStateImpl) then) = + factory _$$NewMessagesStateImplCopyWith(_$NewMessagesStateImpl value, $Res Function(_$NewMessagesStateImpl) then) = __$$NewMessagesStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NewMessagesStateImplCopyWithImpl<$Res> - extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateImpl> +class __$$NewMessagesStateImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateImpl> implements _$$NewMessagesStateImplCopyWith<$Res> { - __$$NewMessagesStateImplCopyWithImpl(_$NewMessagesStateImpl _value, - $Res Function(_$NewMessagesStateImpl) _then) - : super(_value, _then); + __$$NewMessagesStateImplCopyWithImpl(_$NewMessagesStateImpl _value, $Res Function(_$NewMessagesStateImpl) _then) : super(_value, _then); } /// @nodoc @@ -114,8 +107,7 @@ class _$NewMessagesStateImpl implements _NewMessagesState { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is _$NewMessagesStateImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateImpl); } @override @@ -202,19 +194,14 @@ abstract class _NewMessagesState implements NewMessagesState { /// @nodoc abstract class _$$NewMessagesStateEmptyImplCopyWith<$Res> { - factory _$$NewMessagesStateEmptyImplCopyWith( - _$NewMessagesStateEmptyImpl value, - $Res Function(_$NewMessagesStateEmptyImpl) then) = + factory _$$NewMessagesStateEmptyImplCopyWith(_$NewMessagesStateEmptyImpl value, $Res Function(_$NewMessagesStateEmptyImpl) then) = __$$NewMessagesStateEmptyImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NewMessagesStateEmptyImplCopyWithImpl<$Res> - extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateEmptyImpl> +class __$$NewMessagesStateEmptyImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateEmptyImpl> implements _$$NewMessagesStateEmptyImplCopyWith<$Res> { - __$$NewMessagesStateEmptyImplCopyWithImpl(_$NewMessagesStateEmptyImpl _value, - $Res Function(_$NewMessagesStateEmptyImpl) _then) - : super(_value, _then); + __$$NewMessagesStateEmptyImplCopyWithImpl(_$NewMessagesStateEmptyImpl _value, $Res Function(_$NewMessagesStateEmptyImpl) _then) : super(_value, _then); } /// @nodoc @@ -229,9 +216,7 @@ class _$NewMessagesStateEmptyImpl implements NewMessagesStateEmpty { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$NewMessagesStateEmptyImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateEmptyImpl); } @override @@ -318,22 +303,16 @@ abstract class NewMessagesStateEmpty implements NewMessagesState { /// @nodoc abstract class _$$NewMessagesStateLoadedImplCopyWith<$Res> { - factory _$$NewMessagesStateLoadedImplCopyWith( - _$NewMessagesStateLoadedImpl value, - $Res Function(_$NewMessagesStateLoadedImpl) then) = + factory _$$NewMessagesStateLoadedImplCopyWith(_$NewMessagesStateLoadedImpl value, $Res Function(_$NewMessagesStateLoadedImpl) then) = __$$NewMessagesStateLoadedImplCopyWithImpl<$Res>; @useResult $Res call({int messagesCount}); } /// @nodoc -class __$$NewMessagesStateLoadedImplCopyWithImpl<$Res> - extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateLoadedImpl> +class __$$NewMessagesStateLoadedImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateLoadedImpl> implements _$$NewMessagesStateLoadedImplCopyWith<$Res> { - __$$NewMessagesStateLoadedImplCopyWithImpl( - _$NewMessagesStateLoadedImpl _value, - $Res Function(_$NewMessagesStateLoadedImpl) _then) - : super(_value, _then); + __$$NewMessagesStateLoadedImplCopyWithImpl(_$NewMessagesStateLoadedImpl _value, $Res Function(_$NewMessagesStateLoadedImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -367,8 +346,7 @@ class _$NewMessagesStateLoadedImpl implements NewMessagesStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateLoadedImpl && - (identical(other.messagesCount, messagesCount) || - other.messagesCount == messagesCount)); + (identical(other.messagesCount, messagesCount) || other.messagesCount == messagesCount)); } @override @@ -377,9 +355,8 @@ class _$NewMessagesStateLoadedImpl implements NewMessagesStateLoaded { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> - get copyWith => __$$NewMessagesStateLoadedImplCopyWithImpl< - _$NewMessagesStateLoadedImpl>(this, _$identity); + _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> get copyWith => + __$$NewMessagesStateLoadedImplCopyWithImpl<_$NewMessagesStateLoadedImpl>(this, _$identity); @override @optionalTypeArgs @@ -457,32 +434,25 @@ class _$NewMessagesStateLoadedImpl implements NewMessagesStateLoaded { } abstract class NewMessagesStateLoaded implements NewMessagesState { - const factory NewMessagesStateLoaded({required final int messagesCount}) = - _$NewMessagesStateLoadedImpl; + const factory NewMessagesStateLoaded({required final int messagesCount}) = _$NewMessagesStateLoadedImpl; int get messagesCount; @JsonKey(ignore: true) - _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> - get copyWith => throw _privateConstructorUsedError; + _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$NewMessagesStateErrorImplCopyWith<$Res> { - factory _$$NewMessagesStateErrorImplCopyWith( - _$NewMessagesStateErrorImpl value, - $Res Function(_$NewMessagesStateErrorImpl) then) = + factory _$$NewMessagesStateErrorImplCopyWith(_$NewMessagesStateErrorImpl value, $Res Function(_$NewMessagesStateErrorImpl) then) = __$$NewMessagesStateErrorImplCopyWithImpl<$Res>; @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$NewMessagesStateErrorImplCopyWithImpl<$Res> - extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateErrorImpl> +class __$$NewMessagesStateErrorImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateErrorImpl> implements _$$NewMessagesStateErrorImplCopyWith<$Res> { - __$$NewMessagesStateErrorImplCopyWithImpl(_$NewMessagesStateErrorImpl _value, - $Res Function(_$NewMessagesStateErrorImpl) _then) - : super(_value, _then); + __$$NewMessagesStateErrorImplCopyWithImpl(_$NewMessagesStateErrorImpl _value, $Res Function(_$NewMessagesStateErrorImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -516,8 +486,7 @@ class _$NewMessagesStateErrorImpl implements NewMessagesStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateErrorImpl && - (identical(other.errorMessage, errorMessage) || - other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); } @override @@ -526,9 +495,8 @@ class _$NewMessagesStateErrorImpl implements NewMessagesStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> - get copyWith => __$$NewMessagesStateErrorImplCopyWithImpl< - _$NewMessagesStateErrorImpl>(this, _$identity); + _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> get copyWith => + __$$NewMessagesStateErrorImplCopyWithImpl<_$NewMessagesStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -606,11 +574,9 @@ class _$NewMessagesStateErrorImpl implements NewMessagesStateError { } abstract class NewMessagesStateError implements NewMessagesState { - const factory NewMessagesStateError({required final String errorMessage}) = - _$NewMessagesStateErrorImpl; + const factory NewMessagesStateError({required final String errorMessage}) = _$NewMessagesStateErrorImpl; String get errorMessage; @JsonKey(ignore: true) - _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> - get copyWith => throw _privateConstructorUsedError; + _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart b/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart index 0deeebb..2f98548 100644 --- a/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart +++ b/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart @@ -70,14 +70,12 @@ mixin _$NotificationsState { /// @nodoc abstract class $NotificationsStateCopyWith<$Res> { - factory $NotificationsStateCopyWith( - NotificationsState value, $Res Function(NotificationsState) then) = + factory $NotificationsStateCopyWith(NotificationsState value, $Res Function(NotificationsState) then) = _$NotificationsStateCopyWithImpl<$Res, NotificationsState>; } /// @nodoc -class _$NotificationsStateCopyWithImpl<$Res, $Val extends NotificationsState> - implements $NotificationsStateCopyWith<$Res> { +class _$NotificationsStateCopyWithImpl<$Res, $Val extends NotificationsState> implements $NotificationsStateCopyWith<$Res> { _$NotificationsStateCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -88,18 +86,14 @@ class _$NotificationsStateCopyWithImpl<$Res, $Val extends NotificationsState> /// @nodoc abstract class _$$NotificationsStateImplCopyWith<$Res> { - factory _$$NotificationsStateImplCopyWith(_$NotificationsStateImpl value, - $Res Function(_$NotificationsStateImpl) then) = + factory _$$NotificationsStateImplCopyWith(_$NotificationsStateImpl value, $Res Function(_$NotificationsStateImpl) then) = __$$NotificationsStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NotificationsStateImplCopyWithImpl<$Res> - extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateImpl> +class __$$NotificationsStateImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateImpl> implements _$$NotificationsStateImplCopyWith<$Res> { - __$$NotificationsStateImplCopyWithImpl(_$NotificationsStateImpl _value, - $Res Function(_$NotificationsStateImpl) _then) - : super(_value, _then); + __$$NotificationsStateImplCopyWithImpl(_$NotificationsStateImpl _value, $Res Function(_$NotificationsStateImpl) _then) : super(_value, _then); } /// @nodoc @@ -114,8 +108,7 @@ class _$NotificationsStateImpl implements _NotificationsState { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is _$NotificationsStateImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateImpl); } @override @@ -202,21 +195,14 @@ abstract class _NotificationsState implements NotificationsState { /// @nodoc abstract class _$$NotificationsStateEmptyImplCopyWith<$Res> { - factory _$$NotificationsStateEmptyImplCopyWith( - _$NotificationsStateEmptyImpl value, - $Res Function(_$NotificationsStateEmptyImpl) then) = + factory _$$NotificationsStateEmptyImplCopyWith(_$NotificationsStateEmptyImpl value, $Res Function(_$NotificationsStateEmptyImpl) then) = __$$NotificationsStateEmptyImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NotificationsStateEmptyImplCopyWithImpl<$Res> - extends _$NotificationsStateCopyWithImpl<$Res, - _$NotificationsStateEmptyImpl> +class __$$NotificationsStateEmptyImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateEmptyImpl> implements _$$NotificationsStateEmptyImplCopyWith<$Res> { - __$$NotificationsStateEmptyImplCopyWithImpl( - _$NotificationsStateEmptyImpl _value, - $Res Function(_$NotificationsStateEmptyImpl) _then) - : super(_value, _then); + __$$NotificationsStateEmptyImplCopyWithImpl(_$NotificationsStateEmptyImpl _value, $Res Function(_$NotificationsStateEmptyImpl) _then) : super(_value, _then); } /// @nodoc @@ -231,9 +217,7 @@ class _$NotificationsStateEmptyImpl implements NotificationsStateEmpty { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$NotificationsStateEmptyImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateEmptyImpl); } @override @@ -320,22 +304,16 @@ abstract class NotificationsStateEmpty implements NotificationsState { /// @nodoc abstract class _$$NotificationsStateLoadedImplCopyWith<$Res> { - factory _$$NotificationsStateLoadedImplCopyWith( - _$NotificationsStateLoadedImpl value, - $Res Function(_$NotificationsStateLoadedImpl) then) = + factory _$$NotificationsStateLoadedImplCopyWith(_$NotificationsStateLoadedImpl value, $Res Function(_$NotificationsStateLoadedImpl) then) = __$$NotificationsStateLoadedImplCopyWithImpl<$Res>; @useResult $Res call({int notificationsCount}); } /// @nodoc -class __$$NotificationsStateLoadedImplCopyWithImpl<$Res> - extends _$NotificationsStateCopyWithImpl<$Res, - _$NotificationsStateLoadedImpl> +class __$$NotificationsStateLoadedImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateLoadedImpl> implements _$$NotificationsStateLoadedImplCopyWith<$Res> { - __$$NotificationsStateLoadedImplCopyWithImpl( - _$NotificationsStateLoadedImpl _value, - $Res Function(_$NotificationsStateLoadedImpl) _then) + __$$NotificationsStateLoadedImplCopyWithImpl(_$NotificationsStateLoadedImpl _value, $Res Function(_$NotificationsStateLoadedImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -370,8 +348,7 @@ class _$NotificationsStateLoadedImpl implements NotificationsStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateLoadedImpl && - (identical(other.notificationsCount, notificationsCount) || - other.notificationsCount == notificationsCount)); + (identical(other.notificationsCount, notificationsCount) || other.notificationsCount == notificationsCount)); } @override @@ -380,9 +357,8 @@ class _$NotificationsStateLoadedImpl implements NotificationsStateLoaded { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> - get copyWith => __$$NotificationsStateLoadedImplCopyWithImpl< - _$NotificationsStateLoadedImpl>(this, _$identity); + _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> get copyWith => + __$$NotificationsStateLoadedImplCopyWithImpl<_$NotificationsStateLoadedImpl>(this, _$identity); @override @optionalTypeArgs @@ -460,34 +436,25 @@ class _$NotificationsStateLoadedImpl implements NotificationsStateLoaded { } abstract class NotificationsStateLoaded implements NotificationsState { - const factory NotificationsStateLoaded( - {required final int notificationsCount}) = _$NotificationsStateLoadedImpl; + const factory NotificationsStateLoaded({required final int notificationsCount}) = _$NotificationsStateLoadedImpl; int get notificationsCount; @JsonKey(ignore: true) - _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> - get copyWith => throw _privateConstructorUsedError; + _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$NotificationsStateErrorImplCopyWith<$Res> { - factory _$$NotificationsStateErrorImplCopyWith( - _$NotificationsStateErrorImpl value, - $Res Function(_$NotificationsStateErrorImpl) then) = + factory _$$NotificationsStateErrorImplCopyWith(_$NotificationsStateErrorImpl value, $Res Function(_$NotificationsStateErrorImpl) then) = __$$NotificationsStateErrorImplCopyWithImpl<$Res>; @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$NotificationsStateErrorImplCopyWithImpl<$Res> - extends _$NotificationsStateCopyWithImpl<$Res, - _$NotificationsStateErrorImpl> +class __$$NotificationsStateErrorImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateErrorImpl> implements _$$NotificationsStateErrorImplCopyWith<$Res> { - __$$NotificationsStateErrorImplCopyWithImpl( - _$NotificationsStateErrorImpl _value, - $Res Function(_$NotificationsStateErrorImpl) _then) - : super(_value, _then); + __$$NotificationsStateErrorImplCopyWithImpl(_$NotificationsStateErrorImpl _value, $Res Function(_$NotificationsStateErrorImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -521,8 +488,7 @@ class _$NotificationsStateErrorImpl implements NotificationsStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateErrorImpl && - (identical(other.errorMessage, errorMessage) || - other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); } @override @@ -531,9 +497,8 @@ class _$NotificationsStateErrorImpl implements NotificationsStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> - get copyWith => __$$NotificationsStateErrorImplCopyWithImpl< - _$NotificationsStateErrorImpl>(this, _$identity); + _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> get copyWith => + __$$NotificationsStateErrorImplCopyWithImpl<_$NotificationsStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -611,11 +576,9 @@ class _$NotificationsStateErrorImpl implements NotificationsStateError { } abstract class NotificationsStateError implements NotificationsState { - const factory NotificationsStateError({required final String errorMessage}) = - _$NotificationsStateErrorImpl; + const factory NotificationsStateError({required final String errorMessage}) = _$NotificationsStateErrorImpl; String get errorMessage; @JsonKey(ignore: true) - _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> - get copyWith => throw _privateConstructorUsedError; + _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> get copyWith => throw _privateConstructorUsedError; } 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 9865221..5b89028 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 00e17f5..23f03f9 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_message_model.freezed.dart b/lib/features/chat/models/chat_message_model.freezed.dart index 76a91cb..90e7e72 100644 --- a/lib/features/chat/models/chat_message_model.freezed.dart +++ b/lib/features/chat/models/chat_message_model.freezed.dart @@ -31,15 +31,12 @@ mixin _$ChatMessageModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $ChatMessageModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $ChatMessageModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatMessageModelCopyWith<$Res> { - factory $ChatMessageModelCopyWith( - ChatMessageModel value, $Res Function(ChatMessageModel) then) = - _$ChatMessageModelCopyWithImpl<$Res, ChatMessageModel>; + factory $ChatMessageModelCopyWith(ChatMessageModel value, $Res Function(ChatMessageModel) then) = _$ChatMessageModelCopyWithImpl<$Res, ChatMessageModel>; @useResult $Res call( {int id, @@ -50,8 +47,7 @@ abstract class $ChatMessageModelCopyWith<$Res> { } /// @nodoc -class _$ChatMessageModelCopyWithImpl<$Res, $Val extends ChatMessageModel> - implements $ChatMessageModelCopyWith<$Res> { +class _$ChatMessageModelCopyWithImpl<$Res, $Val extends ChatMessageModel> implements $ChatMessageModelCopyWith<$Res> { _$ChatMessageModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -94,10 +90,8 @@ class _$ChatMessageModelCopyWithImpl<$Res, $Val extends ChatMessageModel> } /// @nodoc -abstract class _$$ChatMessageModelImplCopyWith<$Res> - implements $ChatMessageModelCopyWith<$Res> { - factory _$$ChatMessageModelImplCopyWith(_$ChatMessageModelImpl value, - $Res Function(_$ChatMessageModelImpl) then) = +abstract class _$$ChatMessageModelImplCopyWith<$Res> implements $ChatMessageModelCopyWith<$Res> { + factory _$$ChatMessageModelImplCopyWith(_$ChatMessageModelImpl value, $Res Function(_$ChatMessageModelImpl) then) = __$$ChatMessageModelImplCopyWithImpl<$Res>; @override @useResult @@ -110,12 +104,9 @@ abstract class _$$ChatMessageModelImplCopyWith<$Res> } /// @nodoc -class __$$ChatMessageModelImplCopyWithImpl<$Res> - extends _$ChatMessageModelCopyWithImpl<$Res, _$ChatMessageModelImpl> +class __$$ChatMessageModelImplCopyWithImpl<$Res> extends _$ChatMessageModelCopyWithImpl<$Res, _$ChatMessageModelImpl> implements _$$ChatMessageModelImplCopyWith<$Res> { - __$$ChatMessageModelImplCopyWithImpl(_$ChatMessageModelImpl _value, - $Res Function(_$ChatMessageModelImpl) _then) - : super(_value, _then); + __$$ChatMessageModelImplCopyWithImpl(_$ChatMessageModelImpl _value, $Res Function(_$ChatMessageModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -162,8 +153,7 @@ class _$ChatMessageModelImpl implements _ChatMessageModel { @JsonKey(name: 'updated_at') required this.updatedAt}) : _mediaData = mediaData; - factory _$ChatMessageModelImpl.fromJson(Map json) => - _$$ChatMessageModelImplFromJson(json); + factory _$ChatMessageModelImpl.fromJson(Map json) => _$$ChatMessageModelImplFromJson(json); @override final int id; @@ -199,25 +189,19 @@ class _$ChatMessageModelImpl implements _ChatMessageModel { other is _$ChatMessageModelImpl && (identical(other.id, id) || other.id == id) && (identical(other.data, data) || other.data == data) && - const DeepCollectionEquality() - .equals(other._mediaData, _mediaData) && - (identical(other.authorId, authorId) || - other.authorId == authorId) && - (identical(other.updatedAt, updatedAt) || - other.updatedAt == updatedAt)); + const DeepCollectionEquality().equals(other._mediaData, _mediaData) && + (identical(other.authorId, authorId) || other.authorId == authorId) && + (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, data, - const DeepCollectionEquality().hash(_mediaData), authorId, updatedAt); + int get hashCode => Object.hash(runtimeType, id, data, const DeepCollectionEquality().hash(_mediaData), authorId, updatedAt); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => - __$$ChatMessageModelImplCopyWithImpl<_$ChatMessageModelImpl>( - this, _$identity); + _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => __$$ChatMessageModelImplCopyWithImpl<_$ChatMessageModelImpl>(this, _$identity); @override Map toJson() { @@ -229,15 +213,13 @@ class _$ChatMessageModelImpl implements _ChatMessageModel { abstract class _ChatMessageModel implements ChatMessageModel { const factory _ChatMessageModel( - {required final int id, - required final String data, - @JsonKey(name: 'media_data') required final List? mediaData, - @JsonKey(name: 'author_id') required final int authorId, - @JsonKey(name: 'updated_at') required final String updatedAt}) = - _$ChatMessageModelImpl; + {required final int id, + required final String data, + @JsonKey(name: 'media_data') required final List? mediaData, + @JsonKey(name: 'author_id') required final int authorId, + @JsonKey(name: 'updated_at') required final String updatedAt}) = _$ChatMessageModelImpl; - factory _ChatMessageModel.fromJson(Map json) = - _$ChatMessageModelImpl.fromJson; + factory _ChatMessageModel.fromJson(Map json) = _$ChatMessageModelImpl.fromJson; @override int get id; @@ -254,6 +236,5 @@ abstract class _ChatMessageModel implements ChatMessageModel { String get updatedAt; @override @JsonKey(ignore: true) - _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_message_model.g.dart b/lib/features/chat/models/chat_message_model.g.dart index 3a8d182..7053109 100644 --- a/lib/features/chat/models/chat_message_model.g.dart +++ b/lib/features/chat/models/chat_message_model.g.dart @@ -6,9 +6,7 @@ part of 'chat_message_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatMessageModelImpl _$$ChatMessageModelImplFromJson( - Map json) => - _$ChatMessageModelImpl( +_$ChatMessageModelImpl _$$ChatMessageModelImplFromJson(Map json) => _$ChatMessageModelImpl( id: (json['id'] as num).toInt(), data: json['data'] as String, mediaData: json['media_data'] as List?, @@ -16,9 +14,7 @@ _$ChatMessageModelImpl _$$ChatMessageModelImplFromJson( updatedAt: json['updated_at'] as String, ); -Map _$$ChatMessageModelImplToJson( - _$ChatMessageModelImpl instance) => - { +Map _$$ChatMessageModelImplToJson(_$ChatMessageModelImpl instance) => { 'id': instance.id, 'data': instance.data, 'media_data': instance.mediaData, diff --git a/lib/features/chat/models/chat_messages_model.dart b/lib/features/chat/models/chat_messages_model.dart index 84a51b4..999f598 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_messages_model.freezed.dart b/lib/features/chat/models/chat_messages_model.freezed.dart index a970241..e7900ce 100644 --- a/lib/features/chat/models/chat_messages_model.freezed.dart +++ b/lib/features/chat/models/chat_messages_model.freezed.dart @@ -26,26 +26,20 @@ mixin _$ChatMessagesModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $ChatMessagesModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $ChatMessagesModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatMessagesModelCopyWith<$Res> { - factory $ChatMessagesModelCopyWith( - ChatMessagesModel value, $Res Function(ChatMessagesModel) then) = - _$ChatMessagesModelCopyWithImpl<$Res, ChatMessagesModel>; + factory $ChatMessagesModelCopyWith(ChatMessagesModel value, $Res Function(ChatMessagesModel) then) = _$ChatMessagesModelCopyWithImpl<$Res, ChatMessagesModel>; @useResult - $Res call( - {@JsonKey(name: 'data') List messagesList, - ChatMetaModel meta}); + $Res call({@JsonKey(name: 'data') List messagesList, ChatMetaModel meta}); $ChatMetaModelCopyWith<$Res> get meta; } /// @nodoc -class _$ChatMessagesModelCopyWithImpl<$Res, $Val extends ChatMessagesModel> - implements $ChatMessagesModelCopyWith<$Res> { +class _$ChatMessagesModelCopyWithImpl<$Res, $Val extends ChatMessagesModel> implements $ChatMessagesModelCopyWith<$Res> { _$ChatMessagesModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -81,28 +75,21 @@ class _$ChatMessagesModelCopyWithImpl<$Res, $Val extends ChatMessagesModel> } /// @nodoc -abstract class _$$ChatMessagesModelImplCopyWith<$Res> - implements $ChatMessagesModelCopyWith<$Res> { - factory _$$ChatMessagesModelImplCopyWith(_$ChatMessagesModelImpl value, - $Res Function(_$ChatMessagesModelImpl) then) = +abstract class _$$ChatMessagesModelImplCopyWith<$Res> implements $ChatMessagesModelCopyWith<$Res> { + factory _$$ChatMessagesModelImplCopyWith(_$ChatMessagesModelImpl value, $Res Function(_$ChatMessagesModelImpl) then) = __$$ChatMessagesModelImplCopyWithImpl<$Res>; @override @useResult - $Res call( - {@JsonKey(name: 'data') List messagesList, - ChatMetaModel meta}); + $Res call({@JsonKey(name: 'data') List messagesList, ChatMetaModel meta}); @override $ChatMetaModelCopyWith<$Res> get meta; } /// @nodoc -class __$$ChatMessagesModelImplCopyWithImpl<$Res> - extends _$ChatMessagesModelCopyWithImpl<$Res, _$ChatMessagesModelImpl> +class __$$ChatMessagesModelImplCopyWithImpl<$Res> extends _$ChatMessagesModelCopyWithImpl<$Res, _$ChatMessagesModelImpl> implements _$$ChatMessagesModelImplCopyWith<$Res> { - __$$ChatMessagesModelImplCopyWithImpl(_$ChatMessagesModelImpl _value, - $Res Function(_$ChatMessagesModelImpl) _then) - : super(_value, _then); + __$$ChatMessagesModelImplCopyWithImpl(_$ChatMessagesModelImpl _value, $Res Function(_$ChatMessagesModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -126,14 +113,9 @@ class __$$ChatMessagesModelImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() class _$ChatMessagesModelImpl implements _ChatMessagesModel { - const _$ChatMessagesModelImpl( - {@JsonKey(name: 'data') - required final List messagesList, - required this.meta}) - : _messagesList = messagesList; + const _$ChatMessagesModelImpl({@JsonKey(name: 'data') required final List messagesList, required this.meta}) : _messagesList = messagesList; - factory _$ChatMessagesModelImpl.fromJson(Map json) => - _$$ChatMessagesModelImplFromJson(json); + factory _$ChatMessagesModelImpl.fromJson(Map json) => _$$ChatMessagesModelImplFromJson(json); final List _messagesList; @override @@ -157,22 +139,18 @@ class _$ChatMessagesModelImpl implements _ChatMessagesModel { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatMessagesModelImpl && - const DeepCollectionEquality() - .equals(other._messagesList, _messagesList) && + const DeepCollectionEquality().equals(other._messagesList, _messagesList) && (identical(other.meta, meta) || other.meta == meta)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash( - runtimeType, const DeepCollectionEquality().hash(_messagesList), meta); + int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_messagesList), meta); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => - __$$ChatMessagesModelImplCopyWithImpl<_$ChatMessagesModelImpl>( - this, _$identity); + _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => __$$ChatMessagesModelImplCopyWithImpl<_$ChatMessagesModelImpl>(this, _$identity); @override Map toJson() { @@ -183,13 +161,10 @@ class _$ChatMessagesModelImpl implements _ChatMessagesModel { } abstract class _ChatMessagesModel implements ChatMessagesModel { - const factory _ChatMessagesModel( - {@JsonKey(name: 'data') - required final List messagesList, - required final ChatMetaModel meta}) = _$ChatMessagesModelImpl; + const factory _ChatMessagesModel({@JsonKey(name: 'data') required final List messagesList, required final ChatMetaModel meta}) = + _$ChatMessagesModelImpl; - factory _ChatMessagesModel.fromJson(Map json) = - _$ChatMessagesModelImpl.fromJson; + factory _ChatMessagesModel.fromJson(Map json) = _$ChatMessagesModelImpl.fromJson; @override @JsonKey(name: 'data') @@ -198,6 +173,5 @@ abstract class _ChatMessagesModel implements ChatMessagesModel { ChatMetaModel get meta; @override @JsonKey(ignore: true) - _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_messages_model.g.dart b/lib/features/chat/models/chat_messages_model.g.dart index 6216cd8..1a7fe48 100644 --- a/lib/features/chat/models/chat_messages_model.g.dart +++ b/lib/features/chat/models/chat_messages_model.g.dart @@ -6,18 +6,12 @@ part of 'chat_messages_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatMessagesModelImpl _$$ChatMessagesModelImplFromJson( - Map json) => - _$ChatMessagesModelImpl( - messagesList: (json['data'] as List) - .map((e) => ChatMessageModel.fromJson(e as Map)) - .toList(), +_$ChatMessagesModelImpl _$$ChatMessagesModelImplFromJson(Map json) => _$ChatMessagesModelImpl( + messagesList: (json['data'] as List).map((e) => ChatMessageModel.fromJson(e as Map)).toList(), meta: ChatMetaModel.fromJson(json['meta'] as Map), ); -Map _$$ChatMessagesModelImplToJson( - _$ChatMessagesModelImpl instance) => - { +Map _$$ChatMessagesModelImplToJson(_$ChatMessagesModelImpl instance) => { 'data': instance.messagesList, 'meta': instance.meta, }; diff --git a/lib/features/chat/models/chat_meta_model.dart b/lib/features/chat/models/chat_meta_model.dart index 4c4d6cf..b1e68a4 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_meta_model.freezed.dart b/lib/features/chat/models/chat_meta_model.freezed.dart index 11ecb9e..91eec02 100644 --- a/lib/features/chat/models/chat_meta_model.freezed.dart +++ b/lib/features/chat/models/chat_meta_model.freezed.dart @@ -25,22 +25,18 @@ mixin _$ChatMetaModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $ChatMetaModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $ChatMetaModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatMetaModelCopyWith<$Res> { - factory $ChatMetaModelCopyWith( - ChatMetaModel value, $Res Function(ChatMetaModel) then) = - _$ChatMetaModelCopyWithImpl<$Res, ChatMetaModel>; + factory $ChatMetaModelCopyWith(ChatMetaModel value, $Res Function(ChatMetaModel) then) = _$ChatMetaModelCopyWithImpl<$Res, ChatMetaModel>; @useResult $Res call({@JsonKey(name: "last_page") int lastPage}); } /// @nodoc -class _$ChatMetaModelCopyWithImpl<$Res, $Val extends ChatMetaModel> - implements $ChatMetaModelCopyWith<$Res> { +class _$ChatMetaModelCopyWithImpl<$Res, $Val extends ChatMetaModel> implements $ChatMetaModelCopyWith<$Res> { _$ChatMetaModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -63,23 +59,16 @@ class _$ChatMetaModelCopyWithImpl<$Res, $Val extends ChatMetaModel> } /// @nodoc -abstract class _$$ChatMetaModelImplCopyWith<$Res> - implements $ChatMetaModelCopyWith<$Res> { - factory _$$ChatMetaModelImplCopyWith( - _$ChatMetaModelImpl value, $Res Function(_$ChatMetaModelImpl) then) = - __$$ChatMetaModelImplCopyWithImpl<$Res>; +abstract class _$$ChatMetaModelImplCopyWith<$Res> implements $ChatMetaModelCopyWith<$Res> { + factory _$$ChatMetaModelImplCopyWith(_$ChatMetaModelImpl value, $Res Function(_$ChatMetaModelImpl) then) = __$$ChatMetaModelImplCopyWithImpl<$Res>; @override @useResult $Res call({@JsonKey(name: "last_page") int lastPage}); } /// @nodoc -class __$$ChatMetaModelImplCopyWithImpl<$Res> - extends _$ChatMetaModelCopyWithImpl<$Res, _$ChatMetaModelImpl> - implements _$$ChatMetaModelImplCopyWith<$Res> { - __$$ChatMetaModelImplCopyWithImpl( - _$ChatMetaModelImpl _value, $Res Function(_$ChatMetaModelImpl) _then) - : super(_value, _then); +class __$$ChatMetaModelImplCopyWithImpl<$Res> extends _$ChatMetaModelCopyWithImpl<$Res, _$ChatMetaModelImpl> implements _$$ChatMetaModelImplCopyWith<$Res> { + __$$ChatMetaModelImplCopyWithImpl(_$ChatMetaModelImpl _value, $Res Function(_$ChatMetaModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -98,11 +87,9 @@ class __$$ChatMetaModelImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() class _$ChatMetaModelImpl implements _ChatMetaModel { - const _$ChatMetaModelImpl( - {@JsonKey(name: "last_page") required this.lastPage}); + const _$ChatMetaModelImpl({@JsonKey(name: "last_page") required this.lastPage}); - factory _$ChatMetaModelImpl.fromJson(Map json) => - _$$ChatMetaModelImplFromJson(json); + factory _$ChatMetaModelImpl.fromJson(Map json) => _$$ChatMetaModelImplFromJson(json); @override @JsonKey(name: "last_page") @@ -116,10 +103,7 @@ class _$ChatMetaModelImpl implements _ChatMetaModel { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$ChatMetaModelImpl && - (identical(other.lastPage, lastPage) || - other.lastPage == lastPage)); + (other.runtimeType == runtimeType && other is _$ChatMetaModelImpl && (identical(other.lastPage, lastPage) || other.lastPage == lastPage)); } @JsonKey(ignore: true) @@ -129,8 +113,7 @@ class _$ChatMetaModelImpl implements _ChatMetaModel { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => - __$$ChatMetaModelImplCopyWithImpl<_$ChatMetaModelImpl>(this, _$identity); + _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => __$$ChatMetaModelImplCopyWithImpl<_$ChatMetaModelImpl>(this, _$identity); @override Map toJson() { @@ -141,18 +124,14 @@ class _$ChatMetaModelImpl implements _ChatMetaModel { } abstract class _ChatMetaModel implements ChatMetaModel { - const factory _ChatMetaModel( - {@JsonKey(name: "last_page") required final int lastPage}) = - _$ChatMetaModelImpl; + const factory _ChatMetaModel({@JsonKey(name: "last_page") required final int lastPage}) = _$ChatMetaModelImpl; - factory _ChatMetaModel.fromJson(Map json) = - _$ChatMetaModelImpl.fromJson; + factory _ChatMetaModel.fromJson(Map json) = _$ChatMetaModelImpl.fromJson; @override @JsonKey(name: "last_page") int get lastPage; @override @JsonKey(ignore: true) - _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_meta_model.g.dart b/lib/features/chat/models/chat_meta_model.g.dart index 7126e2d..bbd16d1 100644 --- a/lib/features/chat/models/chat_meta_model.g.dart +++ b/lib/features/chat/models/chat_meta_model.g.dart @@ -6,12 +6,10 @@ part of 'chat_meta_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatMetaModelImpl _$$ChatMetaModelImplFromJson(Map json) => - _$ChatMetaModelImpl( +_$ChatMetaModelImpl _$$ChatMetaModelImplFromJson(Map json) => _$ChatMetaModelImpl( lastPage: (json['last_page'] as num).toInt(), ); -Map _$$ChatMetaModelImplToJson(_$ChatMetaModelImpl instance) => - { +Map _$$ChatMetaModelImplToJson(_$ChatMetaModelImpl instance) => { 'last_page': instance.lastPage, }; diff --git a/lib/features/chat/models/chat_room_model.dart b/lib/features/chat/models/chat_room_model.dart index 0196b49..f9e9a41 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_model.freezed.dart b/lib/features/chat/models/chat_room_model.freezed.dart index 5a0b6e6..216c1b6 100644 --- a/lib/features/chat/models/chat_room_model.freezed.dart +++ b/lib/features/chat/models/chat_room_model.freezed.dart @@ -22,34 +22,25 @@ ChatRoomModel _$ChatRoomModelFromJson(Map json) { mixin _$ChatRoomModel { String get id => throw _privateConstructorUsedError; @JsonKey(name: 'chat_room_setting') - ChatRoomSettingsModel get chatRoomSettings => - throw _privateConstructorUsedError; + ChatRoomSettingsModel get chatRoomSettings => throw _privateConstructorUsedError; Map get users => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $ChatRoomModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $ChatRoomModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatRoomModelCopyWith<$Res> { - factory $ChatRoomModelCopyWith( - ChatRoomModel value, $Res Function(ChatRoomModel) then) = - _$ChatRoomModelCopyWithImpl<$Res, ChatRoomModel>; + factory $ChatRoomModelCopyWith(ChatRoomModel value, $Res Function(ChatRoomModel) then) = _$ChatRoomModelCopyWithImpl<$Res, ChatRoomModel>; @useResult - $Res call( - {String id, - @JsonKey(name: 'chat_room_setting') - ChatRoomSettingsModel chatRoomSettings, - Map users}); + $Res call({String id, @JsonKey(name: 'chat_room_setting') ChatRoomSettingsModel chatRoomSettings, Map users}); $ChatRoomSettingsModelCopyWith<$Res> get chatRoomSettings; } /// @nodoc -class _$ChatRoomModelCopyWithImpl<$Res, $Val extends ChatRoomModel> - implements $ChatRoomModelCopyWith<$Res> { +class _$ChatRoomModelCopyWithImpl<$Res, $Val extends ChatRoomModel> implements $ChatRoomModelCopyWith<$Res> { _$ChatRoomModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -83,38 +74,26 @@ class _$ChatRoomModelCopyWithImpl<$Res, $Val extends ChatRoomModel> @override @pragma('vm:prefer-inline') $ChatRoomSettingsModelCopyWith<$Res> get chatRoomSettings { - return $ChatRoomSettingsModelCopyWith<$Res>(_value.chatRoomSettings, - (value) { + return $ChatRoomSettingsModelCopyWith<$Res>(_value.chatRoomSettings, (value) { return _then(_value.copyWith(chatRoomSettings: value) as $Val); }); } } /// @nodoc -abstract class _$$ChatRoomModelImplCopyWith<$Res> - implements $ChatRoomModelCopyWith<$Res> { - factory _$$ChatRoomModelImplCopyWith( - _$ChatRoomModelImpl value, $Res Function(_$ChatRoomModelImpl) then) = - __$$ChatRoomModelImplCopyWithImpl<$Res>; +abstract class _$$ChatRoomModelImplCopyWith<$Res> implements $ChatRoomModelCopyWith<$Res> { + factory _$$ChatRoomModelImplCopyWith(_$ChatRoomModelImpl value, $Res Function(_$ChatRoomModelImpl) then) = __$$ChatRoomModelImplCopyWithImpl<$Res>; @override @useResult - $Res call( - {String id, - @JsonKey(name: 'chat_room_setting') - ChatRoomSettingsModel chatRoomSettings, - Map users}); + $Res call({String id, @JsonKey(name: 'chat_room_setting') ChatRoomSettingsModel chatRoomSettings, Map users}); @override $ChatRoomSettingsModelCopyWith<$Res> get chatRoomSettings; } /// @nodoc -class __$$ChatRoomModelImplCopyWithImpl<$Res> - extends _$ChatRoomModelCopyWithImpl<$Res, _$ChatRoomModelImpl> - implements _$$ChatRoomModelImplCopyWith<$Res> { - __$$ChatRoomModelImplCopyWithImpl( - _$ChatRoomModelImpl _value, $Res Function(_$ChatRoomModelImpl) _then) - : super(_value, _then); +class __$$ChatRoomModelImplCopyWithImpl<$Res> extends _$ChatRoomModelCopyWithImpl<$Res, _$ChatRoomModelImpl> implements _$$ChatRoomModelImplCopyWith<$Res> { + __$$ChatRoomModelImplCopyWithImpl(_$ChatRoomModelImpl _value, $Res Function(_$ChatRoomModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -144,13 +123,10 @@ class __$$ChatRoomModelImplCopyWithImpl<$Res> @JsonSerializable() class _$ChatRoomModelImpl implements _ChatRoomModel { const _$ChatRoomModelImpl( - {required this.id, - @JsonKey(name: 'chat_room_setting') required this.chatRoomSettings, - required final Map users}) + {required this.id, @JsonKey(name: 'chat_room_setting') required this.chatRoomSettings, required final Map users}) : _users = users; - factory _$ChatRoomModelImpl.fromJson(Map json) => - _$$ChatRoomModelImplFromJson(json); + factory _$ChatRoomModelImpl.fromJson(Map json) => _$$ChatRoomModelImplFromJson(json); @override final String id; @@ -176,21 +152,18 @@ class _$ChatRoomModelImpl implements _ChatRoomModel { (other.runtimeType == runtimeType && other is _$ChatRoomModelImpl && (identical(other.id, id) || other.id == id) && - (identical(other.chatRoomSettings, chatRoomSettings) || - other.chatRoomSettings == chatRoomSettings) && + (identical(other.chatRoomSettings, chatRoomSettings) || other.chatRoomSettings == chatRoomSettings) && const DeepCollectionEquality().equals(other._users, _users)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, chatRoomSettings, - const DeepCollectionEquality().hash(_users)); + int get hashCode => Object.hash(runtimeType, id, chatRoomSettings, const DeepCollectionEquality().hash(_users)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => - __$$ChatRoomModelImplCopyWithImpl<_$ChatRoomModelImpl>(this, _$identity); + _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => __$$ChatRoomModelImplCopyWithImpl<_$ChatRoomModelImpl>(this, _$identity); @override Map toJson() { @@ -203,12 +176,10 @@ class _$ChatRoomModelImpl implements _ChatRoomModel { abstract class _ChatRoomModel implements ChatRoomModel { const factory _ChatRoomModel( {required final String id, - @JsonKey(name: 'chat_room_setting') - required final ChatRoomSettingsModel chatRoomSettings, + @JsonKey(name: 'chat_room_setting') required final ChatRoomSettingsModel chatRoomSettings, required final Map users}) = _$ChatRoomModelImpl; - factory _ChatRoomModel.fromJson(Map json) = - _$ChatRoomModelImpl.fromJson; + factory _ChatRoomModel.fromJson(Map json) = _$ChatRoomModelImpl.fromJson; @override String get id; @@ -219,6 +190,5 @@ abstract class _ChatRoomModel implements ChatRoomModel { Map get users; @override @JsonKey(ignore: true) - _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_room_model.g.dart b/lib/features/chat/models/chat_room_model.g.dart index 68d3195..6230d4f 100644 --- a/lib/features/chat/models/chat_room_model.g.dart +++ b/lib/features/chat/models/chat_room_model.g.dart @@ -6,19 +6,15 @@ part of 'chat_room_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatRoomModelImpl _$$ChatRoomModelImplFromJson(Map json) => - _$ChatRoomModelImpl( +_$ChatRoomModelImpl _$$ChatRoomModelImplFromJson(Map json) => _$ChatRoomModelImpl( id: json['id'] as String, - chatRoomSettings: ChatRoomSettingsModel.fromJson( - json['chat_room_setting'] as Map), + chatRoomSettings: ChatRoomSettingsModel.fromJson(json['chat_room_setting'] as Map), users: (json['users'] as Map).map( - (k, e) => - MapEntry(k, ChatUserModel.fromJson(e as Map)), + (k, e) => MapEntry(k, ChatUserModel.fromJson(e as Map)), ), ); -Map _$$ChatRoomModelImplToJson(_$ChatRoomModelImpl instance) => - { +Map _$$ChatRoomModelImplToJson(_$ChatRoomModelImpl instance) => { 'id': instance.id, 'chat_room_setting': instance.chatRoomSettings, 'users': instance.users, diff --git a/lib/features/chat/models/chat_room_settings_model.dart b/lib/features/chat/models/chat_room_settings_model.dart index 7262c9a..de41f22 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_room_settings_model.freezed.dart b/lib/features/chat/models/chat_room_settings_model.freezed.dart index 4f21755..af23772 100644 --- a/lib/features/chat/models/chat_room_settings_model.freezed.dart +++ b/lib/features/chat/models/chat_room_settings_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'); -ChatRoomSettingsModel _$ChatRoomSettingsModelFromJson( - Map json) { +ChatRoomSettingsModel _$ChatRoomSettingsModelFromJson(Map json) { return _ChatRoomSettingsModel.fromJson(json); } @@ -32,14 +31,12 @@ mixin _$ChatRoomSettingsModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $ChatRoomSettingsModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $ChatRoomSettingsModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatRoomSettingsModelCopyWith<$Res> { - factory $ChatRoomSettingsModelCopyWith(ChatRoomSettingsModel value, - $Res Function(ChatRoomSettingsModel) then) = + factory $ChatRoomSettingsModelCopyWith(ChatRoomSettingsModel value, $Res Function(ChatRoomSettingsModel) then) = _$ChatRoomSettingsModelCopyWithImpl<$Res, ChatRoomSettingsModel>; @useResult $Res call( @@ -51,9 +48,7 @@ abstract class $ChatRoomSettingsModelCopyWith<$Res> { } /// @nodoc -class _$ChatRoomSettingsModelCopyWithImpl<$Res, - $Val extends ChatRoomSettingsModel> - implements $ChatRoomSettingsModelCopyWith<$Res> { +class _$ChatRoomSettingsModelCopyWithImpl<$Res, $Val extends ChatRoomSettingsModel> implements $ChatRoomSettingsModelCopyWith<$Res> { _$ChatRoomSettingsModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -96,11 +91,8 @@ class _$ChatRoomSettingsModelCopyWithImpl<$Res, } /// @nodoc -abstract class _$$ChatRoomSettingsModelImplCopyWith<$Res> - implements $ChatRoomSettingsModelCopyWith<$Res> { - factory _$$ChatRoomSettingsModelImplCopyWith( - _$ChatRoomSettingsModelImpl value, - $Res Function(_$ChatRoomSettingsModelImpl) then) = +abstract class _$$ChatRoomSettingsModelImplCopyWith<$Res> implements $ChatRoomSettingsModelCopyWith<$Res> { + factory _$$ChatRoomSettingsModelImplCopyWith(_$ChatRoomSettingsModelImpl value, $Res Function(_$ChatRoomSettingsModelImpl) then) = __$$ChatRoomSettingsModelImplCopyWithImpl<$Res>; @override @useResult @@ -113,13 +105,9 @@ abstract class _$$ChatRoomSettingsModelImplCopyWith<$Res> } /// @nodoc -class __$$ChatRoomSettingsModelImplCopyWithImpl<$Res> - extends _$ChatRoomSettingsModelCopyWithImpl<$Res, - _$ChatRoomSettingsModelImpl> +class __$$ChatRoomSettingsModelImplCopyWithImpl<$Res> extends _$ChatRoomSettingsModelCopyWithImpl<$Res, _$ChatRoomSettingsModelImpl> implements _$$ChatRoomSettingsModelImplCopyWith<$Res> { - __$$ChatRoomSettingsModelImplCopyWithImpl(_$ChatRoomSettingsModelImpl _value, - $Res Function(_$ChatRoomSettingsModelImpl) _then) - : super(_value, _then); + __$$ChatRoomSettingsModelImplCopyWithImpl(_$ChatRoomSettingsModelImpl _value, $Res Function(_$ChatRoomSettingsModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -165,8 +153,7 @@ class _$ChatRoomSettingsModelImpl implements _ChatRoomSettingsModel { @JsonKey(name: 'access_level') required this.accessLevel, @JsonKey(name: 'updated_at') required this.updatedAt}); - factory _$ChatRoomSettingsModelImpl.fromJson(Map json) => - _$$ChatRoomSettingsModelImplFromJson(json); + factory _$ChatRoomSettingsModelImpl.fromJson(Map json) => _$$ChatRoomSettingsModelImplFromJson(json); @override final int id; @@ -193,26 +180,21 @@ class _$ChatRoomSettingsModelImpl implements _ChatRoomSettingsModel { (other.runtimeType == runtimeType && other is _$ChatRoomSettingsModelImpl && (identical(other.id, id) || other.id == id) && - (identical(other.roomName, roomName) || - other.roomName == roomName) && + (identical(other.roomName, roomName) || other.roomName == roomName) && (identical(other.state, state) || other.state == state) && - (identical(other.accessLevel, accessLevel) || - other.accessLevel == accessLevel) && - (identical(other.updatedAt, updatedAt) || - other.updatedAt == updatedAt)); + (identical(other.accessLevel, accessLevel) || other.accessLevel == accessLevel) && + (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)); } @JsonKey(ignore: true) @override - int get hashCode => - Object.hash(runtimeType, id, roomName, state, accessLevel, updatedAt); + int get hashCode => Object.hash(runtimeType, id, roomName, state, accessLevel, updatedAt); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> - get copyWith => __$$ChatRoomSettingsModelImplCopyWithImpl< - _$ChatRoomSettingsModelImpl>(this, _$identity); + _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> get copyWith => + __$$ChatRoomSettingsModelImplCopyWithImpl<_$ChatRoomSettingsModelImpl>(this, _$identity); @override Map toJson() { @@ -224,15 +206,13 @@ class _$ChatRoomSettingsModelImpl implements _ChatRoomSettingsModel { abstract class _ChatRoomSettingsModel implements ChatRoomSettingsModel { const factory _ChatRoomSettingsModel( - {required final int id, - @JsonKey(name: 'room_name') required final String roomName, - required final String state, - @JsonKey(name: 'access_level') required final String accessLevel, - @JsonKey(name: 'updated_at') required final String updatedAt}) = - _$ChatRoomSettingsModelImpl; + {required final int id, + @JsonKey(name: 'room_name') required final String roomName, + required final String state, + @JsonKey(name: 'access_level') required final String accessLevel, + @JsonKey(name: 'updated_at') required final String updatedAt}) = _$ChatRoomSettingsModelImpl; - factory _ChatRoomSettingsModel.fromJson(Map json) = - _$ChatRoomSettingsModelImpl.fromJson; + factory _ChatRoomSettingsModel.fromJson(Map json) = _$ChatRoomSettingsModelImpl.fromJson; @override int get id; @@ -249,6 +229,5 @@ abstract class _ChatRoomSettingsModel implements ChatRoomSettingsModel { String get updatedAt; @override @JsonKey(ignore: true) - _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> - get copyWith => throw _privateConstructorUsedError; + _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_room_settings_model.g.dart b/lib/features/chat/models/chat_room_settings_model.g.dart index 7b82433..1a2ef32 100644 --- a/lib/features/chat/models/chat_room_settings_model.g.dart +++ b/lib/features/chat/models/chat_room_settings_model.g.dart @@ -6,9 +6,7 @@ part of 'chat_room_settings_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatRoomSettingsModelImpl _$$ChatRoomSettingsModelImplFromJson( - Map json) => - _$ChatRoomSettingsModelImpl( +_$ChatRoomSettingsModelImpl _$$ChatRoomSettingsModelImplFromJson(Map json) => _$ChatRoomSettingsModelImpl( id: (json['id'] as num).toInt(), roomName: json['room_name'] as String, state: json['state'] as String, @@ -16,9 +14,7 @@ _$ChatRoomSettingsModelImpl _$$ChatRoomSettingsModelImplFromJson( updatedAt: json['updated_at'] as String, ); -Map _$$ChatRoomSettingsModelImplToJson( - _$ChatRoomSettingsModelImpl instance) => - { +Map _$$ChatRoomSettingsModelImplToJson(_$ChatRoomSettingsModelImpl instance) => { 'id': instance.id, 'room_name': instance.roomName, 'state': instance.state, diff --git a/lib/features/chat/models/chat_user_model.dart b/lib/features/chat/models/chat_user_model.dart index dd8bf02..4ead086 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/chat_user_model.freezed.dart b/lib/features/chat/models/chat_user_model.freezed.dart index 095c09e..2827fa1 100644 --- a/lib/features/chat/models/chat_user_model.freezed.dart +++ b/lib/features/chat/models/chat_user_model.freezed.dart @@ -29,26 +29,18 @@ mixin _$ChatUserModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $ChatUserModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $ChatUserModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatUserModelCopyWith<$Res> { - factory $ChatUserModelCopyWith( - ChatUserModel value, $Res Function(ChatUserModel) then) = - _$ChatUserModelCopyWithImpl<$Res, ChatUserModel>; + factory $ChatUserModelCopyWith(ChatUserModel value, $Res Function(ChatUserModel) then) = _$ChatUserModelCopyWithImpl<$Res, ChatUserModel>; @useResult - $Res call( - {int id, - String name, - @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, - @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); + $Res call({int id, String name, @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); } /// @nodoc -class _$ChatUserModelCopyWithImpl<$Res, $Val extends ChatUserModel> - implements $ChatUserModelCopyWith<$Res> { +class _$ChatUserModelCopyWithImpl<$Res, $Val extends ChatUserModel> implements $ChatUserModelCopyWith<$Res> { _$ChatUserModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -86,27 +78,16 @@ class _$ChatUserModelCopyWithImpl<$Res, $Val extends ChatUserModel> } /// @nodoc -abstract class _$$ChatUserModelImplCopyWith<$Res> - implements $ChatUserModelCopyWith<$Res> { - factory _$$ChatUserModelImplCopyWith( - _$ChatUserModelImpl value, $Res Function(_$ChatUserModelImpl) then) = - __$$ChatUserModelImplCopyWithImpl<$Res>; +abstract class _$$ChatUserModelImplCopyWith<$Res> implements $ChatUserModelCopyWith<$Res> { + factory _$$ChatUserModelImplCopyWith(_$ChatUserModelImpl value, $Res Function(_$ChatUserModelImpl) then) = __$$ChatUserModelImplCopyWithImpl<$Res>; @override @useResult - $Res call( - {int id, - String name, - @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, - @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); + $Res call({int id, String name, @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); } /// @nodoc -class __$$ChatUserModelImplCopyWithImpl<$Res> - extends _$ChatUserModelCopyWithImpl<$Res, _$ChatUserModelImpl> - implements _$$ChatUserModelImplCopyWith<$Res> { - __$$ChatUserModelImplCopyWithImpl( - _$ChatUserModelImpl _value, $Res Function(_$ChatUserModelImpl) _then) - : super(_value, _then); +class __$$ChatUserModelImplCopyWithImpl<$Res> extends _$ChatUserModelCopyWithImpl<$Res, _$ChatUserModelImpl> implements _$$ChatUserModelImplCopyWith<$Res> { + __$$ChatUserModelImplCopyWithImpl(_$ChatUserModelImpl _value, $Res Function(_$ChatUserModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -146,8 +127,7 @@ class _$ChatUserModelImpl implements _ChatUserModel { @JsonKey(name: 'profile_photo_path') this.profilePhotoPath, @JsonKey(name: 'profile_photo_url') this.profilePhotoUrl}); - factory _$ChatUserModelImpl.fromJson(Map json) => - _$$ChatUserModelImplFromJson(json); + factory _$ChatUserModelImpl.fromJson(Map json) => _$$ChatUserModelImplFromJson(json); @override final int id; @@ -172,22 +152,18 @@ class _$ChatUserModelImpl implements _ChatUserModel { other is _$ChatUserModelImpl && (identical(other.id, id) || other.id == id) && (identical(other.name, name) || other.name == name) && - (identical(other.profilePhotoPath, profilePhotoPath) || - other.profilePhotoPath == profilePhotoPath) && - (identical(other.profilePhotoUrl, profilePhotoUrl) || - other.profilePhotoUrl == profilePhotoUrl)); + (identical(other.profilePhotoPath, profilePhotoPath) || other.profilePhotoPath == profilePhotoPath) && + (identical(other.profilePhotoUrl, profilePhotoUrl) || other.profilePhotoUrl == profilePhotoUrl)); } @JsonKey(ignore: true) @override - int get hashCode => - Object.hash(runtimeType, id, name, profilePhotoPath, profilePhotoUrl); + int get hashCode => Object.hash(runtimeType, id, name, profilePhotoPath, profilePhotoUrl); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => - __$$ChatUserModelImplCopyWithImpl<_$ChatUserModelImpl>(this, _$identity); + _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => __$$ChatUserModelImplCopyWithImpl<_$ChatUserModelImpl>(this, _$identity); @override Map toJson() { @@ -199,14 +175,12 @@ class _$ChatUserModelImpl implements _ChatUserModel { abstract class _ChatUserModel implements ChatUserModel { const factory _ChatUserModel( - {required final int id, - required final String name, - @JsonKey(name: 'profile_photo_path') final String? profilePhotoPath, - @JsonKey(name: 'profile_photo_url') final String? profilePhotoUrl}) = - _$ChatUserModelImpl; + {required final int id, + required final String name, + @JsonKey(name: 'profile_photo_path') final String? profilePhotoPath, + @JsonKey(name: 'profile_photo_url') final String? profilePhotoUrl}) = _$ChatUserModelImpl; - factory _ChatUserModel.fromJson(Map json) = - _$ChatUserModelImpl.fromJson; + factory _ChatUserModel.fromJson(Map json) = _$ChatUserModelImpl.fromJson; @override int get id; @@ -220,6 +194,5 @@ abstract class _ChatUserModel implements ChatUserModel { String? get profilePhotoUrl; @override @JsonKey(ignore: true) - _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_user_model.g.dart b/lib/features/chat/models/chat_user_model.g.dart index 78e0f98..06fa92a 100644 --- a/lib/features/chat/models/chat_user_model.g.dart +++ b/lib/features/chat/models/chat_user_model.g.dart @@ -6,16 +6,14 @@ part of 'chat_user_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatUserModelImpl _$$ChatUserModelImplFromJson(Map json) => - _$ChatUserModelImpl( +_$ChatUserModelImpl _$$ChatUserModelImplFromJson(Map json) => _$ChatUserModelImpl( id: (json['id'] as num).toInt(), name: json['name'] as String, profilePhotoPath: json['profile_photo_path'] as String?, profilePhotoUrl: json['profile_photo_url'] as String?, ); -Map _$$ChatUserModelImplToJson(_$ChatUserModelImpl instance) => - { +Map _$$ChatUserModelImplToJson(_$ChatUserModelImpl instance) => { 'id': instance.id, 'name': instance.name, 'profile_photo_path': instance.profilePhotoPath, diff --git a/lib/features/chat/models/websocket_info_model.dart b/lib/features/chat/models/websocket_info_model.dart index 274b421..ed6167a 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/models/websocket_info_model.freezed.dart b/lib/features/chat/models/websocket_info_model.freezed.dart index cd383a2..2f50540 100644 --- a/lib/features/chat/models/websocket_info_model.freezed.dart +++ b/lib/features/chat/models/websocket_info_model.freezed.dart @@ -29,27 +29,19 @@ mixin _$WebsocketInfoModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $WebsocketInfoModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $WebsocketInfoModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $WebsocketInfoModelCopyWith<$Res> { - factory $WebsocketInfoModelCopyWith( - WebsocketInfoModel value, $Res Function(WebsocketInfoModel) then) = + factory $WebsocketInfoModelCopyWith(WebsocketInfoModel value, $Res Function(WebsocketInfoModel) then) = _$WebsocketInfoModelCopyWithImpl<$Res, WebsocketInfoModel>; @useResult - $Res call( - {String key, - String host, - String port, - String cluster, - @JsonKey(name: 'user_id') int userId}); + $Res call({String key, String host, String port, String cluster, @JsonKey(name: 'user_id') int userId}); } /// @nodoc -class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel> - implements $WebsocketInfoModelCopyWith<$Res> { +class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel> implements $WebsocketInfoModelCopyWith<$Res> { _$WebsocketInfoModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -92,28 +84,18 @@ class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel> } /// @nodoc -abstract class _$$WebsocketInfoModelImplCopyWith<$Res> - implements $WebsocketInfoModelCopyWith<$Res> { - factory _$$WebsocketInfoModelImplCopyWith(_$WebsocketInfoModelImpl value, - $Res Function(_$WebsocketInfoModelImpl) then) = +abstract class _$$WebsocketInfoModelImplCopyWith<$Res> implements $WebsocketInfoModelCopyWith<$Res> { + factory _$$WebsocketInfoModelImplCopyWith(_$WebsocketInfoModelImpl value, $Res Function(_$WebsocketInfoModelImpl) then) = __$$WebsocketInfoModelImplCopyWithImpl<$Res>; @override @useResult - $Res call( - {String key, - String host, - String port, - String cluster, - @JsonKey(name: 'user_id') int userId}); + $Res call({String key, String host, String port, String cluster, @JsonKey(name: 'user_id') int userId}); } /// @nodoc -class __$$WebsocketInfoModelImplCopyWithImpl<$Res> - extends _$WebsocketInfoModelCopyWithImpl<$Res, _$WebsocketInfoModelImpl> +class __$$WebsocketInfoModelImplCopyWithImpl<$Res> extends _$WebsocketInfoModelCopyWithImpl<$Res, _$WebsocketInfoModelImpl> implements _$$WebsocketInfoModelImplCopyWith<$Res> { - __$$WebsocketInfoModelImplCopyWithImpl(_$WebsocketInfoModelImpl _value, - $Res Function(_$WebsocketInfoModelImpl) _then) - : super(_value, _then); + __$$WebsocketInfoModelImplCopyWithImpl(_$WebsocketInfoModelImpl _value, $Res Function(_$WebsocketInfoModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -153,14 +135,9 @@ class __$$WebsocketInfoModelImplCopyWithImpl<$Res> @JsonSerializable() class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { const _$WebsocketInfoModelImpl( - {required this.key, - required this.host, - required this.port, - required this.cluster, - @JsonKey(name: 'user_id') required this.userId}); + {required this.key, required this.host, required this.port, required this.cluster, @JsonKey(name: 'user_id') required this.userId}); - factory _$WebsocketInfoModelImpl.fromJson(Map json) => - _$$WebsocketInfoModelImplFromJson(json); + factory _$WebsocketInfoModelImpl.fromJson(Map json) => _$$WebsocketInfoModelImplFromJson(json); @override final String key; @@ -193,15 +170,13 @@ class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { @JsonKey(ignore: true) @override - int get hashCode => - Object.hash(runtimeType, key, host, port, cluster, userId); + int get hashCode => Object.hash(runtimeType, key, host, port, cluster, userId); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith => - __$$WebsocketInfoModelImplCopyWithImpl<_$WebsocketInfoModelImpl>( - this, _$identity); + __$$WebsocketInfoModelImplCopyWithImpl<_$WebsocketInfoModelImpl>(this, _$identity); @override Map toJson() { @@ -213,15 +188,13 @@ class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { abstract class _WebsocketInfoModel implements WebsocketInfoModel { const factory _WebsocketInfoModel( - {required final String key, - required final String host, - required final String port, - required final String cluster, - @JsonKey(name: 'user_id') required final int userId}) = - _$WebsocketInfoModelImpl; + {required final String key, + required final String host, + required final String port, + required final String cluster, + @JsonKey(name: 'user_id') required final int userId}) = _$WebsocketInfoModelImpl; - factory _WebsocketInfoModel.fromJson(Map json) = - _$WebsocketInfoModelImpl.fromJson; + factory _WebsocketInfoModel.fromJson(Map json) = _$WebsocketInfoModelImpl.fromJson; @override String get key; @@ -236,6 +209,5 @@ abstract class _WebsocketInfoModel implements WebsocketInfoModel { int get userId; @override @JsonKey(ignore: true) - _$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/websocket_info_model.g.dart b/lib/features/chat/models/websocket_info_model.g.dart index b2bb124..91c386f 100644 --- a/lib/features/chat/models/websocket_info_model.g.dart +++ b/lib/features/chat/models/websocket_info_model.g.dart @@ -6,9 +6,7 @@ part of 'websocket_info_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson( - Map json) => - _$WebsocketInfoModelImpl( +_$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson(Map json) => _$WebsocketInfoModelImpl( key: json['key'] as String, host: json['host'] as String, port: json['port'] as String, @@ -16,9 +14,7 @@ _$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson( userId: (json['user_id'] as num).toInt(), ); -Map _$$WebsocketInfoModelImplToJson( - _$WebsocketInfoModelImpl instance) => - { +Map _$$WebsocketInfoModelImplToJson(_$WebsocketInfoModelImpl instance) => { 'key': instance.key, 'host': instance.host, 'port': instance.port, diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart index 43bf9df..715c1ab 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart @@ -20,9 +20,7 @@ mixin _$ChatRoomState { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading) - loaded, + required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; @@ -30,9 +28,7 @@ mixin _$ChatRoomState { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult? Function(String errorMessage)? error, }) => throw _privateConstructorUsedError; @@ -40,9 +36,7 @@ mixin _$ChatRoomState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) => @@ -76,14 +70,11 @@ mixin _$ChatRoomState { /// @nodoc abstract class $ChatRoomStateCopyWith<$Res> { - factory $ChatRoomStateCopyWith( - ChatRoomState value, $Res Function(ChatRoomState) then) = - _$ChatRoomStateCopyWithImpl<$Res, ChatRoomState>; + factory $ChatRoomStateCopyWith(ChatRoomState value, $Res Function(ChatRoomState) then) = _$ChatRoomStateCopyWithImpl<$Res, ChatRoomState>; } /// @nodoc -class _$ChatRoomStateCopyWithImpl<$Res, $Val extends ChatRoomState> - implements $ChatRoomStateCopyWith<$Res> { +class _$ChatRoomStateCopyWithImpl<$Res, $Val extends ChatRoomState> implements $ChatRoomStateCopyWith<$Res> { _$ChatRoomStateCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -94,18 +85,12 @@ class _$ChatRoomStateCopyWithImpl<$Res, $Val extends ChatRoomState> /// @nodoc abstract class _$$ChatRoomStateImplCopyWith<$Res> { - factory _$$ChatRoomStateImplCopyWith( - _$ChatRoomStateImpl value, $Res Function(_$ChatRoomStateImpl) then) = - __$$ChatRoomStateImplCopyWithImpl<$Res>; + factory _$$ChatRoomStateImplCopyWith(_$ChatRoomStateImpl value, $Res Function(_$ChatRoomStateImpl) then) = __$$ChatRoomStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$ChatRoomStateImplCopyWithImpl<$Res> - extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateImpl> - implements _$$ChatRoomStateImplCopyWith<$Res> { - __$$ChatRoomStateImplCopyWithImpl( - _$ChatRoomStateImpl _value, $Res Function(_$ChatRoomStateImpl) _then) - : super(_value, _then); +class __$$ChatRoomStateImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateImpl> implements _$$ChatRoomStateImplCopyWith<$Res> { + __$$ChatRoomStateImplCopyWithImpl(_$ChatRoomStateImpl _value, $Res Function(_$ChatRoomStateImpl) _then) : super(_value, _then); } /// @nodoc @@ -120,8 +105,7 @@ class _$ChatRoomStateImpl implements _ChatRoomState { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is _$ChatRoomStateImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateImpl); } @override @@ -132,9 +116,7 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading) - loaded, + required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, required TResult Function(String errorMessage) error, }) { return $default(); @@ -145,9 +127,7 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult? Function(String errorMessage)? error, }) { return $default?.call(); @@ -158,9 +138,7 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -214,18 +192,14 @@ abstract class _ChatRoomState implements ChatRoomState { /// @nodoc abstract class _$$ChatRoomStateLoadingImplCopyWith<$Res> { - factory _$$ChatRoomStateLoadingImplCopyWith(_$ChatRoomStateLoadingImpl value, - $Res Function(_$ChatRoomStateLoadingImpl) then) = + factory _$$ChatRoomStateLoadingImplCopyWith(_$ChatRoomStateLoadingImpl value, $Res Function(_$ChatRoomStateLoadingImpl) then) = __$$ChatRoomStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$ChatRoomStateLoadingImplCopyWithImpl<$Res> - extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadingImpl> +class __$$ChatRoomStateLoadingImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadingImpl> implements _$$ChatRoomStateLoadingImplCopyWith<$Res> { - __$$ChatRoomStateLoadingImplCopyWithImpl(_$ChatRoomStateLoadingImpl _value, - $Res Function(_$ChatRoomStateLoadingImpl) _then) - : super(_value, _then); + __$$ChatRoomStateLoadingImplCopyWithImpl(_$ChatRoomStateLoadingImpl _value, $Res Function(_$ChatRoomStateLoadingImpl) _then) : super(_value, _then); } /// @nodoc @@ -240,9 +214,7 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$ChatRoomStateLoadingImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateLoadingImpl); } @override @@ -253,9 +225,7 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading) - loaded, + required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, required TResult Function(String errorMessage) error, }) { return loading(); @@ -266,9 +236,7 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult? Function(String errorMessage)? error, }) { return loading?.call(); @@ -279,9 +247,7 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -335,26 +301,18 @@ abstract class ChatRoomStateLoading implements ChatRoomState { /// @nodoc abstract class _$$ChatRoomStateLoadedImplCopyWith<$Res> { - factory _$$ChatRoomStateLoadedImplCopyWith(_$ChatRoomStateLoadedImpl value, - $Res Function(_$ChatRoomStateLoadedImpl) then) = + factory _$$ChatRoomStateLoadedImplCopyWith(_$ChatRoomStateLoadedImpl value, $Res Function(_$ChatRoomStateLoadedImpl) then) = __$$ChatRoomStateLoadedImplCopyWithImpl<$Res>; @useResult - $Res call( - {ChatRoomModel chatRoom, - List chatMessages, - bool isTyping, - bool isLoading}); + $Res call({ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading}); $ChatRoomModelCopyWith<$Res> get chatRoom; } /// @nodoc -class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> - extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadedImpl> +class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadedImpl> implements _$$ChatRoomStateLoadedImplCopyWith<$Res> { - __$$ChatRoomStateLoadedImplCopyWithImpl(_$ChatRoomStateLoadedImpl _value, - $Res Function(_$ChatRoomStateLoadedImpl) _then) - : super(_value, _then); + __$$ChatRoomStateLoadedImplCopyWithImpl(_$ChatRoomStateLoadedImpl _value, $Res Function(_$ChatRoomStateLoadedImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -396,11 +354,7 @@ class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> /// @nodoc class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { - const _$ChatRoomStateLoadedImpl( - {required this.chatRoom, - required final List chatMessages, - required this.isTyping, - required this.isLoading}) + const _$ChatRoomStateLoadedImpl({required this.chatRoom, required final List chatMessages, required this.isTyping, required this.isLoading}) : _chatMessages = chatMessages; @override @@ -428,35 +382,27 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateLoadedImpl && - (identical(other.chatRoom, chatRoom) || - other.chatRoom == chatRoom) && - const DeepCollectionEquality() - .equals(other._chatMessages, _chatMessages) && - (identical(other.isTyping, isTyping) || - other.isTyping == isTyping) && - (identical(other.isLoading, isLoading) || - other.isLoading == isLoading)); + (identical(other.chatRoom, chatRoom) || other.chatRoom == chatRoom) && + const DeepCollectionEquality().equals(other._chatMessages, _chatMessages) && + (identical(other.isTyping, isTyping) || other.isTyping == isTyping) && + (identical(other.isLoading, isLoading) || other.isLoading == isLoading)); } @override - int get hashCode => Object.hash(runtimeType, chatRoom, - const DeepCollectionEquality().hash(_chatMessages), isTyping, isLoading); + int get hashCode => Object.hash(runtimeType, chatRoom, const DeepCollectionEquality().hash(_chatMessages), isTyping, isLoading); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$ChatRoomStateLoadedImplCopyWith<_$ChatRoomStateLoadedImpl> get copyWith => - __$$ChatRoomStateLoadedImplCopyWithImpl<_$ChatRoomStateLoadedImpl>( - this, _$identity); + __$$ChatRoomStateLoadedImplCopyWithImpl<_$ChatRoomStateLoadedImpl>(this, _$identity); @override @optionalTypeArgs TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading) - loaded, + required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, required TResult Function(String errorMessage) error, }) { return loaded(chatRoom, chatMessages, isTyping, isLoading); @@ -467,9 +413,7 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult? Function(String errorMessage)? error, }) { return loaded?.call(chatRoom, chatMessages, isTyping, isLoading); @@ -480,9 +424,7 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -542,26 +484,21 @@ abstract class ChatRoomStateLoaded implements ChatRoomState { bool get isTyping; bool get isLoading; @JsonKey(ignore: true) - _$$ChatRoomStateLoadedImplCopyWith<_$ChatRoomStateLoadedImpl> get copyWith => - throw _privateConstructorUsedError; + _$$ChatRoomStateLoadedImplCopyWith<_$ChatRoomStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$ChatRoomStateErrorImplCopyWith<$Res> { - factory _$$ChatRoomStateErrorImplCopyWith(_$ChatRoomStateErrorImpl value, - $Res Function(_$ChatRoomStateErrorImpl) then) = + factory _$$ChatRoomStateErrorImplCopyWith(_$ChatRoomStateErrorImpl value, $Res Function(_$ChatRoomStateErrorImpl) then) = __$$ChatRoomStateErrorImplCopyWithImpl<$Res>; @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$ChatRoomStateErrorImplCopyWithImpl<$Res> - extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateErrorImpl> +class __$$ChatRoomStateErrorImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateErrorImpl> implements _$$ChatRoomStateErrorImplCopyWith<$Res> { - __$$ChatRoomStateErrorImplCopyWithImpl(_$ChatRoomStateErrorImpl _value, - $Res Function(_$ChatRoomStateErrorImpl) _then) - : super(_value, _then); + __$$ChatRoomStateErrorImplCopyWithImpl(_$ChatRoomStateErrorImpl _value, $Res Function(_$ChatRoomStateErrorImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -595,8 +532,7 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateErrorImpl && - (identical(other.errorMessage, errorMessage) || - other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); } @override @@ -606,17 +542,14 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { @override @pragma('vm:prefer-inline') _$$ChatRoomStateErrorImplCopyWith<_$ChatRoomStateErrorImpl> get copyWith => - __$$ChatRoomStateErrorImplCopyWithImpl<_$ChatRoomStateErrorImpl>( - this, _$identity); + __$$ChatRoomStateErrorImplCopyWithImpl<_$ChatRoomStateErrorImpl>(this, _$identity); @override @optionalTypeArgs TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading) - loaded, + required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, required TResult Function(String errorMessage) error, }) { return error(errorMessage); @@ -627,9 +560,7 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult? Function(String errorMessage)? error, }) { return error?.call(errorMessage); @@ -640,9 +571,7 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -691,11 +620,9 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { } abstract class ChatRoomStateError implements ChatRoomState { - const factory ChatRoomStateError({required final String errorMessage}) = - _$ChatRoomStateErrorImpl; + const factory ChatRoomStateError({required final String errorMessage}) = _$ChatRoomStateErrorImpl; String get errorMessage; @JsonKey(ignore: true) - _$$ChatRoomStateErrorImplCopyWith<_$ChatRoomStateErrorImpl> get copyWith => - throw _privateConstructorUsedError; + _$$ChatRoomStateErrorImplCopyWith<_$ChatRoomStateErrorImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/presentation/pages/chat_screen.dart b/lib/features/chat/presentation/pages/chat_screen.dart index 208ff96..d474712 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, 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 a055b5e..8c60e60 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 e5f1262..2ee186f 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 22020a9..1b8b49e 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 dc3f3d2..3df79df 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); 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 4836f94..0e46e71 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 f576a58..a070103 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 6f9e938..5a773cc 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 675d680..888aaba 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 65eb7c5..8d212c4 100644 --- a/lib/features/chat/services/chat_service.g.dart +++ b/lib/features/chat/services/chat_service.g.dart @@ -24,25 +24,23 @@ class _ChatService implements ChatService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>( - _setStreamType>(Options( + final _result = await _dio.fetch>(_setStreamType>(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/chat/show/${id}', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - var _value = _result.data!.map((k, dynamic v) => - MapEntry(k, ChatRoomModel.fromJson(v as Map))); + .compose( + _dio.options, + '/api/chat/show/${id}', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + var _value = _result.data!.map((k, dynamic v) => MapEntry(k, ChatRoomModel.fromJson(v as Map))); return _value; } @@ -78,7 +76,7 @@ class _ChatService implements ChatService { ) .compose( _dio.options, - '/chat/${id}/message/send', + '/api/chat/${id}/message/send', queryParameters: queryParameters, data: _data, ) @@ -98,23 +96,22 @@ class _ChatService implements ChatService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType(Options( + final _result = await _dio.fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/chat/show/${id}/messages?page=${page}', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/chat/show/${id}/messages?page=${page}', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = ChatMessagesModel.fromJson(_result.data!); return _value; } @@ -125,31 +122,28 @@ class _ChatService implements ChatService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType(Options( + final _result = await _dio.fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/profile/ws/params', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/profile/ws/params', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = WebsocketInfoModel.fromJson(_result.data!); return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && - !(requestOptions.responseType == ResponseType.bytes || - requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { diff --git a/lib/features/diary/models/diary_model.freezed.dart b/lib/features/diary/models/diary_model.freezed.dart index 5ede010..b593541 100644 --- a/lib/features/diary/models/diary_model.freezed.dart +++ b/lib/features/diary/models/diary_model.freezed.dart @@ -30,29 +30,18 @@ mixin _$DiaryModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $DiaryModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $DiaryModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $DiaryModelCopyWith<$Res> { - factory $DiaryModelCopyWith( - DiaryModel value, $Res Function(DiaryModel) then) = - _$DiaryModelCopyWithImpl<$Res, DiaryModel>; + factory $DiaryModelCopyWith(DiaryModel value, $Res Function(DiaryModel) then) = _$DiaryModelCopyWithImpl<$Res, DiaryModel>; @useResult - $Res call( - {int id, - DateTime date, - DateTime wakeup, - DateTime retire, - int closed, - String comment, - List meals}); + $Res call({int id, DateTime date, DateTime wakeup, DateTime retire, int closed, String comment, List meals}); } /// @nodoc -class _$DiaryModelCopyWithImpl<$Res, $Val extends DiaryModel> - implements $DiaryModelCopyWith<$Res> { +class _$DiaryModelCopyWithImpl<$Res, $Val extends DiaryModel> implements $DiaryModelCopyWith<$Res> { _$DiaryModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -105,30 +94,16 @@ class _$DiaryModelCopyWithImpl<$Res, $Val extends DiaryModel> } /// @nodoc -abstract class _$$DiaryModelImplCopyWith<$Res> - implements $DiaryModelCopyWith<$Res> { - factory _$$DiaryModelImplCopyWith( - _$DiaryModelImpl value, $Res Function(_$DiaryModelImpl) then) = - __$$DiaryModelImplCopyWithImpl<$Res>; +abstract class _$$DiaryModelImplCopyWith<$Res> implements $DiaryModelCopyWith<$Res> { + factory _$$DiaryModelImplCopyWith(_$DiaryModelImpl value, $Res Function(_$DiaryModelImpl) then) = __$$DiaryModelImplCopyWithImpl<$Res>; @override @useResult - $Res call( - {int id, - DateTime date, - DateTime wakeup, - DateTime retire, - int closed, - String comment, - List meals}); + $Res call({int id, DateTime date, DateTime wakeup, DateTime retire, int closed, String comment, List meals}); } /// @nodoc -class __$$DiaryModelImplCopyWithImpl<$Res> - extends _$DiaryModelCopyWithImpl<$Res, _$DiaryModelImpl> - implements _$$DiaryModelImplCopyWith<$Res> { - __$$DiaryModelImplCopyWithImpl( - _$DiaryModelImpl _value, $Res Function(_$DiaryModelImpl) _then) - : super(_value, _then); +class __$$DiaryModelImplCopyWithImpl<$Res> extends _$DiaryModelCopyWithImpl<$Res, _$DiaryModelImpl> implements _$$DiaryModelImplCopyWith<$Res> { + __$$DiaryModelImplCopyWithImpl(_$DiaryModelImpl _value, $Res Function(_$DiaryModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -187,8 +162,7 @@ class _$DiaryModelImpl implements _DiaryModel { required final List meals}) : _meals = meals; - factory _$DiaryModelImpl.fromJson(Map json) => - _$$DiaryModelImplFromJson(json); + factory _$DiaryModelImpl.fromJson(Map json) => _$$DiaryModelImplFromJson(json); @override final int id; @@ -231,14 +205,12 @@ class _$DiaryModelImpl implements _DiaryModel { @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, date, wakeup, retire, closed, - comment, const DeepCollectionEquality().hash(_meals)); + int get hashCode => Object.hash(runtimeType, id, date, wakeup, retire, closed, comment, const DeepCollectionEquality().hash(_meals)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$DiaryModelImplCopyWith<_$DiaryModelImpl> get copyWith => - __$$DiaryModelImplCopyWithImpl<_$DiaryModelImpl>(this, _$identity); + _$$DiaryModelImplCopyWith<_$DiaryModelImpl> get copyWith => __$$DiaryModelImplCopyWithImpl<_$DiaryModelImpl>(this, _$identity); @override Map toJson() { @@ -258,8 +230,7 @@ abstract class _DiaryModel implements DiaryModel { required final String comment, required final List meals}) = _$DiaryModelImpl; - factory _DiaryModel.fromJson(Map json) = - _$DiaryModelImpl.fromJson; + factory _DiaryModel.fromJson(Map json) = _$DiaryModelImpl.fromJson; @override int get id; @@ -277,6 +248,5 @@ abstract class _DiaryModel implements DiaryModel { List get meals; @override @JsonKey(ignore: true) - _$$DiaryModelImplCopyWith<_$DiaryModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$DiaryModelImplCopyWith<_$DiaryModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/diary/models/diary_model.g.dart b/lib/features/diary/models/diary_model.g.dart index cab25b6..79a0e92 100644 --- a/lib/features/diary/models/diary_model.g.dart +++ b/lib/features/diary/models/diary_model.g.dart @@ -6,21 +6,17 @@ part of 'diary_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$DiaryModelImpl _$$DiaryModelImplFromJson(Map json) => - _$DiaryModelImpl( +_$DiaryModelImpl _$$DiaryModelImplFromJson(Map json) => _$DiaryModelImpl( id: (json['id'] as num).toInt(), date: DateTime.parse(json['date'] as String), wakeup: DateTime.parse(json['wakeup'] as String), retire: DateTime.parse(json['retire'] as String), closed: (json['closed'] as num).toInt(), comment: json['comment'] as String, - meals: (json['meals'] as List) - .map((e) => Meals.fromJson(e as Map)) - .toList(), + meals: (json['meals'] as List).map((e) => Meals.fromJson(e as Map)).toList(), ); -Map _$$DiaryModelImplToJson(_$DiaryModelImpl instance) => - { +Map _$$DiaryModelImplToJson(_$DiaryModelImpl instance) => { 'id': instance.id, 'date': instance.date.toIso8601String(), 'wakeup': instance.wakeup.toIso8601String(), diff --git a/lib/features/diary/presentation/bloc/diary_cubit.dart b/lib/features/diary/presentation/bloc/diary_cubit.dart index 07477bd..ddc8676 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 d4305c8..90e9f4f 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 9cbf204..7218cf6 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 1ae40d8..b5ca031 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 6b6cb6b..0749037 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_model.freezed.dart b/lib/features/feed/models/feed_blog_post_model.freezed.dart index 4d753a1..9afd21e 100644 --- a/lib/features/feed/models/feed_blog_post_model.freezed.dart +++ b/lib/features/feed/models/feed_blog_post_model.freezed.dart @@ -34,15 +34,12 @@ mixin _$FeedBlogPostModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $FeedBlogPostModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $FeedBlogPostModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $FeedBlogPostModelCopyWith<$Res> { - factory $FeedBlogPostModelCopyWith( - FeedBlogPostModel value, $Res Function(FeedBlogPostModel) then) = - _$FeedBlogPostModelCopyWithImpl<$Res, FeedBlogPostModel>; + factory $FeedBlogPostModelCopyWith(FeedBlogPostModel value, $Res Function(FeedBlogPostModel) then) = _$FeedBlogPostModelCopyWithImpl<$Res, FeedBlogPostModel>; @useResult $Res call( {int id, @@ -56,8 +53,7 @@ abstract class $FeedBlogPostModelCopyWith<$Res> { } /// @nodoc -class _$FeedBlogPostModelCopyWithImpl<$Res, $Val extends FeedBlogPostModel> - implements $FeedBlogPostModelCopyWith<$Res> { +class _$FeedBlogPostModelCopyWithImpl<$Res, $Val extends FeedBlogPostModel> implements $FeedBlogPostModelCopyWith<$Res> { _$FeedBlogPostModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -115,10 +111,8 @@ class _$FeedBlogPostModelCopyWithImpl<$Res, $Val extends FeedBlogPostModel> } /// @nodoc -abstract class _$$FeedBlogPostModelImplCopyWith<$Res> - implements $FeedBlogPostModelCopyWith<$Res> { - factory _$$FeedBlogPostModelImplCopyWith(_$FeedBlogPostModelImpl value, - $Res Function(_$FeedBlogPostModelImpl) then) = +abstract class _$$FeedBlogPostModelImplCopyWith<$Res> implements $FeedBlogPostModelCopyWith<$Res> { + factory _$$FeedBlogPostModelImplCopyWith(_$FeedBlogPostModelImpl value, $Res Function(_$FeedBlogPostModelImpl) then) = __$$FeedBlogPostModelImplCopyWithImpl<$Res>; @override @useResult @@ -134,12 +128,9 @@ abstract class _$$FeedBlogPostModelImplCopyWith<$Res> } /// @nodoc -class __$$FeedBlogPostModelImplCopyWithImpl<$Res> - extends _$FeedBlogPostModelCopyWithImpl<$Res, _$FeedBlogPostModelImpl> +class __$$FeedBlogPostModelImplCopyWithImpl<$Res> extends _$FeedBlogPostModelCopyWithImpl<$Res, _$FeedBlogPostModelImpl> implements _$$FeedBlogPostModelImplCopyWith<$Res> { - __$$FeedBlogPostModelImplCopyWithImpl(_$FeedBlogPostModelImpl _value, - $Res Function(_$FeedBlogPostModelImpl) _then) - : super(_value, _then); + __$$FeedBlogPostModelImplCopyWithImpl(_$FeedBlogPostModelImpl _value, $Res Function(_$FeedBlogPostModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -203,8 +194,7 @@ class _$FeedBlogPostModelImpl implements _FeedBlogPostModel { @JsonKey(name: "updated_at") required this.updatedAt, required this.title}); - factory _$FeedBlogPostModelImpl.fromJson(Map json) => - _$$FeedBlogPostModelImplFromJson(json); + factory _$FeedBlogPostModelImpl.fromJson(Map json) => _$$FeedBlogPostModelImplFromJson(json); @override final int id; @@ -239,28 +229,21 @@ class _$FeedBlogPostModelImpl implements _FeedBlogPostModel { (identical(other.id, id) || other.id == id) && (identical(other.state, state) || other.state == state) && (identical(other.image, image) || other.image == image) && - (identical(other.description, description) || - other.description == description) && - (identical(other.youtubeUrl, youtubeUrl) || - other.youtubeUrl == youtubeUrl) && - (identical(other.createdAt, createdAt) || - other.createdAt == createdAt) && - (identical(other.updatedAt, updatedAt) || - other.updatedAt == updatedAt) && + (identical(other.description, description) || other.description == description) && + (identical(other.youtubeUrl, youtubeUrl) || other.youtubeUrl == youtubeUrl) && + (identical(other.createdAt, createdAt) || other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt) && (identical(other.title, title) || other.title == title)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, state, image, description, - youtubeUrl, createdAt, updatedAt, title); + int get hashCode => Object.hash(runtimeType, id, state, image, description, youtubeUrl, createdAt, updatedAt, title); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => - __$$FeedBlogPostModelImplCopyWithImpl<_$FeedBlogPostModelImpl>( - this, _$identity); + _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => __$$FeedBlogPostModelImplCopyWithImpl<_$FeedBlogPostModelImpl>(this, _$identity); @override Map toJson() { @@ -281,8 +264,7 @@ abstract class _FeedBlogPostModel implements FeedBlogPostModel { @JsonKey(name: "updated_at") required final DateTime updatedAt, required final String title}) = _$FeedBlogPostModelImpl; - factory _FeedBlogPostModel.fromJson(Map json) = - _$FeedBlogPostModelImpl.fromJson; + factory _FeedBlogPostModel.fromJson(Map json) = _$FeedBlogPostModelImpl.fromJson; @override int get id; @@ -305,6 +287,5 @@ abstract class _FeedBlogPostModel implements FeedBlogPostModel { String get title; @override @JsonKey(ignore: true) - _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/feed/models/feed_blog_post_model.g.dart b/lib/features/feed/models/feed_blog_post_model.g.dart index 93cc70f..e680864 100644 --- a/lib/features/feed/models/feed_blog_post_model.g.dart +++ b/lib/features/feed/models/feed_blog_post_model.g.dart @@ -6,9 +6,7 @@ part of 'feed_blog_post_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$FeedBlogPostModelImpl _$$FeedBlogPostModelImplFromJson( - Map json) => - _$FeedBlogPostModelImpl( +_$FeedBlogPostModelImpl _$$FeedBlogPostModelImplFromJson(Map json) => _$FeedBlogPostModelImpl( id: (json['id'] as num).toInt(), state: json['state'] as String, image: json['image'] as String, @@ -19,9 +17,7 @@ _$FeedBlogPostModelImpl _$$FeedBlogPostModelImplFromJson( title: json['title'] as String, ); -Map _$$FeedBlogPostModelImplToJson( - _$FeedBlogPostModelImpl instance) => - { +Map _$$FeedBlogPostModelImplToJson(_$FeedBlogPostModelImpl instance) => { 'id': instance.id, 'state': instance.state, 'image': instance.image, diff --git a/lib/features/feed/models/feed_blog_post_settings_model.dart b/lib/features/feed/models/feed_blog_post_settings_model.dart index fa72e97..8296a8b 100644 --- a/lib/features/feed/models/feed_blog_post_settings_model.dart +++ b/lib/features/feed/models/feed_blog_post_settings_model.dart @@ -7,8 +7,7 @@ part 'feed_blog_post_settings_model.g.dart'; @freezed class FeedBlogPostSettingsModel with _$FeedBlogPostSettingsModel { const factory FeedBlogPostSettingsModel({ - @JsonKey(name: 'data') - required List feedBlogPostList, + @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 index 7fd8a12..cab47d2 100644 --- a/lib/features/feed/models/feed_blog_post_settings_model.freezed.dart +++ b/lib/features/feed/models/feed_blog_post_settings_model.freezed.dart @@ -14,36 +14,30 @@ 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) { +FeedBlogPostSettingsModel _$FeedBlogPostSettingsModelFromJson(Map json) { return _FeedBlogPostSettingsModel.fromJson(json); } /// @nodoc mixin _$FeedBlogPostSettingsModel { @JsonKey(name: 'data') - List get feedBlogPostList => - throw _privateConstructorUsedError; + List get feedBlogPostList => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $FeedBlogPostSettingsModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $FeedBlogPostSettingsModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $FeedBlogPostSettingsModelCopyWith<$Res> { - factory $FeedBlogPostSettingsModelCopyWith(FeedBlogPostSettingsModel value, - $Res Function(FeedBlogPostSettingsModel) then) = + 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> { +class _$FeedBlogPostSettingsModelCopyWithImpl<$Res, $Val extends FeedBlogPostSettingsModel> implements $FeedBlogPostSettingsModelCopyWith<$Res> { _$FeedBlogPostSettingsModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -66,11 +60,8 @@ class _$FeedBlogPostSettingsModelCopyWithImpl<$Res, } /// @nodoc -abstract class _$$FeedBlogPostSettingsModelImplCopyWith<$Res> - implements $FeedBlogPostSettingsModelCopyWith<$Res> { - factory _$$FeedBlogPostSettingsModelImplCopyWith( - _$FeedBlogPostSettingsModelImpl value, - $Res Function(_$FeedBlogPostSettingsModelImpl) then) = +abstract class _$$FeedBlogPostSettingsModelImplCopyWith<$Res> implements $FeedBlogPostSettingsModelCopyWith<$Res> { + factory _$$FeedBlogPostSettingsModelImplCopyWith(_$FeedBlogPostSettingsModelImpl value, $Res Function(_$FeedBlogPostSettingsModelImpl) then) = __$$FeedBlogPostSettingsModelImplCopyWithImpl<$Res>; @override @useResult @@ -78,13 +69,9 @@ abstract class _$$FeedBlogPostSettingsModelImplCopyWith<$Res> } /// @nodoc -class __$$FeedBlogPostSettingsModelImplCopyWithImpl<$Res> - extends _$FeedBlogPostSettingsModelCopyWithImpl<$Res, - _$FeedBlogPostSettingsModelImpl> +class __$$FeedBlogPostSettingsModelImplCopyWithImpl<$Res> extends _$FeedBlogPostSettingsModelCopyWithImpl<$Res, _$FeedBlogPostSettingsModelImpl> implements _$$FeedBlogPostSettingsModelImplCopyWith<$Res> { - __$$FeedBlogPostSettingsModelImplCopyWithImpl( - _$FeedBlogPostSettingsModelImpl _value, - $Res Function(_$FeedBlogPostSettingsModelImpl) _then) + __$$FeedBlogPostSettingsModelImplCopyWithImpl(_$FeedBlogPostSettingsModelImpl _value, $Res Function(_$FeedBlogPostSettingsModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -104,20 +91,16 @@ class __$$FeedBlogPostSettingsModelImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() class _$FeedBlogPostSettingsModelImpl implements _FeedBlogPostSettingsModel { - const _$FeedBlogPostSettingsModelImpl( - {@JsonKey(name: 'data') - required final List feedBlogPostList}) + const _$FeedBlogPostSettingsModelImpl({@JsonKey(name: 'data') required final List feedBlogPostList}) : _feedBlogPostList = feedBlogPostList; - factory _$FeedBlogPostSettingsModelImpl.fromJson(Map json) => - _$$FeedBlogPostSettingsModelImplFromJson(json); + factory _$FeedBlogPostSettingsModelImpl.fromJson(Map json) => _$$FeedBlogPostSettingsModelImplFromJson(json); final List _feedBlogPostList; @override @JsonKey(name: 'data') List get feedBlogPostList { - if (_feedBlogPostList is EqualUnmodifiableListView) - return _feedBlogPostList; + if (_feedBlogPostList is EqualUnmodifiableListView) return _feedBlogPostList; // ignore: implicit_dynamic_type return EqualUnmodifiableListView(_feedBlogPostList); } @@ -132,21 +115,18 @@ class _$FeedBlogPostSettingsModelImpl implements _FeedBlogPostSettingsModel { return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedBlogPostSettingsModelImpl && - const DeepCollectionEquality() - .equals(other._feedBlogPostList, _feedBlogPostList)); + const DeepCollectionEquality().equals(other._feedBlogPostList, _feedBlogPostList)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash( - runtimeType, const DeepCollectionEquality().hash(_feedBlogPostList)); + 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); + _$$FeedBlogPostSettingsModelImplCopyWith<_$FeedBlogPostSettingsModelImpl> get copyWith => + __$$FeedBlogPostSettingsModelImplCopyWithImpl<_$FeedBlogPostSettingsModelImpl>(this, _$identity); @override Map toJson() { @@ -157,19 +137,14 @@ class _$FeedBlogPostSettingsModelImpl implements _FeedBlogPostSettingsModel { } abstract class _FeedBlogPostSettingsModel implements FeedBlogPostSettingsModel { - const factory _FeedBlogPostSettingsModel( - {@JsonKey(name: 'data') - required final List feedBlogPostList}) = - _$FeedBlogPostSettingsModelImpl; + const factory _FeedBlogPostSettingsModel({@JsonKey(name: 'data') required final List feedBlogPostList}) = _$FeedBlogPostSettingsModelImpl; - factory _FeedBlogPostSettingsModel.fromJson(Map json) = - _$FeedBlogPostSettingsModelImpl.fromJson; + factory _FeedBlogPostSettingsModel.fromJson(Map json) = _$FeedBlogPostSettingsModelImpl.fromJson; @override @JsonKey(name: 'data') List get feedBlogPostList; @override @JsonKey(ignore: true) - _$$FeedBlogPostSettingsModelImplCopyWith<_$FeedBlogPostSettingsModelImpl> - get copyWith => throw _privateConstructorUsedError; + _$$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 index 3f48be1..c960067 100644 --- a/lib/features/feed/models/feed_blog_post_settings_model.g.dart +++ b/lib/features/feed/models/feed_blog_post_settings_model.g.dart @@ -6,16 +6,10 @@ 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(), +_$FeedBlogPostSettingsModelImpl _$$FeedBlogPostSettingsModelImplFromJson(Map json) => _$FeedBlogPostSettingsModelImpl( + feedBlogPostList: (json['data'] as List).map((e) => FeedBlogPostModel.fromJson(e as Map)).toList(), ); -Map _$$FeedBlogPostSettingsModelImplToJson( - _$FeedBlogPostSettingsModelImpl instance) => - { +Map _$$FeedBlogPostSettingsModelImplToJson(_$FeedBlogPostSettingsModelImpl instance) => { 'data': instance.feedBlogPostList, }; diff --git a/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart b/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart index ab3385f..f3b70a9 100644 --- a/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart +++ b/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart @@ -70,13 +70,11 @@ mixin _$FeedState { /// @nodoc abstract class $FeedStateCopyWith<$Res> { - factory $FeedStateCopyWith(FeedState value, $Res Function(FeedState) then) = - _$FeedStateCopyWithImpl<$Res, FeedState>; + factory $FeedStateCopyWith(FeedState value, $Res Function(FeedState) then) = _$FeedStateCopyWithImpl<$Res, FeedState>; } /// @nodoc -class _$FeedStateCopyWithImpl<$Res, $Val extends FeedState> - implements $FeedStateCopyWith<$Res> { +class _$FeedStateCopyWithImpl<$Res, $Val extends FeedState> implements $FeedStateCopyWith<$Res> { _$FeedStateCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -87,18 +85,12 @@ class _$FeedStateCopyWithImpl<$Res, $Val extends FeedState> /// @nodoc abstract class _$$FeedStateImplCopyWith<$Res> { - factory _$$FeedStateImplCopyWith( - _$FeedStateImpl value, $Res Function(_$FeedStateImpl) then) = - __$$FeedStateImplCopyWithImpl<$Res>; + factory _$$FeedStateImplCopyWith(_$FeedStateImpl value, $Res Function(_$FeedStateImpl) then) = __$$FeedStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$FeedStateImplCopyWithImpl<$Res> - extends _$FeedStateCopyWithImpl<$Res, _$FeedStateImpl> - implements _$$FeedStateImplCopyWith<$Res> { - __$$FeedStateImplCopyWithImpl( - _$FeedStateImpl _value, $Res Function(_$FeedStateImpl) _then) - : super(_value, _then); +class __$$FeedStateImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateImpl> implements _$$FeedStateImplCopyWith<$Res> { + __$$FeedStateImplCopyWithImpl(_$FeedStateImpl _value, $Res Function(_$FeedStateImpl) _then) : super(_value, _then); } /// @nodoc @@ -113,8 +105,7 @@ class _$FeedStateImpl implements _FeedState { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is _$FeedStateImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateImpl); } @override @@ -201,18 +192,14 @@ abstract class _FeedState implements FeedState { /// @nodoc abstract class _$$FeedStateLoadingImplCopyWith<$Res> { - factory _$$FeedStateLoadingImplCopyWith(_$FeedStateLoadingImpl value, - $Res Function(_$FeedStateLoadingImpl) then) = + factory _$$FeedStateLoadingImplCopyWith(_$FeedStateLoadingImpl value, $Res Function(_$FeedStateLoadingImpl) then) = __$$FeedStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$FeedStateLoadingImplCopyWithImpl<$Res> - extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadingImpl> +class __$$FeedStateLoadingImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadingImpl> implements _$$FeedStateLoadingImplCopyWith<$Res> { - __$$FeedStateLoadingImplCopyWithImpl(_$FeedStateLoadingImpl _value, - $Res Function(_$FeedStateLoadingImpl) _then) - : super(_value, _then); + __$$FeedStateLoadingImplCopyWithImpl(_$FeedStateLoadingImpl _value, $Res Function(_$FeedStateLoadingImpl) _then) : super(_value, _then); } /// @nodoc @@ -227,8 +214,7 @@ class _$FeedStateLoadingImpl implements FeedStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is _$FeedStateLoadingImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateLoadingImpl); } @override @@ -315,20 +301,14 @@ abstract class FeedStateLoading implements FeedState { /// @nodoc abstract class _$$FeedStateLoadedImplCopyWith<$Res> { - factory _$$FeedStateLoadedImplCopyWith(_$FeedStateLoadedImpl value, - $Res Function(_$FeedStateLoadedImpl) then) = - __$$FeedStateLoadedImplCopyWithImpl<$Res>; + factory _$$FeedStateLoadedImplCopyWith(_$FeedStateLoadedImpl value, $Res Function(_$FeedStateLoadedImpl) then) = __$$FeedStateLoadedImplCopyWithImpl<$Res>; @useResult $Res call({List feedBlogPostList}); } /// @nodoc -class __$$FeedStateLoadedImplCopyWithImpl<$Res> - extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadedImpl> - implements _$$FeedStateLoadedImplCopyWith<$Res> { - __$$FeedStateLoadedImplCopyWithImpl( - _$FeedStateLoadedImpl _value, $Res Function(_$FeedStateLoadedImpl) _then) - : super(_value, _then); +class __$$FeedStateLoadedImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadedImpl> implements _$$FeedStateLoadedImplCopyWith<$Res> { + __$$FeedStateLoadedImplCopyWithImpl(_$FeedStateLoadedImpl _value, $Res Function(_$FeedStateLoadedImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -347,15 +327,12 @@ class __$$FeedStateLoadedImplCopyWithImpl<$Res> /// @nodoc class _$FeedStateLoadedImpl implements FeedStateLoaded { - const _$FeedStateLoadedImpl( - {required final List feedBlogPostList}) - : _feedBlogPostList = feedBlogPostList; + const _$FeedStateLoadedImpl({required final List feedBlogPostList}) : _feedBlogPostList = feedBlogPostList; final List _feedBlogPostList; @override List get feedBlogPostList { - if (_feedBlogPostList is EqualUnmodifiableListView) - return _feedBlogPostList; + if (_feedBlogPostList is EqualUnmodifiableListView) return _feedBlogPostList; // ignore: implicit_dynamic_type return EqualUnmodifiableListView(_feedBlogPostList); } @@ -370,20 +347,16 @@ class _$FeedStateLoadedImpl implements FeedStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateLoadedImpl && - const DeepCollectionEquality() - .equals(other._feedBlogPostList, _feedBlogPostList)); + const DeepCollectionEquality().equals(other._feedBlogPostList, _feedBlogPostList)); } @override - int get hashCode => Object.hash( - runtimeType, const DeepCollectionEquality().hash(_feedBlogPostList)); + int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_feedBlogPostList)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => - __$$FeedStateLoadedImplCopyWithImpl<_$FeedStateLoadedImpl>( - this, _$identity); + _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => __$$FeedStateLoadedImplCopyWithImpl<_$FeedStateLoadedImpl>(this, _$identity); @override @optionalTypeArgs @@ -461,32 +434,23 @@ class _$FeedStateLoadedImpl implements FeedStateLoaded { } abstract class FeedStateLoaded implements FeedState { - const factory FeedStateLoaded( - {required final List feedBlogPostList}) = - _$FeedStateLoadedImpl; + const factory FeedStateLoaded({required final List feedBlogPostList}) = _$FeedStateLoadedImpl; List get feedBlogPostList; @JsonKey(ignore: true) - _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => - throw _privateConstructorUsedError; + _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$FeedStateErrorImplCopyWith<$Res> { - factory _$$FeedStateErrorImplCopyWith(_$FeedStateErrorImpl value, - $Res Function(_$FeedStateErrorImpl) then) = - __$$FeedStateErrorImplCopyWithImpl<$Res>; + factory _$$FeedStateErrorImplCopyWith(_$FeedStateErrorImpl value, $Res Function(_$FeedStateErrorImpl) then) = __$$FeedStateErrorImplCopyWithImpl<$Res>; @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$FeedStateErrorImplCopyWithImpl<$Res> - extends _$FeedStateCopyWithImpl<$Res, _$FeedStateErrorImpl> - implements _$$FeedStateErrorImplCopyWith<$Res> { - __$$FeedStateErrorImplCopyWithImpl( - _$FeedStateErrorImpl _value, $Res Function(_$FeedStateErrorImpl) _then) - : super(_value, _then); +class __$$FeedStateErrorImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateErrorImpl> implements _$$FeedStateErrorImplCopyWith<$Res> { + __$$FeedStateErrorImplCopyWithImpl(_$FeedStateErrorImpl _value, $Res Function(_$FeedStateErrorImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -520,8 +484,7 @@ class _$FeedStateErrorImpl implements FeedStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateErrorImpl && - (identical(other.errorMessage, errorMessage) || - other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); } @override @@ -530,9 +493,7 @@ class _$FeedStateErrorImpl implements FeedStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => - __$$FeedStateErrorImplCopyWithImpl<_$FeedStateErrorImpl>( - this, _$identity); + _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => __$$FeedStateErrorImplCopyWithImpl<_$FeedStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -610,11 +571,9 @@ class _$FeedStateErrorImpl implements FeedStateError { } abstract class FeedStateError implements FeedState { - const factory FeedStateError({required final String errorMessage}) = - _$FeedStateErrorImpl; + const factory FeedStateError({required final String errorMessage}) = _$FeedStateErrorImpl; String get errorMessage; @JsonKey(ignore: true) - _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => - throw _privateConstructorUsedError; + _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/feed/presentation/pages/feed_screen.dart b/lib/features/feed/presentation/pages/feed_screen.dart index 797bfbb..e97b39e 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/services/feed_service.dart b/lib/features/feed/services/feed_service.dart index a961037..d96ba1c 100644 --- a/lib/features/feed/services/feed_service.dart +++ b/lib/features/feed/services/feed_service.dart @@ -8,6 +8,6 @@ part 'feed_service.g.dart'; abstract class FeedService { factory FeedService(Dio dio, {String baseUrl}) = _FeedService; - @GET('/blogPosts/index') + @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 2ef8381..0e66eb4 100644 --- a/lib/features/feed/services/feed_service.g.dart +++ b/lib/features/feed/services/feed_service.g.dart @@ -24,31 +24,28 @@ class _FeedService implements FeedService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>( - _setStreamType(Options( + final _result = await _dio.fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/blogPosts/index', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/blogPosts/index', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = FeedBlogPostSettingsModel.fromJson(_result.data!); return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && - !(requestOptions.responseType == ResponseType.bytes || - requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { diff --git a/lib/features/registration/consts/cities_list.dart b/lib/features/registration/consts/cities_list.dart index 728024d..0eea40d 100644 --- a/lib/features/registration/consts/cities_list.dart +++ b/lib/features/registration/consts/cities_list.dart @@ -1116,4 +1116,4 @@ const List citiesList = const [ "Ясногорск", "Ясный", "Яхрома", -]; \ No newline at end of file +]; 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 index dcb4923..70a7f33 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_state.freezed.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_state.freezed.dart @@ -19,15 +19,12 @@ mixin _$RegistrationState { UserRegistrationSheet get sheet => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $RegistrationStateCopyWith get copyWith => - throw _privateConstructorUsedError; + $RegistrationStateCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $RegistrationStateCopyWith<$Res> { - factory $RegistrationStateCopyWith( - RegistrationState value, $Res Function(RegistrationState) then) = - _$RegistrationStateCopyWithImpl<$Res, RegistrationState>; + factory $RegistrationStateCopyWith(RegistrationState value, $Res Function(RegistrationState) then) = _$RegistrationStateCopyWithImpl<$Res, RegistrationState>; @useResult $Res call({UserRegistrationSheet sheet}); @@ -35,8 +32,7 @@ abstract class $RegistrationStateCopyWith<$Res> { } /// @nodoc -class _$RegistrationStateCopyWithImpl<$Res, $Val extends RegistrationState> - implements $RegistrationStateCopyWith<$Res> { +class _$RegistrationStateCopyWithImpl<$Res, $Val extends RegistrationState> implements $RegistrationStateCopyWith<$Res> { _$RegistrationStateCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -67,10 +63,8 @@ class _$RegistrationStateCopyWithImpl<$Res, $Val extends RegistrationState> } /// @nodoc -abstract class _$$RegistrationStateImplCopyWith<$Res> - implements $RegistrationStateCopyWith<$Res> { - factory _$$RegistrationStateImplCopyWith(_$RegistrationStateImpl value, - $Res Function(_$RegistrationStateImpl) then) = +abstract class _$$RegistrationStateImplCopyWith<$Res> implements $RegistrationStateCopyWith<$Res> { + factory _$$RegistrationStateImplCopyWith(_$RegistrationStateImpl value, $Res Function(_$RegistrationStateImpl) then) = __$$RegistrationStateImplCopyWithImpl<$Res>; @override @useResult @@ -81,12 +75,9 @@ abstract class _$$RegistrationStateImplCopyWith<$Res> } /// @nodoc -class __$$RegistrationStateImplCopyWithImpl<$Res> - extends _$RegistrationStateCopyWithImpl<$Res, _$RegistrationStateImpl> +class __$$RegistrationStateImplCopyWithImpl<$Res> extends _$RegistrationStateCopyWithImpl<$Res, _$RegistrationStateImpl> implements _$$RegistrationStateImplCopyWith<$Res> { - __$$RegistrationStateImplCopyWithImpl(_$RegistrationStateImpl _value, - $Res Function(_$RegistrationStateImpl) _then) - : super(_value, _then); + __$$RegistrationStateImplCopyWithImpl(_$RegistrationStateImpl _value, $Res Function(_$RegistrationStateImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -118,9 +109,7 @@ class _$RegistrationStateImpl implements _RegistrationState { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$RegistrationStateImpl && - (identical(other.sheet, sheet) || other.sheet == sheet)); + (other.runtimeType == runtimeType && other is _$RegistrationStateImpl && (identical(other.sheet, sheet) || other.sheet == sheet)); } @override @@ -129,19 +118,15 @@ class _$RegistrationStateImpl implements _RegistrationState { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => - __$$RegistrationStateImplCopyWithImpl<_$RegistrationStateImpl>( - this, _$identity); + _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => __$$RegistrationStateImplCopyWithImpl<_$RegistrationStateImpl>(this, _$identity); } abstract class _RegistrationState implements RegistrationState { - const factory _RegistrationState( - {required final UserRegistrationSheet sheet}) = _$RegistrationStateImpl; + const factory _RegistrationState({required final UserRegistrationSheet sheet}) = _$RegistrationStateImpl; @override UserRegistrationSheet get sheet; @override @JsonKey(ignore: true) - _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => - throw _privateConstructorUsedError; + _$$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 index ec4578c..b1838fd 100644 --- a/lib/features/registration/presentation/pages/additional_information_screen.dart +++ b/lib/features/registration/presentation/pages/additional_information_screen.dart @@ -1,7 +1,7 @@ -import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.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 { diff --git a/lib/features/registration/presentation/pages/blood_pressure_screen.dart b/lib/features/registration/presentation/pages/blood_pressure_screen.dart index c423666..ef69278 100644 --- a/lib/features/registration/presentation/pages/blood_pressure_screen.dart +++ b/lib/features/registration/presentation/pages/blood_pressure_screen.dart @@ -1,10 +1,10 @@ -import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; -import 'package:flutter/services.dart'; 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:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; class BloodPressureScreen extends StatefulWidget { final UserRegistrationSheet sheet; diff --git a/lib/features/registration/presentation/pages/body_circumferences_screen.dart b/lib/features/registration/presentation/pages/body_circumferences_screen.dart index 06417c8..c537084 100644 --- a/lib/features/registration/presentation/pages/body_circumferences_screen.dart +++ b/lib/features/registration/presentation/pages/body_circumferences_screen.dart @@ -1,10 +1,9 @@ -import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; - -import 'package:flutter/services.dart'; 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; diff --git a/lib/features/registration/presentation/pages/city_of_living_screen.dart b/lib/features/registration/presentation/pages/city_of_living_screen.dart index b183ec9..0372d8b 100644 --- a/lib/features/registration/presentation/pages/city_of_living_screen.dart +++ b/lib/features/registration/presentation/pages/city_of_living_screen.dart @@ -1,8 +1,8 @@ +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/core/app_export.dart'; import 'package:eatvio_app/widgets/custom_drop_down.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; import 'package:flutter/material.dart'; import 'package:flutter_typeahead/flutter_typeahead.dart'; diff --git a/lib/features/registration/presentation/pages/credentials_screen.dart b/lib/features/registration/presentation/pages/credentials_screen.dart index ec7809c..3175b5c 100644 --- a/lib/features/registration/presentation/pages/credentials_screen.dart +++ b/lib/features/registration/presentation/pages/credentials_screen.dart @@ -1,6 +1,6 @@ +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/core/app_export.dart'; import 'package:eatvio_app/widgets/custom_text_form_field.dart'; import 'package:flutter/material.dart'; diff --git a/lib/features/registration/presentation/pages/date_of_birth_screen.dart b/lib/features/registration/presentation/pages/date_of_birth_screen.dart index 49118ca..54e1935 100644 --- a/lib/features/registration/presentation/pages/date_of_birth_screen.dart +++ b/lib/features/registration/presentation/pages/date_of_birth_screen.dart @@ -1,7 +1,7 @@ -import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; -import 'package:flutter/cupertino.dart'; 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 { @@ -92,26 +92,22 @@ class _DateOfBirthScreenState extends State { 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, - ), - ), + 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 index b26f0c2..d17b5e1 100644 --- a/lib/features/registration/presentation/pages/favorite_foods_screen.dart +++ b/lib/features/registration/presentation/pages/favorite_foods_screen.dart @@ -1,6 +1,6 @@ -import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; 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'; diff --git a/lib/features/registration/presentation/pages/favorite_sports_screen.dart b/lib/features/registration/presentation/pages/favorite_sports_screen.dart index 86c7d24..55273ec 100644 --- a/lib/features/registration/presentation/pages/favorite_sports_screen.dart +++ b/lib/features/registration/presentation/pages/favorite_sports_screen.dart @@ -1,6 +1,6 @@ -import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; 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'; @@ -38,7 +38,8 @@ class _FavoriteSportsScreenState extends State { SizedBox(height: 2.v), CustomTextFormField( controller: enterInformationController, - hintText: "Я занимаюсь плаванием , почти каждый вечер прогулки на свежем воздухе, пару раз в месяц играю в волейбол. Стараюсь не сидеть на месте!", + hintText: + "Я занимаюсь плаванием , почти каждый вечер прогулки на свежем воздухе, пару раз в месяц играю в волейбол. Стараюсь не сидеть на месте!", textInputAction: TextInputAction.done, maxLines: 8, onChanged: (newValue) { diff --git a/lib/features/registration/presentation/pages/gender_screen.dart b/lib/features/registration/presentation/pages/gender_screen.dart index 803759d..6225826 100644 --- a/lib/features/registration/presentation/pages/gender_screen.dart +++ b/lib/features/registration/presentation/pages/gender_screen.dart @@ -1,6 +1,6 @@ -import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; -import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; 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 { diff --git a/lib/features/registration/presentation/pages/height_screen.dart b/lib/features/registration/presentation/pages/height_screen.dart index a2f47e0..98fc71f 100644 --- a/lib/features/registration/presentation/pages/height_screen.dart +++ b/lib/features/registration/presentation/pages/height_screen.dart @@ -1,9 +1,9 @@ -import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:flutter/services.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; diff --git a/lib/features/registration/presentation/pages/medicine_intake_screen.dart b/lib/features/registration/presentation/pages/medicine_intake_screen.dart index 1e6f4ff..d6ea9fb 100644 --- a/lib/features/registration/presentation/pages/medicine_intake_screen.dart +++ b/lib/features/registration/presentation/pages/medicine_intake_screen.dart @@ -1,7 +1,7 @@ -import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.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 { diff --git a/lib/features/registration/presentation/pages/name_screen.dart b/lib/features/registration/presentation/pages/name_screen.dart index dfd9a16..2f1e4c5 100644 --- a/lib/features/registration/presentation/pages/name_screen.dart +++ b/lib/features/registration/presentation/pages/name_screen.dart @@ -1,6 +1,6 @@ +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/core/app_export.dart'; import 'package:eatvio_app/widgets/custom_text_form_field.dart'; import 'package:flutter/material.dart'; diff --git a/lib/features/registration/presentation/pages/registration_screen.dart b/lib/features/registration/presentation/pages/registration_screen.dart index 30eb759..eae9818 100644 --- a/lib/features/registration/presentation/pages/registration_screen.dart +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -1,22 +1,22 @@ 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/allergies_screen.dart'; -import 'package:eatvio_app/features/registration/presentation/pages/city_of_living_screen.dart'; -import 'package:eatvio_app/features/registration/presentation/pages/favorite_foods_screen.dart'; -import 'package:eatvio_app/features/registration/presentation/pages/height_screen.dart'; -import 'package:eatvio_app/features/registration/presentation/pages/name_screen.dart'; -import 'package:eatvio_app/locator_service.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'; diff --git a/lib/features/registration/presentation/pages/weight_screen.dart b/lib/features/registration/presentation/pages/weight_screen.dart index 6c64ad1..855593e 100644 --- a/lib/features/registration/presentation/pages/weight_screen.dart +++ b/lib/features/registration/presentation/pages/weight_screen.dart @@ -1,9 +1,9 @@ -import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart'; import 'package:eatvio_app/core/app_export.dart'; -import 'package:eatvio_app/widgets/custom_text_form_field.dart'; -import 'package:flutter/services.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; diff --git a/lib/features/registration/services/registration_service.dart b/lib/features/registration/services/registration_service.dart index 9ff8108..00ae673 100644 --- a/lib/features/registration/services/registration_service.dart +++ b/lib/features/registration/services/registration_service.dart @@ -7,7 +7,7 @@ part 'registration_service.g.dart'; abstract class RegistrationService { factory RegistrationService(Dio dio, {String baseUrl}) = _RegistrationService; - @POST('/register') + @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 index 0a7fc8f..1268b0b 100644 --- a/lib/features/registration/services/registration_service.g.dart +++ b/lib/features/registration/services/registration_service.g.dart @@ -32,7 +32,7 @@ class _RegistrationService implements RegistrationService { ) .compose( _dio.options, - '/register', + '/api/register', queryParameters: queryParameters, data: _data, ) @@ -44,9 +44,7 @@ class _RegistrationService implements RegistrationService { } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && - !(requestOptions.responseType == ResponseType.bytes || - requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { diff --git a/lib/localization/app_localization.dart b/lib/localization/app_localization.dart index 5d003fc..0c0b256 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 282c4c7..4c0df24 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 3d28a23..8d7f708 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 dc09164..1d95a0b 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'; @@ -14,7 +15,6 @@ import 'package:eatvio_app/features/feed/services/feed_service.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:flutter_dotenv/flutter_dotenv.dart'; import 'package:get_it/get_it.dart'; final sl = GetIt.instance; @@ -46,7 +46,7 @@ Future init() async { sl.registerLazySingleton( () => Dio( BaseOptions( - baseUrl: dotenv.env['SERVER_ROOT']!, + baseUrl: baseUrl, ), ), ); diff --git a/lib/main.dart b/lib/main.dart index 7faced2..ab53cca 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, diff --git a/lib/presentation/auth/auth_screen/auth_screen.dart b/lib/presentation/auth/auth_screen/auth_screen.dart index ad32b70..ec01a98 100644 --- a/lib/presentation/auth/auth_screen/auth_screen.dart +++ b/lib/presentation/auth/auth_screen/auth_screen.dart @@ -1,22 +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:url_launcher/url_launcher.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( @@ -30,6 +29,13 @@ class AuthScreen extends StatelessWidget { ); } + @override + State createState() => _AuthScreenState(); +} + +class _AuthScreenState extends State { + bool checkboxState = false; + @override Widget build(BuildContext context) { mediaQueryData = MediaQuery.of(context); @@ -95,12 +101,6 @@ class AuthScreen extends StatelessWidget { ); }, ), - TextButton( - onPressed: () async { - await launchUrl(Uri.parse(dotenv.env['OFERTA']!)); - }, - child: Text('Пользовательское соглашение'), - ), ], ), ), @@ -117,7 +117,7 @@ class AuthScreen extends StatelessWidget { 'password': state.passwordController!.text, }; final response = await http.post( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/login'), + Uri.parse(baseUrl + '/api/login'), headers: {'Content-Type': 'application/json'}, body: json.encode(credentials), encoding: utf8, diff --git a/lib/presentation/auth/auth_screen/bloc/auth_bloc.dart b/lib/presentation/auth/auth_screen/bloc/auth_bloc.dart index 6622981..0d8f67a 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 e93f295..1792f4d 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 c2c5dad..318a768 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 dfea7c2..e5f942f 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 6f68bc2..d37abbf 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 a28b79d..65ea65b 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 be825ab..6b42e38 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 619e8f7..2ade3f8 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 22cc1aa..81e034a 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 bfc5e24..ab0d2ee 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 aa7cf20..d76d79d 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 e12eab5..56dabcf 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 e7b709d..85b7d5a 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 4b026cb..3f4a8ce 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 5fcd3a1..3d0551a 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 49913f7..d587263 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 950e47a..9fae1ef 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 7ddbaca..624a1ef 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 4da3f5a..33dc59b 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 d403e45..13d4b86 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 5dec030..f4bfea0 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 46b21c4..b571cef 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 07dc31c..02e496f 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 cc2d5f3..d78db89 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 7012a55..ba69137 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 67cbe66..73e9c6a 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 feecc7c..2b9c713 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 ab177fa..ed2e075 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 2c40739..bc3b161 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 cef2304..bbfff40 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 f78c3ff..45b6bcd 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 a6f8cf5..42119a8 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 35caec2..e845318 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, - 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), + 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 2c40739..bc3b161 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 cef2304..bbfff40 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 fd30edd..3cab0f6 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 93e4aaf..4e98812 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 8126259..165be86 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 e150c8b..5987b6b 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 6676962..e3cf6b8 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 abea8b9..c700574 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 e65409f..dcf6070 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 5ab68c2..2c8561b 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 022e4e2..1508c75 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 e920db8..ad9a7a4 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 cefb6cf..5052710 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 98cefd4..bf61868 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 af1c558..8b01f61 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', }, @@ -278,7 +278,7 @@ class MyProfileBloc extends Bloc { } 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 7c66b4c..85c254d 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 9aeb496..3aa1f64 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) { @@ -156,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, @@ -720,7 +720,7 @@ class MyProfileScreen extends StatelessWidget { child: Container( margin: EdgeInsets.only(bottom: 12.h), child: Image.network( - dotenv.env['STORAGE_URL']! + imagePaths?[i], + baseUrl + '/storage/' + imagePaths?[i], height: 25.adaptSize, width: 25.adaptSize, ), @@ -849,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', @@ -941,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 cb3aeb6..4cd47b1 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 ebb0ec0..c0b0e2e 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 4865bf3..d58773a 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 5afb164..0f8f3f5 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 0fbc048..560c75e 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']! + '/recipes/show/$recipeID'), + Uri.parse(baseUrl + '/api/recipes/show/$recipeID'), headers: { 'Authorization': 'Bearer $token', }, @@ -166,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, @@ -200,7 +199,7 @@ class RecipeEditBloc extends Bloc { } final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipes/getTags/$id'), + Uri.parse(baseUrl + '/api/recipes/getTags/$id'), headers: { 'Authorization': 'Bearer $token', }, 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 e9086e6..57df9f2 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 6621fc8..e3dbcbe 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 08f57b4..399e20f 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 @@ -3,14 +3,14 @@ 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: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,7 +31,7 @@ class RecipeSelectBloc extends Bloc { if (token == null) { AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); } - final response = await sl().get(dotenv.env['SERVER_ROOT']! + '/recipes/index'); + final response = await sl().get(baseUrl + '/api/recipes/index'); print('Got response'); if (response.statusCode == 200) { print('Got 200'); 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 33b59af..29e47b3 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) { @@ -118,50 +118,51 @@ class RecipeSelectScreen 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?['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 e8ef6e3..ac2d9a9 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']! + '/recipes/show/$recipeID'), + Uri.parse(baseUrl + '/api/recipes/show/$recipeID'), headers: { 'Authorization': 'Bearer $token', }, @@ -93,7 +92,7 @@ class RecipeBloc extends Bloc { } final int id = event.id; final response = await http.post( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipes/delete/$id'), + Uri.parse(baseUrl + '/api/recipes/delete/$id'), headers: { 'Authorization': 'Bearer $token', }, @@ -131,7 +130,7 @@ class RecipeBloc extends Bloc { } final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipes/getAuthor/$id'), + Uri.parse(baseUrl + '/api/recipes/getAuthor/$id'), headers: { 'Authorization': 'Bearer $token', }, @@ -147,7 +146,7 @@ class RecipeBloc extends Bloc { AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); } final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipes/getComments/$id'), + Uri.parse(baseUrl + '/api/recipes/getComments/$id'), headers: { 'Authorization': 'Bearer $token', }, @@ -165,7 +164,7 @@ class RecipeBloc extends Bloc { } final response = await http.get( - Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipes/getTags/$id'), + Uri.parse(baseUrl + '/api/recipes/getTags/$id'), headers: { 'Authorization': 'Bearer $token', }, @@ -191,7 +190,7 @@ class RecipeBloc extends Bloc { } Future _sendCommentData(String? token, String body, int id) async { - String url = dotenv.env['SERVER_ROOT']! + '/recipes/createComment/$id'; + String url = baseUrl + '/api/recipes/createComment/$id'; final Map credentials = { 'id': id, 'body': body, 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 efc80d6..335ac20 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 30fd4e9..c42813d 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 ab177fa..ed2e075 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/users/subscribers_screen/bloc/subscribers_bloc.dart b/lib/presentation/users/subscribers_screen/bloc/subscribers_bloc.dart index 1bb1bcf..a48d619 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 151e062..f934270 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 f2ac7e1..01fb9a7 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 f304e54..9ba1b22 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 60f947d..ae2863b 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 de3bee7..1ed606c 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 f9f64aa..e202a86 100644 --- a/lib/theme/theme_helper.dart +++ b/lib/theme/theme_helper.dart @@ -1,6 +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. diff --git a/lib/widgets/chart_axis.dart b/lib/widgets/chart_axis.dart index 5cc6448..f137c6d 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 7f4fc34..eac9e99 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 4b4e709..90b1d3d 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_expandable_list.dart b/lib/widgets/custom_expandable_list.dart index 79d62d1..a98dd33 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 e25c462..edad8ec 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 173de64..2e0c511 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 2937b5a..d029004 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 03d11a9..5868bf0 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 9d7d161..44850fa 100644 --- a/lib/widgets/custom_navigation_menu_item.dart +++ b/lib/widgets/custom_navigation_menu_item.dart @@ -1,6 +1,6 @@ import 'package:eatvio_app/core/app_export.dart'; -import 'package:flutter/material.dart'; import 'package:eatvio_app/widgets/custom_image_view.dart'; +import 'package:flutter/material.dart'; class MenuItem extends StatelessWidget { final String icon; diff --git a/lib/widgets/custom_notification_screen.dart b/lib/widgets/custom_notification_screen.dart index 960293c..72fd860 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 3d061e9..862cc10 100644 --- a/lib/widgets/custom_text_form_field.dart +++ b/lib/widgets/custom_text_form_field.dart @@ -181,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 36031fc..2cdbe59 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 @@ -59,5 +58,4 @@ flutter: uses-material-design: true assets: - assets/ - - assets/images/ - - .env \ No newline at end of file + - assets/images/ \ No newline at end of file -- 2.49.1 From ae213f39a5d56c59f157bfee42e35f9b2586d69b Mon Sep 17 00:00:00 2001 From: maxxkim Date: Mon, 15 Jul 2024 17:10:55 +0300 Subject: [PATCH 063/110] fix(diary): Meal change method fix --- .../diary/presentation/bloc/diary_bloc.dart | 20 ++-- .../diary/presentation/bloc/diary_event.dart | 7 +- .../diary/presentation/bloc/diary_state.dart | 1 + .../bloc/diary_state.freezed.dart | 40 +++++++- .../presentation/pages/diary_screen.dart | 93 ++++++------------- 5 files changed, 83 insertions(+), 78 deletions(-) diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index 8cebe1a..c50210b 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -57,14 +57,23 @@ class DiaryBloc extends Bloc { final int? diaryID = data['id']; final DiaryModel diary = await diaryRepository.getDiary(diaryID ?? 45); final Meal currentMeal = diary.meals[0]; - List portions = [SelectionPopupModel(title: "gr"), SelectionPopupModel(title: "pcs")]; + List portionList = [SelectionPopupModel(title: "gr"), SelectionPopupModel(title: "pcs")]; + List mealList = [ + SelectionPopupModel(title: "Прием пищи 1", id: 1), + SelectionPopupModel(title: "Прием пищи 2", id: 2), + SelectionPopupModel(title: "Прием пищи 3", id: 3), + SelectionPopupModel(title: "Прием пищи 4", id: 4), + SelectionPopupModel(title: "Прием пищи 5", id: 5), + SelectionPopupModel(title: "Прием пищи 6", id: 6), + ]; emit(DiaryState.loaded( diary: diary, currentMeal: currentMeal, portions: currentMeal.portions, photos: currentMeal.photos, - portionList: portions, - portionController: portions[0], + portionList: portionList, + portionController: portionList[0], + mealList: mealList, selectedMood: currentMeal.mood, selectedSatiety: currentMeal.satiety, commentController: TextEditingController(), @@ -209,9 +218,8 @@ class DiaryBloc extends Bloc { Emitter emit, ) async { if (state is DiaryStateLoaded) { - var currentState = state as DiaryStateLoaded; - Meal? meal = currentState.diary.meals.firstWhere((meal) => meal.id == event.value.id); - + final currentState = state as DiaryStateLoaded; + final Meal meal = currentState.diary.meals.firstWhere((meal) => meal.type == event.value.id); DiaryStateLoaded updatedState = currentState.copyWith( currentMeal: meal, portions: meal.portions, diff --git a/lib/features/diary/presentation/bloc/diary_event.dart b/lib/features/diary/presentation/bloc/diary_event.dart index eb4742e..d663752 100644 --- a/lib/features/diary/presentation/bloc/diary_event.dart +++ b/lib/features/diary/presentation/bloc/diary_event.dart @@ -110,11 +110,10 @@ class ProductInput extends DiaryEvent { } class ChangeMeal extends DiaryEvent { - ChangeMeal({required this.value, required this.meals}); - Meal value; - List? meals; + ChangeMeal({required this.value}); + SelectionPopupModel value; @override - List get props => [value, meals]; + List get props => [value]; } class ClearInput extends DiaryEvent { diff --git a/lib/features/diary/presentation/bloc/diary_state.dart b/lib/features/diary/presentation/bloc/diary_state.dart index 957dafc..fa49016 100644 --- a/lib/features/diary/presentation/bloc/diary_state.dart +++ b/lib/features/diary/presentation/bloc/diary_state.dart @@ -23,6 +23,7 @@ abstract class DiaryState with _$DiaryState { required List consumedChartValues, required List portions, required List photos, + required List mealList, required List portionList, required Meal currentMeal, required SelectionPopupModel portionController, diff --git a/lib/features/diary/presentation/bloc/diary_state.freezed.dart b/lib/features/diary/presentation/bloc/diary_state.freezed.dart index 3293104..2ecc30d 100644 --- a/lib/features/diary/presentation/bloc/diary_state.freezed.dart +++ b/lib/features/diary/presentation/bloc/diary_state.freezed.dart @@ -28,6 +28,7 @@ mixin _$DiaryState { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, @@ -64,6 +65,7 @@ mixin _$DiaryState { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, @@ -100,6 +102,7 @@ mixin _$DiaryState { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, @@ -218,6 +221,7 @@ class _$DiaryStateImpl implements _DiaryState { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, @@ -257,6 +261,7 @@ class _$DiaryStateImpl implements _DiaryState { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, @@ -296,6 +301,7 @@ class _$DiaryStateImpl implements _DiaryState { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, @@ -416,6 +422,7 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, @@ -455,6 +462,7 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, @@ -494,6 +502,7 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, @@ -580,6 +589,7 @@ abstract class _$$DiaryStateLoadedImplCopyWith<$Res> { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, @@ -623,6 +633,7 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> Object? consumedChartValues = null, Object? portions = null, Object? photos = null, + Object? mealList = null, Object? portionList = null, Object? currentMeal = null, Object? portionController = null, @@ -673,6 +684,10 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> ? _value._photos : photos // ignore: cast_nullable_to_non_nullable as List, + mealList: null == mealList + ? _value._mealList + : mealList // ignore: cast_nullable_to_non_nullable + as List, portionList: null == portionList ? _value._portionList : portionList // ignore: cast_nullable_to_non_nullable @@ -784,6 +799,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { required final List consumedChartValues, required final List portions, required final List photos, + required final List mealList, required final List portionList, required this.currentMeal, required this.portionController, @@ -809,6 +825,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { _consumedChartValues = consumedChartValues, _portions = portions, _photos = photos, + _mealList = mealList, _portionList = portionList; @override @@ -858,6 +875,14 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { return EqualUnmodifiableListView(_photos); } + final List _mealList; + @override + List get mealList { + if (_mealList is EqualUnmodifiableListView) return _mealList; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_mealList); + } + final List _portionList; @override List get portionList { @@ -907,7 +932,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { @override String toString() { - return 'DiaryState.loaded(diary: $diary, diaryDate: $diaryDate, autocompleteList: $autocompleteList, recommendedChartValues: $recommendedChartValues, consumedChartValues: $consumedChartValues, portions: $portions, photos: $photos, portionList: $portionList, currentMeal: $currentMeal, portionController: $portionController, wakeupController: $wakeupController, retireController: $retireController, mealTimeController: $mealTimeController, commentController: $commentController, productNameController: $productNameController, productQuantityController: $productQuantityController, caloriesController: $caloriesController, fatsController: $fatsController, proteinsController: $proteinsController, carbsController: $carbsController, selectedMood: $selectedMood, selectedSatiety: $selectedSatiety, wakeupExpanded: $wakeupExpanded, moderationExpanded: $moderationExpanded, moodExpanded: $moodExpanded, isLoading: $isLoading, isAdded: $isAdded)'; + return 'DiaryState.loaded(diary: $diary, diaryDate: $diaryDate, autocompleteList: $autocompleteList, recommendedChartValues: $recommendedChartValues, consumedChartValues: $consumedChartValues, portions: $portions, photos: $photos, mealList: $mealList, portionList: $portionList, currentMeal: $currentMeal, portionController: $portionController, wakeupController: $wakeupController, retireController: $retireController, mealTimeController: $mealTimeController, commentController: $commentController, productNameController: $productNameController, productQuantityController: $productQuantityController, caloriesController: $caloriesController, fatsController: $fatsController, proteinsController: $proteinsController, carbsController: $carbsController, selectedMood: $selectedMood, selectedSatiety: $selectedSatiety, wakeupExpanded: $wakeupExpanded, moderationExpanded: $moderationExpanded, moodExpanded: $moodExpanded, isLoading: $isLoading, isAdded: $isAdded)'; } @override @@ -926,6 +951,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { .equals(other._consumedChartValues, _consumedChartValues) && const DeepCollectionEquality().equals(other._portions, _portions) && const DeepCollectionEquality().equals(other._photos, _photos) && + const DeepCollectionEquality().equals(other._mealList, _mealList) && const DeepCollectionEquality() .equals(other._portionList, _portionList) && (identical(other.currentMeal, currentMeal) || @@ -978,6 +1004,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { const DeepCollectionEquality().hash(_consumedChartValues), const DeepCollectionEquality().hash(_portions), const DeepCollectionEquality().hash(_photos), + const DeepCollectionEquality().hash(_mealList), const DeepCollectionEquality().hash(_portionList), currentMeal, portionController, @@ -1020,6 +1047,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, @@ -1051,6 +1079,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { consumedChartValues, portions, photos, + mealList, portionList, currentMeal, portionController, @@ -1086,6 +1115,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, @@ -1117,6 +1147,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { consumedChartValues, portions, photos, + mealList, portionList, currentMeal, portionController, @@ -1152,6 +1183,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, @@ -1185,6 +1217,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { consumedChartValues, portions, photos, + mealList, portionList, currentMeal, portionController, @@ -1256,6 +1289,7 @@ abstract class DiaryStateLoaded implements DiaryState { required final List consumedChartValues, required final List portions, required final List photos, + required final List mealList, required final List portionList, required final Meal currentMeal, required final SelectionPopupModel portionController, @@ -1284,6 +1318,7 @@ abstract class DiaryStateLoaded implements DiaryState { List get consumedChartValues; List get portions; List get photos; + List get mealList; List get portionList; Meal get currentMeal; SelectionPopupModel get portionController; @@ -1385,6 +1420,7 @@ class _$DiaryStateErrorImpl implements DiaryStateError { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, @@ -1424,6 +1460,7 @@ class _$DiaryStateErrorImpl implements DiaryStateError { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, @@ -1463,6 +1500,7 @@ class _$DiaryStateErrorImpl implements DiaryStateError { List consumedChartValues, List portions, List photos, + List mealList, List portionList, Meal currentMeal, SelectionPopupModel portionController, diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index 8dcdbb7..422d8bc 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -247,9 +247,7 @@ class DiaryScreen extends StatelessWidget { borderRadius: BorderRadiusStyle.roundedBorder5, ), child: Center( - child: CircularProgressIndicator( - color: appTheme - .blueGray300), // Замените на свой прелоадер при необходимости + child: CircularProgressIndicator(color: appTheme.blueGray300), // Замените на свой прелоадер при необходимости ), ), ], @@ -273,8 +271,7 @@ class DiaryScreen extends StatelessWidget { _buildMeal(BuildContext context, DiaryStateLoaded state) { final digitsOnly = FilteringTextInputFormatter.digitsOnly; - List _options = - state.autocompleteList.map((dynamic item) => item as String).toList(); + List _options = state.autocompleteList.map((dynamic item) => item as String).toList(); FocusNode focusNodeName = FocusNode(); return Container( margin: EdgeInsets.symmetric(horizontal: 16.h), @@ -318,9 +315,7 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectMealTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: state.mealTimeController - ?.format(context) - .toString(), + hintText: state.mealTimeController?.format(context).toString(), autofocus: false, ), ), @@ -342,14 +337,13 @@ class DiaryScreen extends StatelessWidget { return null; }, builder: (context, diary) { - List meals = mealsToDropdown(diary!.meals); return CustomDropDown( - hintText: meals[0].title, - items: meals, + items: state.mealList, contentPadding: EdgeInsets.symmetric( horizontal: 10.h, vertical: 9.v, ), + defaultValue: state.mealList[0], onChanged: changeMeal(context, state), ); }, @@ -457,9 +451,7 @@ class DiaryScreen extends StatelessWidget { SizedBox(height: 30.v), _buildAddProduct(context, state), SizedBox(height: 30.v), - ...state.portions - .map((portion) => _buildProduct(context, portion)) - .toList(), + ...state.portions.map((portion) => _buildProduct(context, portion)).toList(), SizedBox(height: 30.v), /*...state.photos != null ? state.photos!.isEmpty @@ -616,8 +608,7 @@ class DiaryScreen extends StatelessWidget { popDialog(BuildContext dialogContext) { return () { - Navigator.of(dialogContext) - .pop(); // Dismiss the dialog on Cancel button press + Navigator.of(dialogContext).pop(); // Dismiss the dialog on Cancel button press }; } @@ -627,8 +618,7 @@ class DiaryScreen extends StatelessWidget { }; } - selectProduct(AutocompleteOnSelected onSelected, String option, - DiaryStateLoaded state) { + selectProduct(AutocompleteOnSelected onSelected, String option, DiaryStateLoaded state) { state.productNameController.text = option; return () { onSelected(option); @@ -653,9 +643,7 @@ class DiaryScreen extends StatelessWidget { changeMeal(BuildContext context, DiaryStateLoaded state) { return (value) { - context - .read() - .add(ChangeMeal(meals: state.diary.meals, value: value)); + context.read().add(ChangeMeal(value: value)); }; } @@ -672,8 +660,7 @@ class DiaryScreen extends StatelessWidget { return CarouselSlider( options: CarouselOptions(height: 340.0), items: state.currentMeal.photos.map((photo) { - return _buildPhoto( - context, photo); // Assuming photos are stored as strings + return _buildPhoto(context, photo); // Assuming photos are stored as strings }).toList(), ); } @@ -699,9 +686,7 @@ class DiaryScreen extends StatelessWidget { top: 5.v, ), child: Text( - portion.productName.length > 8 - ? portion.productName.substring(0, 8) - : portion.productName, + portion.productName.length > 8 ? portion.productName.substring(0, 8) : portion.productName, style: CustomTextStyles.titleMedium16, ), ), @@ -773,15 +758,12 @@ class DiaryScreen extends StatelessWidget { removePhoto(BuildContext context, Photo photo) { return () { - context - .read() - .add(RemoveImageEvent(photo.id.toString(), photo.path)); + context.read().add(RemoveImageEvent(photo.id.toString(), photo.path)); }; } _buildNutritionChart(BuildContext context, DiaryStateLoaded state) { - final List recommendedValues = state - .recommendedChartValues; // Рекомендуемые значения: калории, жиры, белки, углеводы + final List recommendedValues = state.recommendedChartValues; // Рекомендуемые значения: калории, жиры, белки, углеводы final List consumedValues = state.consumedChartValues; // return Container( margin: EdgeInsets.symmetric(horizontal: 16.h), @@ -845,10 +827,7 @@ class DiaryScreen extends StatelessWidget { barRods: [ BarChartRodData( toY: consumedValues[0] / recommendedValues[0] * 100, - color: checkConsumedValues( - [recommendedValues[0]], [consumedValues[1]]) - ? Colors.red - : Colors.blue, + color: checkConsumedValues([recommendedValues[0]], [consumedValues[1]]) ? Colors.red : Colors.blue, ), ], ), @@ -857,10 +836,7 @@ class DiaryScreen extends StatelessWidget { barRods: [ BarChartRodData( toY: consumedValues[1] / recommendedValues[1] * 100, - color: checkConsumedValues( - [recommendedValues[1]], [consumedValues[1]]) - ? Colors.red - : Colors.blue, + color: checkConsumedValues([recommendedValues[1]], [consumedValues[1]]) ? Colors.red : Colors.blue, ), ], ), @@ -869,10 +845,7 @@ class DiaryScreen extends StatelessWidget { barRods: [ BarChartRodData( toY: consumedValues[2] / recommendedValues[2] * 100, - color: checkConsumedValues( - [recommendedValues[2]], [consumedValues[2]]) - ? Colors.red - : Colors.blue, + color: checkConsumedValues([recommendedValues[2]], [consumedValues[2]]) ? Colors.red : Colors.blue, ), ], ), @@ -881,10 +854,7 @@ class DiaryScreen extends StatelessWidget { barRods: [ BarChartRodData( toY: consumedValues[3] / recommendedValues[3] * 100, - color: checkConsumedValues( - [recommendedValues[3]], [consumedValues[3]]) - ? Colors.red - : Colors.blue, + color: checkConsumedValues([recommendedValues[3]], [consumedValues[3]]) ? Colors.red : Colors.blue, ), ], ), @@ -1075,9 +1045,7 @@ class DiaryScreen extends StatelessWidget { r"Подъем \ отход ко сну", style: CustomTextStyles.bodyMediumBlack900, ), - Icon(state.wakeupExpanded - ? Icons.arrow_drop_up - : Icons.arrow_drop_down), + Icon(state.wakeupExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), ], ), ), @@ -1091,8 +1059,7 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectWakeupTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: - state.wakeupController?.format(context).toString(), + hintText: state.wakeupController?.format(context).toString(), prefix: Icon(Icons.sunny), autofocus: false, ), @@ -1103,8 +1070,7 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectRetireTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: - state.retireController?.format(context).toString(), + hintText: state.retireController?.format(context).toString(), prefix: Icon(Icons.bed), autofocus: false, ), @@ -1151,8 +1117,7 @@ class DiaryScreen extends StatelessWidget { }; } - Function() sendFinishDayData( - BuildContext dialogContext, BuildContext context) { + Function() sendFinishDayData(BuildContext dialogContext, BuildContext context) { return () { closeDialog(dialogContext); context.read().add(FinishDay()); @@ -1195,9 +1160,7 @@ class DiaryScreen extends StatelessWidget { "Ваше настроение после приема пищи", style: CustomTextStyles.bodyMediumBlack900, ), - Icon(state.moodExpanded - ? Icons.arrow_drop_up - : Icons.arrow_drop_down), + Icon(state.moodExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), ], ), ), @@ -1257,8 +1220,7 @@ class DiaryScreen extends StatelessWidget { }; } - Future _selectWakeupTime( - BuildContext context, DiaryStateLoaded state) async { + Future _selectWakeupTime(BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.wakeupController ?? TimeOfDay.now(), @@ -1268,8 +1230,7 @@ class DiaryScreen extends StatelessWidget { } } - Future _selectRetireTime( - BuildContext context, DiaryStateLoaded state) async { + Future _selectRetireTime(BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.retireController ?? TimeOfDay.now(), @@ -1279,8 +1240,7 @@ class DiaryScreen extends StatelessWidget { } } - Future _selectMealTime( - BuildContext context, DiaryStateLoaded state) async { + Future _selectMealTime(BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.mealTimeController ?? TimeOfDay.now(), @@ -1291,8 +1251,7 @@ class DiaryScreen extends StatelessWidget { } } -bool checkConsumedValues( - List recommendedValues, List consumedValues) { +bool checkConsumedValues(List recommendedValues, List consumedValues) { for (int i = 0; i < recommendedValues.length; i++) { if (consumedValues[i] > recommendedValues[i]) { // Если хотя бы одно потребленное значение превышает рекомендованное -- 2.49.1 From fc58ec60421a49e154d5a84467cf9824cc48ef9d Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Mon, 15 Jul 2024 17:34:04 +0300 Subject: [PATCH 064/110] feature(registration): iter 7 --- .../initialization_state.freezed.dart | 90 +++++++--- .../selection_popup_model.freezed.dart | 43 +++-- .../user_registration_model.freezed.dart | 120 ++++++++----- .../user_registration_model.g.dart | 11 +- .../models/blog_post_model.freezed.dart | 58 +++++-- .../blog_post/models/blog_post_model.g.dart | 6 +- .../bloc/blog_post_state.freezed.dart | 82 ++++++--- .../services/blog_post_service.g.dart | 29 ++-- .../services/blog_service.g.dart | 32 ++-- .../new_messages_state.freezed.dart | 86 +++++++--- .../notifications_state.freezed.dart | 89 +++++++--- .../models/chat_message_model.freezed.dart | 59 ++++--- .../chat/models/chat_message_model.g.dart | 8 +- .../models/chat_messages_model.freezed.dart | 62 +++++-- .../chat/models/chat_messages_model.g.dart | 12 +- .../chat/models/chat_meta_model.freezed.dart | 49 ++++-- .../chat/models/chat_meta_model.g.dart | 6 +- .../chat/models/chat_room_model.freezed.dart | 68 +++++--- .../chat/models/chat_room_model.g.dart | 12 +- .../chat_room_settings_model.freezed.dart | 65 ++++--- .../models/chat_room_settings_model.g.dart | 8 +- .../chat/models/chat_user_model.freezed.dart | 67 +++++--- .../chat/models/chat_user_model.g.dart | 6 +- .../models/websocket_info_model.freezed.dart | 68 +++++--- .../chat/models/websocket_info_model.g.dart | 8 +- .../chat_room_state.freezed.dart | 161 +++++++++++++----- .../chat/services/chat_service.g.dart | 82 ++++----- .../diary/models/diary_model.freezed.dart | 58 +++++-- lib/features/diary/models/diary_model.g.dart | 10 +- .../models/feed_blog_post_model.freezed.dart | 51 ++++-- .../feed/models/feed_blog_post_model.g.dart | 8 +- ...feed_blog_post_settings_model.freezed.dart | 63 ++++--- .../feed_blog_post_settings_model.g.dart | 12 +- .../bloc/feed_cubit/feed_state.freezed.dart | 95 ++++++++--- .../feed/services/feed_service.g.dart | 29 ++-- .../registration_cubit.dart | 12 +- .../registration_state.freezed.dart | 37 ++-- .../pages/registration_screen.dart | 32 +++- .../repositories/registration_repository.dart | 4 +- .../services/registration_service.dart | 2 +- .../services/registration_service.g.dart | 34 ++-- 41 files changed, 1264 insertions(+), 570 deletions(-) diff --git a/lib/core/initialization_cubit/initialization_state.freezed.dart b/lib/core/initialization_cubit/initialization_state.freezed.dart index b5e8e4d..3364e44 100644 --- a/lib/core/initialization_cubit/initialization_state.freezed.dart +++ b/lib/core/initialization_cubit/initialization_state.freezed.dart @@ -70,12 +70,14 @@ mixin _$InitializationState { /// @nodoc abstract class $InitializationStateCopyWith<$Res> { - factory $InitializationStateCopyWith(InitializationState value, $Res Function(InitializationState) then) = + factory $InitializationStateCopyWith( + InitializationState value, $Res Function(InitializationState) then) = _$InitializationStateCopyWithImpl<$Res, InitializationState>; } /// @nodoc -class _$InitializationStateCopyWithImpl<$Res, $Val extends InitializationState> implements $InitializationStateCopyWith<$Res> { +class _$InitializationStateCopyWithImpl<$Res, $Val extends InitializationState> + implements $InitializationStateCopyWith<$Res> { _$InitializationStateCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -86,14 +88,18 @@ class _$InitializationStateCopyWithImpl<$Res, $Val extends InitializationState> /// @nodoc abstract class _$$InitializationStateImplCopyWith<$Res> { - factory _$$InitializationStateImplCopyWith(_$InitializationStateImpl value, $Res Function(_$InitializationStateImpl) then) = + factory _$$InitializationStateImplCopyWith(_$InitializationStateImpl value, + $Res Function(_$InitializationStateImpl) then) = __$$InitializationStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$InitializationStateImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateImpl> +class __$$InitializationStateImplCopyWithImpl<$Res> + extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateImpl> implements _$$InitializationStateImplCopyWith<$Res> { - __$$InitializationStateImplCopyWithImpl(_$InitializationStateImpl _value, $Res Function(_$InitializationStateImpl) _then) : super(_value, _then); + __$$InitializationStateImplCopyWithImpl(_$InitializationStateImpl _value, + $Res Function(_$InitializationStateImpl) _then) + : super(_value, _then); } /// @nodoc @@ -108,7 +114,9 @@ class _$InitializationStateImpl implements _InitializationState { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$InitializationStateImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$InitializationStateImpl); } @override @@ -195,14 +203,20 @@ abstract class _InitializationState implements InitializationState { /// @nodoc abstract class _$$InitializationStateLoadingImplCopyWith<$Res> { - factory _$$InitializationStateLoadingImplCopyWith(_$InitializationStateLoadingImpl value, $Res Function(_$InitializationStateLoadingImpl) then) = + factory _$$InitializationStateLoadingImplCopyWith( + _$InitializationStateLoadingImpl value, + $Res Function(_$InitializationStateLoadingImpl) then) = __$$InitializationStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$InitializationStateLoadingImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateLoadingImpl> +class __$$InitializationStateLoadingImplCopyWithImpl<$Res> + extends _$InitializationStateCopyWithImpl<$Res, + _$InitializationStateLoadingImpl> implements _$$InitializationStateLoadingImplCopyWith<$Res> { - __$$InitializationStateLoadingImplCopyWithImpl(_$InitializationStateLoadingImpl _value, $Res Function(_$InitializationStateLoadingImpl) _then) + __$$InitializationStateLoadingImplCopyWithImpl( + _$InitializationStateLoadingImpl _value, + $Res Function(_$InitializationStateLoadingImpl) _then) : super(_value, _then); } @@ -218,7 +232,9 @@ class _$InitializationStateLoadingImpl implements InitializationStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$InitializationStateLoadingImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$InitializationStateLoadingImpl); } @override @@ -305,16 +321,22 @@ abstract class InitializationStateLoading implements InitializationState { /// @nodoc abstract class _$$InitializationStateSuccessImplCopyWith<$Res> { - factory _$$InitializationStateSuccessImplCopyWith(_$InitializationStateSuccessImpl value, $Res Function(_$InitializationStateSuccessImpl) then) = + factory _$$InitializationStateSuccessImplCopyWith( + _$InitializationStateSuccessImpl value, + $Res Function(_$InitializationStateSuccessImpl) then) = __$$InitializationStateSuccessImplCopyWithImpl<$Res>; @useResult $Res call({PusherChannelsClient client}); } /// @nodoc -class __$$InitializationStateSuccessImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateSuccessImpl> +class __$$InitializationStateSuccessImplCopyWithImpl<$Res> + extends _$InitializationStateCopyWithImpl<$Res, + _$InitializationStateSuccessImpl> implements _$$InitializationStateSuccessImplCopyWith<$Res> { - __$$InitializationStateSuccessImplCopyWithImpl(_$InitializationStateSuccessImpl _value, $Res Function(_$InitializationStateSuccessImpl) _then) + __$$InitializationStateSuccessImplCopyWithImpl( + _$InitializationStateSuccessImpl _value, + $Res Function(_$InitializationStateSuccessImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -347,7 +369,9 @@ class _$InitializationStateSuccessImpl implements InitializationStateSuccess { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && other is _$InitializationStateSuccessImpl && (identical(other.client, client) || other.client == client)); + (other.runtimeType == runtimeType && + other is _$InitializationStateSuccessImpl && + (identical(other.client, client) || other.client == client)); } @override @@ -356,8 +380,9 @@ class _$InitializationStateSuccessImpl implements InitializationStateSuccess { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> get copyWith => - __$$InitializationStateSuccessImplCopyWithImpl<_$InitializationStateSuccessImpl>(this, _$identity); + _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> + get copyWith => __$$InitializationStateSuccessImplCopyWithImpl< + _$InitializationStateSuccessImpl>(this, _$identity); @override @optionalTypeArgs @@ -435,25 +460,34 @@ class _$InitializationStateSuccessImpl implements InitializationStateSuccess { } abstract class InitializationStateSuccess implements InitializationState { - const factory InitializationStateSuccess({required final PusherChannelsClient client}) = _$InitializationStateSuccessImpl; + const factory InitializationStateSuccess( + {required final PusherChannelsClient client}) = + _$InitializationStateSuccessImpl; PusherChannelsClient get client; @JsonKey(ignore: true) - _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> get copyWith => throw _privateConstructorUsedError; + _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> + get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$InitializationStateErrorImplCopyWith<$Res> { - factory _$$InitializationStateErrorImplCopyWith(_$InitializationStateErrorImpl value, $Res Function(_$InitializationStateErrorImpl) then) = + factory _$$InitializationStateErrorImplCopyWith( + _$InitializationStateErrorImpl value, + $Res Function(_$InitializationStateErrorImpl) then) = __$$InitializationStateErrorImplCopyWithImpl<$Res>; @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$InitializationStateErrorImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateErrorImpl> +class __$$InitializationStateErrorImplCopyWithImpl<$Res> + extends _$InitializationStateCopyWithImpl<$Res, + _$InitializationStateErrorImpl> implements _$$InitializationStateErrorImplCopyWith<$Res> { - __$$InitializationStateErrorImplCopyWithImpl(_$InitializationStateErrorImpl _value, $Res Function(_$InitializationStateErrorImpl) _then) + __$$InitializationStateErrorImplCopyWithImpl( + _$InitializationStateErrorImpl _value, + $Res Function(_$InitializationStateErrorImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -488,7 +522,8 @@ class _$InitializationStateErrorImpl implements InitializationStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$InitializationStateErrorImpl && - (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); } @override @@ -497,8 +532,9 @@ class _$InitializationStateErrorImpl implements InitializationStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> get copyWith => - __$$InitializationStateErrorImplCopyWithImpl<_$InitializationStateErrorImpl>(this, _$identity); + _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> + get copyWith => __$$InitializationStateErrorImplCopyWithImpl< + _$InitializationStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -576,9 +612,11 @@ class _$InitializationStateErrorImpl implements InitializationStateError { } abstract class InitializationStateError implements InitializationState { - const factory InitializationStateError({required final String errorMessage}) = _$InitializationStateErrorImpl; + const factory InitializationStateError({required final String errorMessage}) = + _$InitializationStateErrorImpl; String get errorMessage; @JsonKey(ignore: true) - _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> get copyWith => throw _privateConstructorUsedError; + _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> + get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart b/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart index 85c5d00..917785c 100644 --- a/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart +++ b/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart @@ -22,19 +22,22 @@ mixin _$SelectionPopupModel { bool get isSelected => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $SelectionPopupModelCopyWith get copyWith => throw _privateConstructorUsedError; + $SelectionPopupModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $SelectionPopupModelCopyWith<$Res> { - factory $SelectionPopupModelCopyWith(SelectionPopupModel value, $Res Function(SelectionPopupModel) then) = + 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> { +class _$SelectionPopupModelCopyWithImpl<$Res, $Val extends SelectionPopupModel> + implements $SelectionPopupModelCopyWith<$Res> { _$SelectionPopupModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -72,8 +75,10 @@ class _$SelectionPopupModelCopyWithImpl<$Res, $Val extends SelectionPopupModel> } /// @nodoc -abstract class _$$SelectionPopupModelImplCopyWith<$Res> implements $SelectionPopupModelCopyWith<$Res> { - factory _$$SelectionPopupModelImplCopyWith(_$SelectionPopupModelImpl value, $Res Function(_$SelectionPopupModelImpl) then) = +abstract class _$$SelectionPopupModelImplCopyWith<$Res> + implements $SelectionPopupModelCopyWith<$Res> { + factory _$$SelectionPopupModelImplCopyWith(_$SelectionPopupModelImpl value, + $Res Function(_$SelectionPopupModelImpl) then) = __$$SelectionPopupModelImplCopyWithImpl<$Res>; @override @useResult @@ -81,9 +86,12 @@ abstract class _$$SelectionPopupModelImplCopyWith<$Res> implements $SelectionPop } /// @nodoc -class __$$SelectionPopupModelImplCopyWithImpl<$Res> extends _$SelectionPopupModelCopyWithImpl<$Res, _$SelectionPopupModelImpl> +class __$$SelectionPopupModelImplCopyWithImpl<$Res> + extends _$SelectionPopupModelCopyWithImpl<$Res, _$SelectionPopupModelImpl> implements _$$SelectionPopupModelImplCopyWith<$Res> { - __$$SelectionPopupModelImplCopyWithImpl(_$SelectionPopupModelImpl _value, $Res Function(_$SelectionPopupModelImpl) _then) : super(_value, _then); + __$$SelectionPopupModelImplCopyWithImpl(_$SelectionPopupModelImpl _value, + $Res Function(_$SelectionPopupModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -117,7 +125,8 @@ class __$$SelectionPopupModelImplCopyWithImpl<$Res> extends _$SelectionPopupMode /// @nodoc class _$SelectionPopupModelImpl implements _SelectionPopupModel { - const _$SelectionPopupModelImpl({this.id, required this.title, this.value, this.isSelected = false}); + const _$SelectionPopupModelImpl( + {this.id, required this.title, this.value, this.isSelected = false}); @override final int? id; @@ -142,21 +151,28 @@ class _$SelectionPopupModelImpl implements _SelectionPopupModel { (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)); + (identical(other.isSelected, isSelected) || + other.isSelected == isSelected)); } @override - int get hashCode => Object.hash(runtimeType, id, title, const DeepCollectionEquality().hash(value), isSelected); + 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); + __$$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; + const factory _SelectionPopupModel( + {final int? id, + required final String title, + final dynamic value, + final bool isSelected}) = _$SelectionPopupModelImpl; @override int? get id; @@ -168,5 +184,6 @@ abstract class _SelectionPopupModel implements SelectionPopupModel { bool get isSelected; @override @JsonKey(ignore: true) - _$$SelectionPopupModelImplCopyWith<_$SelectionPopupModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$SelectionPopupModelImplCopyWith<_$SelectionPopupModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart b/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart index 6c44566..4aa91df 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart @@ -14,7 +14,8 @@ 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) { +UserRegistrationSheet _$UserRegistrationSheetFromJson( + Map json) { return _UserRegistrationSheet.fromJson(json); } @@ -69,12 +70,14 @@ mixin _$UserRegistrationSheet { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $UserRegistrationSheetCopyWith get copyWith => throw _privateConstructorUsedError; + $UserRegistrationSheetCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $UserRegistrationSheetCopyWith<$Res> { - factory $UserRegistrationSheetCopyWith(UserRegistrationSheet value, $Res Function(UserRegistrationSheet) then) = + factory $UserRegistrationSheetCopyWith(UserRegistrationSheet value, + $Res Function(UserRegistrationSheet) then) = _$UserRegistrationSheetCopyWithImpl<$Res, UserRegistrationSheet>; @useResult $Res call( @@ -109,7 +112,9 @@ abstract class $UserRegistrationSheetCopyWith<$Res> { } /// @nodoc -class _$UserRegistrationSheetCopyWithImpl<$Res, $Val extends UserRegistrationSheet> implements $UserRegistrationSheetCopyWith<$Res> { +class _$UserRegistrationSheetCopyWithImpl<$Res, + $Val extends UserRegistrationSheet> + implements $UserRegistrationSheetCopyWith<$Res> { _$UserRegistrationSheetCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -267,8 +272,11 @@ class _$UserRegistrationSheetCopyWithImpl<$Res, $Val extends UserRegistrationShe } /// @nodoc -abstract class _$$UserRegistrationSheetImplCopyWith<$Res> implements $UserRegistrationSheetCopyWith<$Res> { - factory _$$UserRegistrationSheetImplCopyWith(_$UserRegistrationSheetImpl value, $Res Function(_$UserRegistrationSheetImpl) then) = +abstract class _$$UserRegistrationSheetImplCopyWith<$Res> + implements $UserRegistrationSheetCopyWith<$Res> { + factory _$$UserRegistrationSheetImplCopyWith( + _$UserRegistrationSheetImpl value, + $Res Function(_$UserRegistrationSheetImpl) then) = __$$UserRegistrationSheetImplCopyWithImpl<$Res>; @override @useResult @@ -304,9 +312,13 @@ abstract class _$$UserRegistrationSheetImplCopyWith<$Res> implements $UserRegist } /// @nodoc -class __$$UserRegistrationSheetImplCopyWithImpl<$Res> extends _$UserRegistrationSheetCopyWithImpl<$Res, _$UserRegistrationSheetImpl> +class __$$UserRegistrationSheetImplCopyWithImpl<$Res> + extends _$UserRegistrationSheetCopyWithImpl<$Res, + _$UserRegistrationSheetImpl> implements _$$UserRegistrationSheetImplCopyWith<$Res> { - __$$UserRegistrationSheetImplCopyWithImpl(_$UserRegistrationSheetImpl _value, $Res Function(_$UserRegistrationSheetImpl) _then) : super(_value, _then); + __$$UserRegistrationSheetImplCopyWithImpl(_$UserRegistrationSheetImpl _value, + $Res Function(_$UserRegistrationSheetImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -466,7 +478,8 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @JsonKey(name: 'last_name') required this.lastName, required this.email, required this.password, - @JsonKey(name: 'password_confirmation') required this.passwordConfirmation, + @JsonKey(name: 'password_confirmation') + required this.passwordConfirmation, @JsonKey(name: 'terms') this.termsAccepted = 'accepted', required this.birthdate, required this.gender, @@ -490,7 +503,8 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @JsonKey(name: 'additional_info') required this.additionalInfo, @JsonKey(name: 'activity_coefficient') this.activityCoefficient = 1.2}); - factory _$UserRegistrationSheetImpl.fromJson(Map json) => _$$UserRegistrationSheetImplFromJson(json); + factory _$UserRegistrationSheetImpl.fromJson(Map json) => + _$$UserRegistrationSheetImplFromJson(json); @override final String name; @@ -578,33 +592,52 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { (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.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.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.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)); + (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) @@ -644,8 +677,9 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$UserRegistrationSheetImplCopyWith<_$UserRegistrationSheetImpl> get copyWith => - __$$UserRegistrationSheetImplCopyWithImpl<_$UserRegistrationSheetImpl>(this, _$identity); + _$$UserRegistrationSheetImplCopyWith<_$UserRegistrationSheetImpl> + get copyWith => __$$UserRegistrationSheetImplCopyWithImpl< + _$UserRegistrationSheetImpl>(this, _$identity); @override Map toJson() { @@ -662,7 +696,8 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { @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: 'password_confirmation') + required final String passwordConfirmation, @JsonKey(name: 'terms') final String termsAccepted, required final String birthdate, required final String gender, @@ -671,22 +706,28 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { 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: '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: '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: '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; + @JsonKey(name: 'activity_coefficient') + final double activityCoefficient}) = _$UserRegistrationSheetImpl; - factory _UserRegistrationSheet.fromJson(Map json) = _$UserRegistrationSheetImpl.fromJson; + factory _UserRegistrationSheet.fromJson(Map json) = + _$UserRegistrationSheetImpl.fromJson; @override String get name; @@ -764,5 +805,6 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { double get activityCoefficient; @override @JsonKey(ignore: true) - _$$UserRegistrationSheetImplCopyWith<_$UserRegistrationSheetImpl> get copyWith => throw _privateConstructorUsedError; + _$$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 index 7827901..132240b 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.g.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.g.dart @@ -6,7 +6,9 @@ part of 'user_registration_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson(Map json) => _$UserRegistrationSheetImpl( +_$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson( + Map json) => + _$UserRegistrationSheetImpl( name: json['name'] as String, firstName: json['first_name'] as String, lastName: json['last_name'] as String, @@ -34,10 +36,13 @@ _$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson(Map _$$UserRegistrationSheetImplToJson(_$UserRegistrationSheetImpl instance) => { +Map _$$UserRegistrationSheetImplToJson( + _$UserRegistrationSheetImpl instance) => + { 'name': instance.name, 'first_name': instance.firstName, 'last_name': instance.lastName, diff --git a/lib/features/blog_post/models/blog_post_model.freezed.dart b/lib/features/blog_post/models/blog_post_model.freezed.dart index 06f768a..7c0a750 100644 --- a/lib/features/blog_post/models/blog_post_model.freezed.dart +++ b/lib/features/blog_post/models/blog_post_model.freezed.dart @@ -36,12 +36,15 @@ mixin _$BlogPostModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $BlogPostModelCopyWith get copyWith => throw _privateConstructorUsedError; + $BlogPostModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $BlogPostModelCopyWith<$Res> { - factory $BlogPostModelCopyWith(BlogPostModel value, $Res Function(BlogPostModel) then) = _$BlogPostModelCopyWithImpl<$Res, BlogPostModel>; + factory $BlogPostModelCopyWith( + BlogPostModel value, $Res Function(BlogPostModel) then) = + _$BlogPostModelCopyWithImpl<$Res, BlogPostModel>; @useResult $Res call( {int id, @@ -57,7 +60,8 @@ abstract class $BlogPostModelCopyWith<$Res> { } /// @nodoc -class _$BlogPostModelCopyWithImpl<$Res, $Val extends BlogPostModel> implements $BlogPostModelCopyWith<$Res> { +class _$BlogPostModelCopyWithImpl<$Res, $Val extends BlogPostModel> + implements $BlogPostModelCopyWith<$Res> { _$BlogPostModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -125,8 +129,11 @@ class _$BlogPostModelCopyWithImpl<$Res, $Val extends BlogPostModel> implements $ } /// @nodoc -abstract class _$$BlogPostModelImplCopyWith<$Res> implements $BlogPostModelCopyWith<$Res> { - factory _$$BlogPostModelImplCopyWith(_$BlogPostModelImpl value, $Res Function(_$BlogPostModelImpl) then) = __$$BlogPostModelImplCopyWithImpl<$Res>; +abstract class _$$BlogPostModelImplCopyWith<$Res> + implements $BlogPostModelCopyWith<$Res> { + factory _$$BlogPostModelImplCopyWith( + _$BlogPostModelImpl value, $Res Function(_$BlogPostModelImpl) then) = + __$$BlogPostModelImplCopyWithImpl<$Res>; @override @useResult $Res call( @@ -143,8 +150,12 @@ abstract class _$$BlogPostModelImplCopyWith<$Res> implements $BlogPostModelCopyW } /// @nodoc -class __$$BlogPostModelImplCopyWithImpl<$Res> extends _$BlogPostModelCopyWithImpl<$Res, _$BlogPostModelImpl> implements _$$BlogPostModelImplCopyWith<$Res> { - __$$BlogPostModelImplCopyWithImpl(_$BlogPostModelImpl _value, $Res Function(_$BlogPostModelImpl) _then) : super(_value, _then); +class __$$BlogPostModelImplCopyWithImpl<$Res> + extends _$BlogPostModelCopyWithImpl<$Res, _$BlogPostModelImpl> + implements _$$BlogPostModelImplCopyWith<$Res> { + __$$BlogPostModelImplCopyWithImpl( + _$BlogPostModelImpl _value, $Res Function(_$BlogPostModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -220,7 +231,8 @@ class _$BlogPostModelImpl implements _BlogPostModel { @JsonKey(name: "updated_at") required this.updatedAt, required this.title}); - factory _$BlogPostModelImpl.fromJson(Map json) => _$$BlogPostModelImplFromJson(json); + factory _$BlogPostModelImpl.fromJson(Map json) => + _$$BlogPostModelImplFromJson(json); @override final int id; @@ -259,23 +271,31 @@ class _$BlogPostModelImpl implements _BlogPostModel { (identical(other.id, id) || other.id == id) && (identical(other.state, state) || other.state == state) && (identical(other.image, image) || other.image == image) && - (identical(other.description, description) || other.description == description) && - (identical(other.author_name, author_name) || other.author_name == author_name) && - (identical(other.author_avatar_path, author_avatar_path) || other.author_avatar_path == author_avatar_path) && - (identical(other.youtubeUrl, youtubeUrl) || other.youtubeUrl == youtubeUrl) && - (identical(other.createdAt, createdAt) || other.createdAt == createdAt) && - (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt) && + (identical(other.description, description) || + other.description == description) && + (identical(other.author_name, author_name) || + other.author_name == author_name) && + (identical(other.author_avatar_path, author_avatar_path) || + other.author_avatar_path == author_avatar_path) && + (identical(other.youtubeUrl, youtubeUrl) || + other.youtubeUrl == youtubeUrl) && + (identical(other.createdAt, createdAt) || + other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt) && (identical(other.title, title) || other.title == title)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, state, image, description, author_name, author_avatar_path, youtubeUrl, createdAt, updatedAt, title); + int get hashCode => Object.hash(runtimeType, id, state, image, description, + author_name, author_avatar_path, youtubeUrl, createdAt, updatedAt, title); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => __$$BlogPostModelImplCopyWithImpl<_$BlogPostModelImpl>(this, _$identity); + _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => + __$$BlogPostModelImplCopyWithImpl<_$BlogPostModelImpl>(this, _$identity); @override Map toJson() { @@ -298,7 +318,8 @@ abstract class _BlogPostModel implements BlogPostModel { @JsonKey(name: "updated_at") required final DateTime updatedAt, required final String title}) = _$BlogPostModelImpl; - factory _BlogPostModel.fromJson(Map json) = _$BlogPostModelImpl.fromJson; + factory _BlogPostModel.fromJson(Map json) = + _$BlogPostModelImpl.fromJson; @override int get id; @@ -325,5 +346,6 @@ abstract class _BlogPostModel implements BlogPostModel { String get title; @override @JsonKey(ignore: true) - _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/blog_post/models/blog_post_model.g.dart b/lib/features/blog_post/models/blog_post_model.g.dart index 137652f..2e3233c 100644 --- a/lib/features/blog_post/models/blog_post_model.g.dart +++ b/lib/features/blog_post/models/blog_post_model.g.dart @@ -6,7 +6,8 @@ part of 'blog_post_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$BlogPostModelImpl _$$BlogPostModelImplFromJson(Map json) => _$BlogPostModelImpl( +_$BlogPostModelImpl _$$BlogPostModelImplFromJson(Map json) => + _$BlogPostModelImpl( id: (json['id'] as num).toInt(), state: json['state'] as String, image: json['image'] as String?, @@ -19,7 +20,8 @@ _$BlogPostModelImpl _$$BlogPostModelImplFromJson(Map json) => _ title: json['title'] as String, ); -Map _$$BlogPostModelImplToJson(_$BlogPostModelImpl instance) => { +Map _$$BlogPostModelImplToJson(_$BlogPostModelImpl instance) => + { 'id': instance.id, 'state': instance.state, 'image': instance.image, diff --git a/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart b/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart index d204df1..4f99a3c 100644 --- a/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart +++ b/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart @@ -70,11 +70,14 @@ mixin _$BlogPostState { /// @nodoc abstract class $BlogPostStateCopyWith<$Res> { - factory $BlogPostStateCopyWith(BlogPostState value, $Res Function(BlogPostState) then) = _$BlogPostStateCopyWithImpl<$Res, BlogPostState>; + factory $BlogPostStateCopyWith( + BlogPostState value, $Res Function(BlogPostState) then) = + _$BlogPostStateCopyWithImpl<$Res, BlogPostState>; } /// @nodoc -class _$BlogPostStateCopyWithImpl<$Res, $Val extends BlogPostState> implements $BlogPostStateCopyWith<$Res> { +class _$BlogPostStateCopyWithImpl<$Res, $Val extends BlogPostState> + implements $BlogPostStateCopyWith<$Res> { _$BlogPostStateCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -85,12 +88,18 @@ class _$BlogPostStateCopyWithImpl<$Res, $Val extends BlogPostState> implements $ /// @nodoc abstract class _$$BlogPostStateImplCopyWith<$Res> { - factory _$$BlogPostStateImplCopyWith(_$BlogPostStateImpl value, $Res Function(_$BlogPostStateImpl) then) = __$$BlogPostStateImplCopyWithImpl<$Res>; + factory _$$BlogPostStateImplCopyWith( + _$BlogPostStateImpl value, $Res Function(_$BlogPostStateImpl) then) = + __$$BlogPostStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$BlogPostStateImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateImpl> implements _$$BlogPostStateImplCopyWith<$Res> { - __$$BlogPostStateImplCopyWithImpl(_$BlogPostStateImpl _value, $Res Function(_$BlogPostStateImpl) _then) : super(_value, _then); +class __$$BlogPostStateImplCopyWithImpl<$Res> + extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateImpl> + implements _$$BlogPostStateImplCopyWith<$Res> { + __$$BlogPostStateImplCopyWithImpl( + _$BlogPostStateImpl _value, $Res Function(_$BlogPostStateImpl) _then) + : super(_value, _then); } /// @nodoc @@ -105,7 +114,8 @@ class _$BlogPostStateImpl implements _BlogPostState { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$BlogPostStateImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$BlogPostStateImpl); } @override @@ -192,14 +202,18 @@ abstract class _BlogPostState implements BlogPostState { /// @nodoc abstract class _$$BlogPostStateLoadingImplCopyWith<$Res> { - factory _$$BlogPostStateLoadingImplCopyWith(_$BlogPostStateLoadingImpl value, $Res Function(_$BlogPostStateLoadingImpl) then) = + factory _$$BlogPostStateLoadingImplCopyWith(_$BlogPostStateLoadingImpl value, + $Res Function(_$BlogPostStateLoadingImpl) then) = __$$BlogPostStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$BlogPostStateLoadingImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadingImpl> +class __$$BlogPostStateLoadingImplCopyWithImpl<$Res> + extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadingImpl> implements _$$BlogPostStateLoadingImplCopyWith<$Res> { - __$$BlogPostStateLoadingImplCopyWithImpl(_$BlogPostStateLoadingImpl _value, $Res Function(_$BlogPostStateLoadingImpl) _then) : super(_value, _then); + __$$BlogPostStateLoadingImplCopyWithImpl(_$BlogPostStateLoadingImpl _value, + $Res Function(_$BlogPostStateLoadingImpl) _then) + : super(_value, _then); } /// @nodoc @@ -214,7 +228,9 @@ class _$BlogPostStateLoadingImpl implements BlogPostStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$BlogPostStateLoadingImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$BlogPostStateLoadingImpl); } @override @@ -301,7 +317,8 @@ abstract class BlogPostStateLoading implements BlogPostState { /// @nodoc abstract class _$$BlogPostStateLoadedImplCopyWith<$Res> { - factory _$$BlogPostStateLoadedImplCopyWith(_$BlogPostStateLoadedImpl value, $Res Function(_$BlogPostStateLoadedImpl) then) = + factory _$$BlogPostStateLoadedImplCopyWith(_$BlogPostStateLoadedImpl value, + $Res Function(_$BlogPostStateLoadedImpl) then) = __$$BlogPostStateLoadedImplCopyWithImpl<$Res>; @useResult $Res call({BlogPostModel blogPost}); @@ -310,9 +327,12 @@ abstract class _$$BlogPostStateLoadedImplCopyWith<$Res> { } /// @nodoc -class __$$BlogPostStateLoadedImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadedImpl> +class __$$BlogPostStateLoadedImplCopyWithImpl<$Res> + extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadedImpl> implements _$$BlogPostStateLoadedImplCopyWith<$Res> { - __$$BlogPostStateLoadedImplCopyWithImpl(_$BlogPostStateLoadedImpl _value, $Res Function(_$BlogPostStateLoadedImpl) _then) : super(_value, _then); + __$$BlogPostStateLoadedImplCopyWithImpl(_$BlogPostStateLoadedImpl _value, + $Res Function(_$BlogPostStateLoadedImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -352,7 +372,10 @@ class _$BlogPostStateLoadedImpl implements BlogPostStateLoaded { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && other is _$BlogPostStateLoadedImpl && (identical(other.blogPost, blogPost) || other.blogPost == blogPost)); + (other.runtimeType == runtimeType && + other is _$BlogPostStateLoadedImpl && + (identical(other.blogPost, blogPost) || + other.blogPost == blogPost)); } @override @@ -362,7 +385,8 @@ class _$BlogPostStateLoadedImpl implements BlogPostStateLoaded { @override @pragma('vm:prefer-inline') _$$BlogPostStateLoadedImplCopyWith<_$BlogPostStateLoadedImpl> get copyWith => - __$$BlogPostStateLoadedImplCopyWithImpl<_$BlogPostStateLoadedImpl>(this, _$identity); + __$$BlogPostStateLoadedImplCopyWithImpl<_$BlogPostStateLoadedImpl>( + this, _$identity); @override @optionalTypeArgs @@ -440,25 +464,31 @@ class _$BlogPostStateLoadedImpl implements BlogPostStateLoaded { } abstract class BlogPostStateLoaded implements BlogPostState { - const factory BlogPostStateLoaded({required final BlogPostModel blogPost}) = _$BlogPostStateLoadedImpl; + const factory BlogPostStateLoaded({required final BlogPostModel blogPost}) = + _$BlogPostStateLoadedImpl; BlogPostModel get blogPost; @JsonKey(ignore: true) - _$$BlogPostStateLoadedImplCopyWith<_$BlogPostStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; + _$$BlogPostStateLoadedImplCopyWith<_$BlogPostStateLoadedImpl> get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class _$$BlogPostStateErrorImplCopyWith<$Res> { - factory _$$BlogPostStateErrorImplCopyWith(_$BlogPostStateErrorImpl value, $Res Function(_$BlogPostStateErrorImpl) then) = + factory _$$BlogPostStateErrorImplCopyWith(_$BlogPostStateErrorImpl value, + $Res Function(_$BlogPostStateErrorImpl) then) = __$$BlogPostStateErrorImplCopyWithImpl<$Res>; @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$BlogPostStateErrorImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateErrorImpl> +class __$$BlogPostStateErrorImplCopyWithImpl<$Res> + extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateErrorImpl> implements _$$BlogPostStateErrorImplCopyWith<$Res> { - __$$BlogPostStateErrorImplCopyWithImpl(_$BlogPostStateErrorImpl _value, $Res Function(_$BlogPostStateErrorImpl) _then) : super(_value, _then); + __$$BlogPostStateErrorImplCopyWithImpl(_$BlogPostStateErrorImpl _value, + $Res Function(_$BlogPostStateErrorImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -492,7 +522,8 @@ class _$BlogPostStateErrorImpl implements BlogPostStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$BlogPostStateErrorImpl && - (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); } @override @@ -502,7 +533,8 @@ class _$BlogPostStateErrorImpl implements BlogPostStateError { @override @pragma('vm:prefer-inline') _$$BlogPostStateErrorImplCopyWith<_$BlogPostStateErrorImpl> get copyWith => - __$$BlogPostStateErrorImplCopyWithImpl<_$BlogPostStateErrorImpl>(this, _$identity); + __$$BlogPostStateErrorImplCopyWithImpl<_$BlogPostStateErrorImpl>( + this, _$identity); @override @optionalTypeArgs @@ -580,9 +612,11 @@ class _$BlogPostStateErrorImpl implements BlogPostStateError { } abstract class BlogPostStateError implements BlogPostState { - const factory BlogPostStateError({required final String errorMessage}) = _$BlogPostStateErrorImpl; + const factory BlogPostStateError({required final String errorMessage}) = + _$BlogPostStateErrorImpl; String get errorMessage; @JsonKey(ignore: true) - _$$BlogPostStateErrorImplCopyWith<_$BlogPostStateErrorImpl> get copyWith => throw _privateConstructorUsedError; + _$$BlogPostStateErrorImplCopyWith<_$BlogPostStateErrorImpl> get copyWith => + throw _privateConstructorUsedError; } 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 bed4199..4090577 100644 --- a/lib/features/blog_post/services/blog_post_service.g.dart +++ b/lib/features/blog_post/services/blog_post_service.g.dart @@ -24,28 +24,31 @@ class _BlogPostService implements BlogPostService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio + .fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/feed/show/${id}', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/feed/show/${id}', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = BlogPostModel.fromJson(_result.data!); return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && + !(requestOptions.responseType == ResponseType.bytes || + requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { 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 d30d7d8..a6ff68e 100644 --- a/lib/features/blog_post_create/services/blog_service.g.dart +++ b/lib/features/blog_post_create/services/blog_service.g.dart @@ -19,33 +19,37 @@ class _BlogService implements BlogService { String? baseUrl; @override - Future createBlogPost(BlogPostCreateCredentialsModel model) async { + Future createBlogPost( + BlogPostCreateCredentialsModel model) async { final _extra = {}; final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio.fetch>( + _setStreamType(Options( method: 'POST', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/blog_post/create', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/blog_post/create', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = BlogPostCreateCredentialsModel.fromJson(_result.data!); return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && + !(requestOptions.responseType == ResponseType.bytes || + requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart index 68714d7..02a1c4b 100644 --- a/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart +++ b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart @@ -70,11 +70,14 @@ mixin _$NewMessagesState { /// @nodoc abstract class $NewMessagesStateCopyWith<$Res> { - factory $NewMessagesStateCopyWith(NewMessagesState value, $Res Function(NewMessagesState) then) = _$NewMessagesStateCopyWithImpl<$Res, NewMessagesState>; + factory $NewMessagesStateCopyWith( + NewMessagesState value, $Res Function(NewMessagesState) then) = + _$NewMessagesStateCopyWithImpl<$Res, NewMessagesState>; } /// @nodoc -class _$NewMessagesStateCopyWithImpl<$Res, $Val extends NewMessagesState> implements $NewMessagesStateCopyWith<$Res> { +class _$NewMessagesStateCopyWithImpl<$Res, $Val extends NewMessagesState> + implements $NewMessagesStateCopyWith<$Res> { _$NewMessagesStateCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -85,14 +88,18 @@ class _$NewMessagesStateCopyWithImpl<$Res, $Val extends NewMessagesState> implem /// @nodoc abstract class _$$NewMessagesStateImplCopyWith<$Res> { - factory _$$NewMessagesStateImplCopyWith(_$NewMessagesStateImpl value, $Res Function(_$NewMessagesStateImpl) then) = + factory _$$NewMessagesStateImplCopyWith(_$NewMessagesStateImpl value, + $Res Function(_$NewMessagesStateImpl) then) = __$$NewMessagesStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NewMessagesStateImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateImpl> +class __$$NewMessagesStateImplCopyWithImpl<$Res> + extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateImpl> implements _$$NewMessagesStateImplCopyWith<$Res> { - __$$NewMessagesStateImplCopyWithImpl(_$NewMessagesStateImpl _value, $Res Function(_$NewMessagesStateImpl) _then) : super(_value, _then); + __$$NewMessagesStateImplCopyWithImpl(_$NewMessagesStateImpl _value, + $Res Function(_$NewMessagesStateImpl) _then) + : super(_value, _then); } /// @nodoc @@ -107,7 +114,8 @@ class _$NewMessagesStateImpl implements _NewMessagesState { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$NewMessagesStateImpl); } @override @@ -194,14 +202,19 @@ abstract class _NewMessagesState implements NewMessagesState { /// @nodoc abstract class _$$NewMessagesStateEmptyImplCopyWith<$Res> { - factory _$$NewMessagesStateEmptyImplCopyWith(_$NewMessagesStateEmptyImpl value, $Res Function(_$NewMessagesStateEmptyImpl) then) = + factory _$$NewMessagesStateEmptyImplCopyWith( + _$NewMessagesStateEmptyImpl value, + $Res Function(_$NewMessagesStateEmptyImpl) then) = __$$NewMessagesStateEmptyImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NewMessagesStateEmptyImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateEmptyImpl> +class __$$NewMessagesStateEmptyImplCopyWithImpl<$Res> + extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateEmptyImpl> implements _$$NewMessagesStateEmptyImplCopyWith<$Res> { - __$$NewMessagesStateEmptyImplCopyWithImpl(_$NewMessagesStateEmptyImpl _value, $Res Function(_$NewMessagesStateEmptyImpl) _then) : super(_value, _then); + __$$NewMessagesStateEmptyImplCopyWithImpl(_$NewMessagesStateEmptyImpl _value, + $Res Function(_$NewMessagesStateEmptyImpl) _then) + : super(_value, _then); } /// @nodoc @@ -216,7 +229,9 @@ class _$NewMessagesStateEmptyImpl implements NewMessagesStateEmpty { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateEmptyImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$NewMessagesStateEmptyImpl); } @override @@ -303,16 +318,22 @@ abstract class NewMessagesStateEmpty implements NewMessagesState { /// @nodoc abstract class _$$NewMessagesStateLoadedImplCopyWith<$Res> { - factory _$$NewMessagesStateLoadedImplCopyWith(_$NewMessagesStateLoadedImpl value, $Res Function(_$NewMessagesStateLoadedImpl) then) = + factory _$$NewMessagesStateLoadedImplCopyWith( + _$NewMessagesStateLoadedImpl value, + $Res Function(_$NewMessagesStateLoadedImpl) then) = __$$NewMessagesStateLoadedImplCopyWithImpl<$Res>; @useResult $Res call({int messagesCount}); } /// @nodoc -class __$$NewMessagesStateLoadedImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateLoadedImpl> +class __$$NewMessagesStateLoadedImplCopyWithImpl<$Res> + extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateLoadedImpl> implements _$$NewMessagesStateLoadedImplCopyWith<$Res> { - __$$NewMessagesStateLoadedImplCopyWithImpl(_$NewMessagesStateLoadedImpl _value, $Res Function(_$NewMessagesStateLoadedImpl) _then) : super(_value, _then); + __$$NewMessagesStateLoadedImplCopyWithImpl( + _$NewMessagesStateLoadedImpl _value, + $Res Function(_$NewMessagesStateLoadedImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -346,7 +367,8 @@ class _$NewMessagesStateLoadedImpl implements NewMessagesStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateLoadedImpl && - (identical(other.messagesCount, messagesCount) || other.messagesCount == messagesCount)); + (identical(other.messagesCount, messagesCount) || + other.messagesCount == messagesCount)); } @override @@ -355,8 +377,9 @@ class _$NewMessagesStateLoadedImpl implements NewMessagesStateLoaded { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> get copyWith => - __$$NewMessagesStateLoadedImplCopyWithImpl<_$NewMessagesStateLoadedImpl>(this, _$identity); + _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> + get copyWith => __$$NewMessagesStateLoadedImplCopyWithImpl< + _$NewMessagesStateLoadedImpl>(this, _$identity); @override @optionalTypeArgs @@ -434,25 +457,32 @@ class _$NewMessagesStateLoadedImpl implements NewMessagesStateLoaded { } abstract class NewMessagesStateLoaded implements NewMessagesState { - const factory NewMessagesStateLoaded({required final int messagesCount}) = _$NewMessagesStateLoadedImpl; + const factory NewMessagesStateLoaded({required final int messagesCount}) = + _$NewMessagesStateLoadedImpl; int get messagesCount; @JsonKey(ignore: true) - _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; + _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> + get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$NewMessagesStateErrorImplCopyWith<$Res> { - factory _$$NewMessagesStateErrorImplCopyWith(_$NewMessagesStateErrorImpl value, $Res Function(_$NewMessagesStateErrorImpl) then) = + factory _$$NewMessagesStateErrorImplCopyWith( + _$NewMessagesStateErrorImpl value, + $Res Function(_$NewMessagesStateErrorImpl) then) = __$$NewMessagesStateErrorImplCopyWithImpl<$Res>; @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$NewMessagesStateErrorImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateErrorImpl> +class __$$NewMessagesStateErrorImplCopyWithImpl<$Res> + extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateErrorImpl> implements _$$NewMessagesStateErrorImplCopyWith<$Res> { - __$$NewMessagesStateErrorImplCopyWithImpl(_$NewMessagesStateErrorImpl _value, $Res Function(_$NewMessagesStateErrorImpl) _then) : super(_value, _then); + __$$NewMessagesStateErrorImplCopyWithImpl(_$NewMessagesStateErrorImpl _value, + $Res Function(_$NewMessagesStateErrorImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -486,7 +516,8 @@ class _$NewMessagesStateErrorImpl implements NewMessagesStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateErrorImpl && - (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); } @override @@ -495,8 +526,9 @@ class _$NewMessagesStateErrorImpl implements NewMessagesStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> get copyWith => - __$$NewMessagesStateErrorImplCopyWithImpl<_$NewMessagesStateErrorImpl>(this, _$identity); + _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> + get copyWith => __$$NewMessagesStateErrorImplCopyWithImpl< + _$NewMessagesStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -574,9 +606,11 @@ class _$NewMessagesStateErrorImpl implements NewMessagesStateError { } abstract class NewMessagesStateError implements NewMessagesState { - const factory NewMessagesStateError({required final String errorMessage}) = _$NewMessagesStateErrorImpl; + const factory NewMessagesStateError({required final String errorMessage}) = + _$NewMessagesStateErrorImpl; String get errorMessage; @JsonKey(ignore: true) - _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> get copyWith => throw _privateConstructorUsedError; + _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> + get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart b/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart index 2f98548..0deeebb 100644 --- a/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart +++ b/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart @@ -70,12 +70,14 @@ mixin _$NotificationsState { /// @nodoc abstract class $NotificationsStateCopyWith<$Res> { - factory $NotificationsStateCopyWith(NotificationsState value, $Res Function(NotificationsState) then) = + factory $NotificationsStateCopyWith( + NotificationsState value, $Res Function(NotificationsState) then) = _$NotificationsStateCopyWithImpl<$Res, NotificationsState>; } /// @nodoc -class _$NotificationsStateCopyWithImpl<$Res, $Val extends NotificationsState> implements $NotificationsStateCopyWith<$Res> { +class _$NotificationsStateCopyWithImpl<$Res, $Val extends NotificationsState> + implements $NotificationsStateCopyWith<$Res> { _$NotificationsStateCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -86,14 +88,18 @@ class _$NotificationsStateCopyWithImpl<$Res, $Val extends NotificationsState> im /// @nodoc abstract class _$$NotificationsStateImplCopyWith<$Res> { - factory _$$NotificationsStateImplCopyWith(_$NotificationsStateImpl value, $Res Function(_$NotificationsStateImpl) then) = + factory _$$NotificationsStateImplCopyWith(_$NotificationsStateImpl value, + $Res Function(_$NotificationsStateImpl) then) = __$$NotificationsStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NotificationsStateImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateImpl> +class __$$NotificationsStateImplCopyWithImpl<$Res> + extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateImpl> implements _$$NotificationsStateImplCopyWith<$Res> { - __$$NotificationsStateImplCopyWithImpl(_$NotificationsStateImpl _value, $Res Function(_$NotificationsStateImpl) _then) : super(_value, _then); + __$$NotificationsStateImplCopyWithImpl(_$NotificationsStateImpl _value, + $Res Function(_$NotificationsStateImpl) _then) + : super(_value, _then); } /// @nodoc @@ -108,7 +114,8 @@ class _$NotificationsStateImpl implements _NotificationsState { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$NotificationsStateImpl); } @override @@ -195,14 +202,21 @@ abstract class _NotificationsState implements NotificationsState { /// @nodoc abstract class _$$NotificationsStateEmptyImplCopyWith<$Res> { - factory _$$NotificationsStateEmptyImplCopyWith(_$NotificationsStateEmptyImpl value, $Res Function(_$NotificationsStateEmptyImpl) then) = + factory _$$NotificationsStateEmptyImplCopyWith( + _$NotificationsStateEmptyImpl value, + $Res Function(_$NotificationsStateEmptyImpl) then) = __$$NotificationsStateEmptyImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NotificationsStateEmptyImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateEmptyImpl> +class __$$NotificationsStateEmptyImplCopyWithImpl<$Res> + extends _$NotificationsStateCopyWithImpl<$Res, + _$NotificationsStateEmptyImpl> implements _$$NotificationsStateEmptyImplCopyWith<$Res> { - __$$NotificationsStateEmptyImplCopyWithImpl(_$NotificationsStateEmptyImpl _value, $Res Function(_$NotificationsStateEmptyImpl) _then) : super(_value, _then); + __$$NotificationsStateEmptyImplCopyWithImpl( + _$NotificationsStateEmptyImpl _value, + $Res Function(_$NotificationsStateEmptyImpl) _then) + : super(_value, _then); } /// @nodoc @@ -217,7 +231,9 @@ class _$NotificationsStateEmptyImpl implements NotificationsStateEmpty { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateEmptyImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$NotificationsStateEmptyImpl); } @override @@ -304,16 +320,22 @@ abstract class NotificationsStateEmpty implements NotificationsState { /// @nodoc abstract class _$$NotificationsStateLoadedImplCopyWith<$Res> { - factory _$$NotificationsStateLoadedImplCopyWith(_$NotificationsStateLoadedImpl value, $Res Function(_$NotificationsStateLoadedImpl) then) = + factory _$$NotificationsStateLoadedImplCopyWith( + _$NotificationsStateLoadedImpl value, + $Res Function(_$NotificationsStateLoadedImpl) then) = __$$NotificationsStateLoadedImplCopyWithImpl<$Res>; @useResult $Res call({int notificationsCount}); } /// @nodoc -class __$$NotificationsStateLoadedImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateLoadedImpl> +class __$$NotificationsStateLoadedImplCopyWithImpl<$Res> + extends _$NotificationsStateCopyWithImpl<$Res, + _$NotificationsStateLoadedImpl> implements _$$NotificationsStateLoadedImplCopyWith<$Res> { - __$$NotificationsStateLoadedImplCopyWithImpl(_$NotificationsStateLoadedImpl _value, $Res Function(_$NotificationsStateLoadedImpl) _then) + __$$NotificationsStateLoadedImplCopyWithImpl( + _$NotificationsStateLoadedImpl _value, + $Res Function(_$NotificationsStateLoadedImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -348,7 +370,8 @@ class _$NotificationsStateLoadedImpl implements NotificationsStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateLoadedImpl && - (identical(other.notificationsCount, notificationsCount) || other.notificationsCount == notificationsCount)); + (identical(other.notificationsCount, notificationsCount) || + other.notificationsCount == notificationsCount)); } @override @@ -357,8 +380,9 @@ class _$NotificationsStateLoadedImpl implements NotificationsStateLoaded { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> get copyWith => - __$$NotificationsStateLoadedImplCopyWithImpl<_$NotificationsStateLoadedImpl>(this, _$identity); + _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> + get copyWith => __$$NotificationsStateLoadedImplCopyWithImpl< + _$NotificationsStateLoadedImpl>(this, _$identity); @override @optionalTypeArgs @@ -436,25 +460,34 @@ class _$NotificationsStateLoadedImpl implements NotificationsStateLoaded { } abstract class NotificationsStateLoaded implements NotificationsState { - const factory NotificationsStateLoaded({required final int notificationsCount}) = _$NotificationsStateLoadedImpl; + const factory NotificationsStateLoaded( + {required final int notificationsCount}) = _$NotificationsStateLoadedImpl; int get notificationsCount; @JsonKey(ignore: true) - _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; + _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> + get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$NotificationsStateErrorImplCopyWith<$Res> { - factory _$$NotificationsStateErrorImplCopyWith(_$NotificationsStateErrorImpl value, $Res Function(_$NotificationsStateErrorImpl) then) = + factory _$$NotificationsStateErrorImplCopyWith( + _$NotificationsStateErrorImpl value, + $Res Function(_$NotificationsStateErrorImpl) then) = __$$NotificationsStateErrorImplCopyWithImpl<$Res>; @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$NotificationsStateErrorImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateErrorImpl> +class __$$NotificationsStateErrorImplCopyWithImpl<$Res> + extends _$NotificationsStateCopyWithImpl<$Res, + _$NotificationsStateErrorImpl> implements _$$NotificationsStateErrorImplCopyWith<$Res> { - __$$NotificationsStateErrorImplCopyWithImpl(_$NotificationsStateErrorImpl _value, $Res Function(_$NotificationsStateErrorImpl) _then) : super(_value, _then); + __$$NotificationsStateErrorImplCopyWithImpl( + _$NotificationsStateErrorImpl _value, + $Res Function(_$NotificationsStateErrorImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -488,7 +521,8 @@ class _$NotificationsStateErrorImpl implements NotificationsStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateErrorImpl && - (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); } @override @@ -497,8 +531,9 @@ class _$NotificationsStateErrorImpl implements NotificationsStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> get copyWith => - __$$NotificationsStateErrorImplCopyWithImpl<_$NotificationsStateErrorImpl>(this, _$identity); + _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> + get copyWith => __$$NotificationsStateErrorImplCopyWithImpl< + _$NotificationsStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -576,9 +611,11 @@ class _$NotificationsStateErrorImpl implements NotificationsStateError { } abstract class NotificationsStateError implements NotificationsState { - const factory NotificationsStateError({required final String errorMessage}) = _$NotificationsStateErrorImpl; + const factory NotificationsStateError({required final String errorMessage}) = + _$NotificationsStateErrorImpl; String get errorMessage; @JsonKey(ignore: true) - _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> get copyWith => throw _privateConstructorUsedError; + _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> + get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_message_model.freezed.dart b/lib/features/chat/models/chat_message_model.freezed.dart index 90e7e72..76a91cb 100644 --- a/lib/features/chat/models/chat_message_model.freezed.dart +++ b/lib/features/chat/models/chat_message_model.freezed.dart @@ -31,12 +31,15 @@ mixin _$ChatMessageModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $ChatMessageModelCopyWith get copyWith => throw _privateConstructorUsedError; + $ChatMessageModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatMessageModelCopyWith<$Res> { - factory $ChatMessageModelCopyWith(ChatMessageModel value, $Res Function(ChatMessageModel) then) = _$ChatMessageModelCopyWithImpl<$Res, ChatMessageModel>; + factory $ChatMessageModelCopyWith( + ChatMessageModel value, $Res Function(ChatMessageModel) then) = + _$ChatMessageModelCopyWithImpl<$Res, ChatMessageModel>; @useResult $Res call( {int id, @@ -47,7 +50,8 @@ abstract class $ChatMessageModelCopyWith<$Res> { } /// @nodoc -class _$ChatMessageModelCopyWithImpl<$Res, $Val extends ChatMessageModel> implements $ChatMessageModelCopyWith<$Res> { +class _$ChatMessageModelCopyWithImpl<$Res, $Val extends ChatMessageModel> + implements $ChatMessageModelCopyWith<$Res> { _$ChatMessageModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -90,8 +94,10 @@ class _$ChatMessageModelCopyWithImpl<$Res, $Val extends ChatMessageModel> implem } /// @nodoc -abstract class _$$ChatMessageModelImplCopyWith<$Res> implements $ChatMessageModelCopyWith<$Res> { - factory _$$ChatMessageModelImplCopyWith(_$ChatMessageModelImpl value, $Res Function(_$ChatMessageModelImpl) then) = +abstract class _$$ChatMessageModelImplCopyWith<$Res> + implements $ChatMessageModelCopyWith<$Res> { + factory _$$ChatMessageModelImplCopyWith(_$ChatMessageModelImpl value, + $Res Function(_$ChatMessageModelImpl) then) = __$$ChatMessageModelImplCopyWithImpl<$Res>; @override @useResult @@ -104,9 +110,12 @@ abstract class _$$ChatMessageModelImplCopyWith<$Res> implements $ChatMessageMode } /// @nodoc -class __$$ChatMessageModelImplCopyWithImpl<$Res> extends _$ChatMessageModelCopyWithImpl<$Res, _$ChatMessageModelImpl> +class __$$ChatMessageModelImplCopyWithImpl<$Res> + extends _$ChatMessageModelCopyWithImpl<$Res, _$ChatMessageModelImpl> implements _$$ChatMessageModelImplCopyWith<$Res> { - __$$ChatMessageModelImplCopyWithImpl(_$ChatMessageModelImpl _value, $Res Function(_$ChatMessageModelImpl) _then) : super(_value, _then); + __$$ChatMessageModelImplCopyWithImpl(_$ChatMessageModelImpl _value, + $Res Function(_$ChatMessageModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -153,7 +162,8 @@ class _$ChatMessageModelImpl implements _ChatMessageModel { @JsonKey(name: 'updated_at') required this.updatedAt}) : _mediaData = mediaData; - factory _$ChatMessageModelImpl.fromJson(Map json) => _$$ChatMessageModelImplFromJson(json); + factory _$ChatMessageModelImpl.fromJson(Map json) => + _$$ChatMessageModelImplFromJson(json); @override final int id; @@ -189,19 +199,25 @@ class _$ChatMessageModelImpl implements _ChatMessageModel { other is _$ChatMessageModelImpl && (identical(other.id, id) || other.id == id) && (identical(other.data, data) || other.data == data) && - const DeepCollectionEquality().equals(other._mediaData, _mediaData) && - (identical(other.authorId, authorId) || other.authorId == authorId) && - (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)); + const DeepCollectionEquality() + .equals(other._mediaData, _mediaData) && + (identical(other.authorId, authorId) || + other.authorId == authorId) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, data, const DeepCollectionEquality().hash(_mediaData), authorId, updatedAt); + int get hashCode => Object.hash(runtimeType, id, data, + const DeepCollectionEquality().hash(_mediaData), authorId, updatedAt); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => __$$ChatMessageModelImplCopyWithImpl<_$ChatMessageModelImpl>(this, _$identity); + _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => + __$$ChatMessageModelImplCopyWithImpl<_$ChatMessageModelImpl>( + this, _$identity); @override Map toJson() { @@ -213,13 +229,15 @@ class _$ChatMessageModelImpl implements _ChatMessageModel { abstract class _ChatMessageModel implements ChatMessageModel { const factory _ChatMessageModel( - {required final int id, - required final String data, - @JsonKey(name: 'media_data') required final List? mediaData, - @JsonKey(name: 'author_id') required final int authorId, - @JsonKey(name: 'updated_at') required final String updatedAt}) = _$ChatMessageModelImpl; + {required final int id, + required final String data, + @JsonKey(name: 'media_data') required final List? mediaData, + @JsonKey(name: 'author_id') required final int authorId, + @JsonKey(name: 'updated_at') required final String updatedAt}) = + _$ChatMessageModelImpl; - factory _ChatMessageModel.fromJson(Map json) = _$ChatMessageModelImpl.fromJson; + factory _ChatMessageModel.fromJson(Map json) = + _$ChatMessageModelImpl.fromJson; @override int get id; @@ -236,5 +254,6 @@ abstract class _ChatMessageModel implements ChatMessageModel { String get updatedAt; @override @JsonKey(ignore: true) - _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_message_model.g.dart b/lib/features/chat/models/chat_message_model.g.dart index 7053109..3a8d182 100644 --- a/lib/features/chat/models/chat_message_model.g.dart +++ b/lib/features/chat/models/chat_message_model.g.dart @@ -6,7 +6,9 @@ part of 'chat_message_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatMessageModelImpl _$$ChatMessageModelImplFromJson(Map json) => _$ChatMessageModelImpl( +_$ChatMessageModelImpl _$$ChatMessageModelImplFromJson( + Map json) => + _$ChatMessageModelImpl( id: (json['id'] as num).toInt(), data: json['data'] as String, mediaData: json['media_data'] as List?, @@ -14,7 +16,9 @@ _$ChatMessageModelImpl _$$ChatMessageModelImplFromJson(Map json updatedAt: json['updated_at'] as String, ); -Map _$$ChatMessageModelImplToJson(_$ChatMessageModelImpl instance) => { +Map _$$ChatMessageModelImplToJson( + _$ChatMessageModelImpl instance) => + { 'id': instance.id, 'data': instance.data, 'media_data': instance.mediaData, diff --git a/lib/features/chat/models/chat_messages_model.freezed.dart b/lib/features/chat/models/chat_messages_model.freezed.dart index e7900ce..a970241 100644 --- a/lib/features/chat/models/chat_messages_model.freezed.dart +++ b/lib/features/chat/models/chat_messages_model.freezed.dart @@ -26,20 +26,26 @@ mixin _$ChatMessagesModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $ChatMessagesModelCopyWith get copyWith => throw _privateConstructorUsedError; + $ChatMessagesModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatMessagesModelCopyWith<$Res> { - factory $ChatMessagesModelCopyWith(ChatMessagesModel value, $Res Function(ChatMessagesModel) then) = _$ChatMessagesModelCopyWithImpl<$Res, ChatMessagesModel>; + factory $ChatMessagesModelCopyWith( + ChatMessagesModel value, $Res Function(ChatMessagesModel) then) = + _$ChatMessagesModelCopyWithImpl<$Res, ChatMessagesModel>; @useResult - $Res call({@JsonKey(name: 'data') List messagesList, ChatMetaModel meta}); + $Res call( + {@JsonKey(name: 'data') List messagesList, + ChatMetaModel meta}); $ChatMetaModelCopyWith<$Res> get meta; } /// @nodoc -class _$ChatMessagesModelCopyWithImpl<$Res, $Val extends ChatMessagesModel> implements $ChatMessagesModelCopyWith<$Res> { +class _$ChatMessagesModelCopyWithImpl<$Res, $Val extends ChatMessagesModel> + implements $ChatMessagesModelCopyWith<$Res> { _$ChatMessagesModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -75,21 +81,28 @@ class _$ChatMessagesModelCopyWithImpl<$Res, $Val extends ChatMessagesModel> impl } /// @nodoc -abstract class _$$ChatMessagesModelImplCopyWith<$Res> implements $ChatMessagesModelCopyWith<$Res> { - factory _$$ChatMessagesModelImplCopyWith(_$ChatMessagesModelImpl value, $Res Function(_$ChatMessagesModelImpl) then) = +abstract class _$$ChatMessagesModelImplCopyWith<$Res> + implements $ChatMessagesModelCopyWith<$Res> { + factory _$$ChatMessagesModelImplCopyWith(_$ChatMessagesModelImpl value, + $Res Function(_$ChatMessagesModelImpl) then) = __$$ChatMessagesModelImplCopyWithImpl<$Res>; @override @useResult - $Res call({@JsonKey(name: 'data') List messagesList, ChatMetaModel meta}); + $Res call( + {@JsonKey(name: 'data') List messagesList, + ChatMetaModel meta}); @override $ChatMetaModelCopyWith<$Res> get meta; } /// @nodoc -class __$$ChatMessagesModelImplCopyWithImpl<$Res> extends _$ChatMessagesModelCopyWithImpl<$Res, _$ChatMessagesModelImpl> +class __$$ChatMessagesModelImplCopyWithImpl<$Res> + extends _$ChatMessagesModelCopyWithImpl<$Res, _$ChatMessagesModelImpl> implements _$$ChatMessagesModelImplCopyWith<$Res> { - __$$ChatMessagesModelImplCopyWithImpl(_$ChatMessagesModelImpl _value, $Res Function(_$ChatMessagesModelImpl) _then) : super(_value, _then); + __$$ChatMessagesModelImplCopyWithImpl(_$ChatMessagesModelImpl _value, + $Res Function(_$ChatMessagesModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -113,9 +126,14 @@ class __$$ChatMessagesModelImplCopyWithImpl<$Res> extends _$ChatMessagesModelCop /// @nodoc @JsonSerializable() class _$ChatMessagesModelImpl implements _ChatMessagesModel { - const _$ChatMessagesModelImpl({@JsonKey(name: 'data') required final List messagesList, required this.meta}) : _messagesList = messagesList; + const _$ChatMessagesModelImpl( + {@JsonKey(name: 'data') + required final List messagesList, + required this.meta}) + : _messagesList = messagesList; - factory _$ChatMessagesModelImpl.fromJson(Map json) => _$$ChatMessagesModelImplFromJson(json); + factory _$ChatMessagesModelImpl.fromJson(Map json) => + _$$ChatMessagesModelImplFromJson(json); final List _messagesList; @override @@ -139,18 +157,22 @@ class _$ChatMessagesModelImpl implements _ChatMessagesModel { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatMessagesModelImpl && - const DeepCollectionEquality().equals(other._messagesList, _messagesList) && + const DeepCollectionEquality() + .equals(other._messagesList, _messagesList) && (identical(other.meta, meta) || other.meta == meta)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_messagesList), meta); + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_messagesList), meta); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => __$$ChatMessagesModelImplCopyWithImpl<_$ChatMessagesModelImpl>(this, _$identity); + _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => + __$$ChatMessagesModelImplCopyWithImpl<_$ChatMessagesModelImpl>( + this, _$identity); @override Map toJson() { @@ -161,10 +183,13 @@ class _$ChatMessagesModelImpl implements _ChatMessagesModel { } abstract class _ChatMessagesModel implements ChatMessagesModel { - const factory _ChatMessagesModel({@JsonKey(name: 'data') required final List messagesList, required final ChatMetaModel meta}) = - _$ChatMessagesModelImpl; + const factory _ChatMessagesModel( + {@JsonKey(name: 'data') + required final List messagesList, + required final ChatMetaModel meta}) = _$ChatMessagesModelImpl; - factory _ChatMessagesModel.fromJson(Map json) = _$ChatMessagesModelImpl.fromJson; + factory _ChatMessagesModel.fromJson(Map json) = + _$ChatMessagesModelImpl.fromJson; @override @JsonKey(name: 'data') @@ -173,5 +198,6 @@ abstract class _ChatMessagesModel implements ChatMessagesModel { ChatMetaModel get meta; @override @JsonKey(ignore: true) - _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_messages_model.g.dart b/lib/features/chat/models/chat_messages_model.g.dart index 1a7fe48..6216cd8 100644 --- a/lib/features/chat/models/chat_messages_model.g.dart +++ b/lib/features/chat/models/chat_messages_model.g.dart @@ -6,12 +6,18 @@ part of 'chat_messages_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatMessagesModelImpl _$$ChatMessagesModelImplFromJson(Map json) => _$ChatMessagesModelImpl( - messagesList: (json['data'] as List).map((e) => ChatMessageModel.fromJson(e as Map)).toList(), +_$ChatMessagesModelImpl _$$ChatMessagesModelImplFromJson( + Map json) => + _$ChatMessagesModelImpl( + messagesList: (json['data'] as List) + .map((e) => ChatMessageModel.fromJson(e as Map)) + .toList(), meta: ChatMetaModel.fromJson(json['meta'] as Map), ); -Map _$$ChatMessagesModelImplToJson(_$ChatMessagesModelImpl instance) => { +Map _$$ChatMessagesModelImplToJson( + _$ChatMessagesModelImpl instance) => + { 'data': instance.messagesList, 'meta': instance.meta, }; diff --git a/lib/features/chat/models/chat_meta_model.freezed.dart b/lib/features/chat/models/chat_meta_model.freezed.dart index 91eec02..11ecb9e 100644 --- a/lib/features/chat/models/chat_meta_model.freezed.dart +++ b/lib/features/chat/models/chat_meta_model.freezed.dart @@ -25,18 +25,22 @@ mixin _$ChatMetaModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $ChatMetaModelCopyWith get copyWith => throw _privateConstructorUsedError; + $ChatMetaModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatMetaModelCopyWith<$Res> { - factory $ChatMetaModelCopyWith(ChatMetaModel value, $Res Function(ChatMetaModel) then) = _$ChatMetaModelCopyWithImpl<$Res, ChatMetaModel>; + factory $ChatMetaModelCopyWith( + ChatMetaModel value, $Res Function(ChatMetaModel) then) = + _$ChatMetaModelCopyWithImpl<$Res, ChatMetaModel>; @useResult $Res call({@JsonKey(name: "last_page") int lastPage}); } /// @nodoc -class _$ChatMetaModelCopyWithImpl<$Res, $Val extends ChatMetaModel> implements $ChatMetaModelCopyWith<$Res> { +class _$ChatMetaModelCopyWithImpl<$Res, $Val extends ChatMetaModel> + implements $ChatMetaModelCopyWith<$Res> { _$ChatMetaModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -59,16 +63,23 @@ class _$ChatMetaModelCopyWithImpl<$Res, $Val extends ChatMetaModel> implements $ } /// @nodoc -abstract class _$$ChatMetaModelImplCopyWith<$Res> implements $ChatMetaModelCopyWith<$Res> { - factory _$$ChatMetaModelImplCopyWith(_$ChatMetaModelImpl value, $Res Function(_$ChatMetaModelImpl) then) = __$$ChatMetaModelImplCopyWithImpl<$Res>; +abstract class _$$ChatMetaModelImplCopyWith<$Res> + implements $ChatMetaModelCopyWith<$Res> { + factory _$$ChatMetaModelImplCopyWith( + _$ChatMetaModelImpl value, $Res Function(_$ChatMetaModelImpl) then) = + __$$ChatMetaModelImplCopyWithImpl<$Res>; @override @useResult $Res call({@JsonKey(name: "last_page") int lastPage}); } /// @nodoc -class __$$ChatMetaModelImplCopyWithImpl<$Res> extends _$ChatMetaModelCopyWithImpl<$Res, _$ChatMetaModelImpl> implements _$$ChatMetaModelImplCopyWith<$Res> { - __$$ChatMetaModelImplCopyWithImpl(_$ChatMetaModelImpl _value, $Res Function(_$ChatMetaModelImpl) _then) : super(_value, _then); +class __$$ChatMetaModelImplCopyWithImpl<$Res> + extends _$ChatMetaModelCopyWithImpl<$Res, _$ChatMetaModelImpl> + implements _$$ChatMetaModelImplCopyWith<$Res> { + __$$ChatMetaModelImplCopyWithImpl( + _$ChatMetaModelImpl _value, $Res Function(_$ChatMetaModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -87,9 +98,11 @@ class __$$ChatMetaModelImplCopyWithImpl<$Res> extends _$ChatMetaModelCopyWithImp /// @nodoc @JsonSerializable() class _$ChatMetaModelImpl implements _ChatMetaModel { - const _$ChatMetaModelImpl({@JsonKey(name: "last_page") required this.lastPage}); + const _$ChatMetaModelImpl( + {@JsonKey(name: "last_page") required this.lastPage}); - factory _$ChatMetaModelImpl.fromJson(Map json) => _$$ChatMetaModelImplFromJson(json); + factory _$ChatMetaModelImpl.fromJson(Map json) => + _$$ChatMetaModelImplFromJson(json); @override @JsonKey(name: "last_page") @@ -103,7 +116,10 @@ class _$ChatMetaModelImpl implements _ChatMetaModel { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && other is _$ChatMetaModelImpl && (identical(other.lastPage, lastPage) || other.lastPage == lastPage)); + (other.runtimeType == runtimeType && + other is _$ChatMetaModelImpl && + (identical(other.lastPage, lastPage) || + other.lastPage == lastPage)); } @JsonKey(ignore: true) @@ -113,7 +129,8 @@ class _$ChatMetaModelImpl implements _ChatMetaModel { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => __$$ChatMetaModelImplCopyWithImpl<_$ChatMetaModelImpl>(this, _$identity); + _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => + __$$ChatMetaModelImplCopyWithImpl<_$ChatMetaModelImpl>(this, _$identity); @override Map toJson() { @@ -124,14 +141,18 @@ class _$ChatMetaModelImpl implements _ChatMetaModel { } abstract class _ChatMetaModel implements ChatMetaModel { - const factory _ChatMetaModel({@JsonKey(name: "last_page") required final int lastPage}) = _$ChatMetaModelImpl; + const factory _ChatMetaModel( + {@JsonKey(name: "last_page") required final int lastPage}) = + _$ChatMetaModelImpl; - factory _ChatMetaModel.fromJson(Map json) = _$ChatMetaModelImpl.fromJson; + factory _ChatMetaModel.fromJson(Map json) = + _$ChatMetaModelImpl.fromJson; @override @JsonKey(name: "last_page") int get lastPage; @override @JsonKey(ignore: true) - _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_meta_model.g.dart b/lib/features/chat/models/chat_meta_model.g.dart index bbd16d1..7126e2d 100644 --- a/lib/features/chat/models/chat_meta_model.g.dart +++ b/lib/features/chat/models/chat_meta_model.g.dart @@ -6,10 +6,12 @@ part of 'chat_meta_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatMetaModelImpl _$$ChatMetaModelImplFromJson(Map json) => _$ChatMetaModelImpl( +_$ChatMetaModelImpl _$$ChatMetaModelImplFromJson(Map json) => + _$ChatMetaModelImpl( lastPage: (json['last_page'] as num).toInt(), ); -Map _$$ChatMetaModelImplToJson(_$ChatMetaModelImpl instance) => { +Map _$$ChatMetaModelImplToJson(_$ChatMetaModelImpl instance) => + { 'last_page': instance.lastPage, }; diff --git a/lib/features/chat/models/chat_room_model.freezed.dart b/lib/features/chat/models/chat_room_model.freezed.dart index 216c1b6..5a0b6e6 100644 --- a/lib/features/chat/models/chat_room_model.freezed.dart +++ b/lib/features/chat/models/chat_room_model.freezed.dart @@ -22,25 +22,34 @@ ChatRoomModel _$ChatRoomModelFromJson(Map json) { mixin _$ChatRoomModel { String get id => throw _privateConstructorUsedError; @JsonKey(name: 'chat_room_setting') - ChatRoomSettingsModel get chatRoomSettings => throw _privateConstructorUsedError; + ChatRoomSettingsModel get chatRoomSettings => + throw _privateConstructorUsedError; Map get users => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $ChatRoomModelCopyWith get copyWith => throw _privateConstructorUsedError; + $ChatRoomModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatRoomModelCopyWith<$Res> { - factory $ChatRoomModelCopyWith(ChatRoomModel value, $Res Function(ChatRoomModel) then) = _$ChatRoomModelCopyWithImpl<$Res, ChatRoomModel>; + factory $ChatRoomModelCopyWith( + ChatRoomModel value, $Res Function(ChatRoomModel) then) = + _$ChatRoomModelCopyWithImpl<$Res, ChatRoomModel>; @useResult - $Res call({String id, @JsonKey(name: 'chat_room_setting') ChatRoomSettingsModel chatRoomSettings, Map users}); + $Res call( + {String id, + @JsonKey(name: 'chat_room_setting') + ChatRoomSettingsModel chatRoomSettings, + Map users}); $ChatRoomSettingsModelCopyWith<$Res> get chatRoomSettings; } /// @nodoc -class _$ChatRoomModelCopyWithImpl<$Res, $Val extends ChatRoomModel> implements $ChatRoomModelCopyWith<$Res> { +class _$ChatRoomModelCopyWithImpl<$Res, $Val extends ChatRoomModel> + implements $ChatRoomModelCopyWith<$Res> { _$ChatRoomModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -74,26 +83,38 @@ class _$ChatRoomModelCopyWithImpl<$Res, $Val extends ChatRoomModel> implements $ @override @pragma('vm:prefer-inline') $ChatRoomSettingsModelCopyWith<$Res> get chatRoomSettings { - return $ChatRoomSettingsModelCopyWith<$Res>(_value.chatRoomSettings, (value) { + return $ChatRoomSettingsModelCopyWith<$Res>(_value.chatRoomSettings, + (value) { return _then(_value.copyWith(chatRoomSettings: value) as $Val); }); } } /// @nodoc -abstract class _$$ChatRoomModelImplCopyWith<$Res> implements $ChatRoomModelCopyWith<$Res> { - factory _$$ChatRoomModelImplCopyWith(_$ChatRoomModelImpl value, $Res Function(_$ChatRoomModelImpl) then) = __$$ChatRoomModelImplCopyWithImpl<$Res>; +abstract class _$$ChatRoomModelImplCopyWith<$Res> + implements $ChatRoomModelCopyWith<$Res> { + factory _$$ChatRoomModelImplCopyWith( + _$ChatRoomModelImpl value, $Res Function(_$ChatRoomModelImpl) then) = + __$$ChatRoomModelImplCopyWithImpl<$Res>; @override @useResult - $Res call({String id, @JsonKey(name: 'chat_room_setting') ChatRoomSettingsModel chatRoomSettings, Map users}); + $Res call( + {String id, + @JsonKey(name: 'chat_room_setting') + ChatRoomSettingsModel chatRoomSettings, + Map users}); @override $ChatRoomSettingsModelCopyWith<$Res> get chatRoomSettings; } /// @nodoc -class __$$ChatRoomModelImplCopyWithImpl<$Res> extends _$ChatRoomModelCopyWithImpl<$Res, _$ChatRoomModelImpl> implements _$$ChatRoomModelImplCopyWith<$Res> { - __$$ChatRoomModelImplCopyWithImpl(_$ChatRoomModelImpl _value, $Res Function(_$ChatRoomModelImpl) _then) : super(_value, _then); +class __$$ChatRoomModelImplCopyWithImpl<$Res> + extends _$ChatRoomModelCopyWithImpl<$Res, _$ChatRoomModelImpl> + implements _$$ChatRoomModelImplCopyWith<$Res> { + __$$ChatRoomModelImplCopyWithImpl( + _$ChatRoomModelImpl _value, $Res Function(_$ChatRoomModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -123,10 +144,13 @@ class __$$ChatRoomModelImplCopyWithImpl<$Res> extends _$ChatRoomModelCopyWithImp @JsonSerializable() class _$ChatRoomModelImpl implements _ChatRoomModel { const _$ChatRoomModelImpl( - {required this.id, @JsonKey(name: 'chat_room_setting') required this.chatRoomSettings, required final Map users}) + {required this.id, + @JsonKey(name: 'chat_room_setting') required this.chatRoomSettings, + required final Map users}) : _users = users; - factory _$ChatRoomModelImpl.fromJson(Map json) => _$$ChatRoomModelImplFromJson(json); + factory _$ChatRoomModelImpl.fromJson(Map json) => + _$$ChatRoomModelImplFromJson(json); @override final String id; @@ -152,18 +176,21 @@ class _$ChatRoomModelImpl implements _ChatRoomModel { (other.runtimeType == runtimeType && other is _$ChatRoomModelImpl && (identical(other.id, id) || other.id == id) && - (identical(other.chatRoomSettings, chatRoomSettings) || other.chatRoomSettings == chatRoomSettings) && + (identical(other.chatRoomSettings, chatRoomSettings) || + other.chatRoomSettings == chatRoomSettings) && const DeepCollectionEquality().equals(other._users, _users)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, chatRoomSettings, const DeepCollectionEquality().hash(_users)); + int get hashCode => Object.hash(runtimeType, id, chatRoomSettings, + const DeepCollectionEquality().hash(_users)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => __$$ChatRoomModelImplCopyWithImpl<_$ChatRoomModelImpl>(this, _$identity); + _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => + __$$ChatRoomModelImplCopyWithImpl<_$ChatRoomModelImpl>(this, _$identity); @override Map toJson() { @@ -176,10 +203,12 @@ class _$ChatRoomModelImpl implements _ChatRoomModel { abstract class _ChatRoomModel implements ChatRoomModel { const factory _ChatRoomModel( {required final String id, - @JsonKey(name: 'chat_room_setting') required final ChatRoomSettingsModel chatRoomSettings, + @JsonKey(name: 'chat_room_setting') + required final ChatRoomSettingsModel chatRoomSettings, required final Map users}) = _$ChatRoomModelImpl; - factory _ChatRoomModel.fromJson(Map json) = _$ChatRoomModelImpl.fromJson; + factory _ChatRoomModel.fromJson(Map json) = + _$ChatRoomModelImpl.fromJson; @override String get id; @@ -190,5 +219,6 @@ abstract class _ChatRoomModel implements ChatRoomModel { Map get users; @override @JsonKey(ignore: true) - _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_room_model.g.dart b/lib/features/chat/models/chat_room_model.g.dart index 6230d4f..68d3195 100644 --- a/lib/features/chat/models/chat_room_model.g.dart +++ b/lib/features/chat/models/chat_room_model.g.dart @@ -6,15 +6,19 @@ part of 'chat_room_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatRoomModelImpl _$$ChatRoomModelImplFromJson(Map json) => _$ChatRoomModelImpl( +_$ChatRoomModelImpl _$$ChatRoomModelImplFromJson(Map json) => + _$ChatRoomModelImpl( id: json['id'] as String, - chatRoomSettings: ChatRoomSettingsModel.fromJson(json['chat_room_setting'] as Map), + chatRoomSettings: ChatRoomSettingsModel.fromJson( + json['chat_room_setting'] as Map), users: (json['users'] as Map).map( - (k, e) => MapEntry(k, ChatUserModel.fromJson(e as Map)), + (k, e) => + MapEntry(k, ChatUserModel.fromJson(e as Map)), ), ); -Map _$$ChatRoomModelImplToJson(_$ChatRoomModelImpl instance) => { +Map _$$ChatRoomModelImplToJson(_$ChatRoomModelImpl instance) => + { 'id': instance.id, 'chat_room_setting': instance.chatRoomSettings, 'users': instance.users, diff --git a/lib/features/chat/models/chat_room_settings_model.freezed.dart b/lib/features/chat/models/chat_room_settings_model.freezed.dart index af23772..4f21755 100644 --- a/lib/features/chat/models/chat_room_settings_model.freezed.dart +++ b/lib/features/chat/models/chat_room_settings_model.freezed.dart @@ -14,7 +14,8 @@ 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'); -ChatRoomSettingsModel _$ChatRoomSettingsModelFromJson(Map json) { +ChatRoomSettingsModel _$ChatRoomSettingsModelFromJson( + Map json) { return _ChatRoomSettingsModel.fromJson(json); } @@ -31,12 +32,14 @@ mixin _$ChatRoomSettingsModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $ChatRoomSettingsModelCopyWith get copyWith => throw _privateConstructorUsedError; + $ChatRoomSettingsModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatRoomSettingsModelCopyWith<$Res> { - factory $ChatRoomSettingsModelCopyWith(ChatRoomSettingsModel value, $Res Function(ChatRoomSettingsModel) then) = + factory $ChatRoomSettingsModelCopyWith(ChatRoomSettingsModel value, + $Res Function(ChatRoomSettingsModel) then) = _$ChatRoomSettingsModelCopyWithImpl<$Res, ChatRoomSettingsModel>; @useResult $Res call( @@ -48,7 +51,9 @@ abstract class $ChatRoomSettingsModelCopyWith<$Res> { } /// @nodoc -class _$ChatRoomSettingsModelCopyWithImpl<$Res, $Val extends ChatRoomSettingsModel> implements $ChatRoomSettingsModelCopyWith<$Res> { +class _$ChatRoomSettingsModelCopyWithImpl<$Res, + $Val extends ChatRoomSettingsModel> + implements $ChatRoomSettingsModelCopyWith<$Res> { _$ChatRoomSettingsModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -91,8 +96,11 @@ class _$ChatRoomSettingsModelCopyWithImpl<$Res, $Val extends ChatRoomSettingsMod } /// @nodoc -abstract class _$$ChatRoomSettingsModelImplCopyWith<$Res> implements $ChatRoomSettingsModelCopyWith<$Res> { - factory _$$ChatRoomSettingsModelImplCopyWith(_$ChatRoomSettingsModelImpl value, $Res Function(_$ChatRoomSettingsModelImpl) then) = +abstract class _$$ChatRoomSettingsModelImplCopyWith<$Res> + implements $ChatRoomSettingsModelCopyWith<$Res> { + factory _$$ChatRoomSettingsModelImplCopyWith( + _$ChatRoomSettingsModelImpl value, + $Res Function(_$ChatRoomSettingsModelImpl) then) = __$$ChatRoomSettingsModelImplCopyWithImpl<$Res>; @override @useResult @@ -105,9 +113,13 @@ abstract class _$$ChatRoomSettingsModelImplCopyWith<$Res> implements $ChatRoomSe } /// @nodoc -class __$$ChatRoomSettingsModelImplCopyWithImpl<$Res> extends _$ChatRoomSettingsModelCopyWithImpl<$Res, _$ChatRoomSettingsModelImpl> +class __$$ChatRoomSettingsModelImplCopyWithImpl<$Res> + extends _$ChatRoomSettingsModelCopyWithImpl<$Res, + _$ChatRoomSettingsModelImpl> implements _$$ChatRoomSettingsModelImplCopyWith<$Res> { - __$$ChatRoomSettingsModelImplCopyWithImpl(_$ChatRoomSettingsModelImpl _value, $Res Function(_$ChatRoomSettingsModelImpl) _then) : super(_value, _then); + __$$ChatRoomSettingsModelImplCopyWithImpl(_$ChatRoomSettingsModelImpl _value, + $Res Function(_$ChatRoomSettingsModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -153,7 +165,8 @@ class _$ChatRoomSettingsModelImpl implements _ChatRoomSettingsModel { @JsonKey(name: 'access_level') required this.accessLevel, @JsonKey(name: 'updated_at') required this.updatedAt}); - factory _$ChatRoomSettingsModelImpl.fromJson(Map json) => _$$ChatRoomSettingsModelImplFromJson(json); + factory _$ChatRoomSettingsModelImpl.fromJson(Map json) => + _$$ChatRoomSettingsModelImplFromJson(json); @override final int id; @@ -180,21 +193,26 @@ class _$ChatRoomSettingsModelImpl implements _ChatRoomSettingsModel { (other.runtimeType == runtimeType && other is _$ChatRoomSettingsModelImpl && (identical(other.id, id) || other.id == id) && - (identical(other.roomName, roomName) || other.roomName == roomName) && + (identical(other.roomName, roomName) || + other.roomName == roomName) && (identical(other.state, state) || other.state == state) && - (identical(other.accessLevel, accessLevel) || other.accessLevel == accessLevel) && - (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)); + (identical(other.accessLevel, accessLevel) || + other.accessLevel == accessLevel) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, roomName, state, accessLevel, updatedAt); + int get hashCode => + Object.hash(runtimeType, id, roomName, state, accessLevel, updatedAt); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> get copyWith => - __$$ChatRoomSettingsModelImplCopyWithImpl<_$ChatRoomSettingsModelImpl>(this, _$identity); + _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> + get copyWith => __$$ChatRoomSettingsModelImplCopyWithImpl< + _$ChatRoomSettingsModelImpl>(this, _$identity); @override Map toJson() { @@ -206,13 +224,15 @@ class _$ChatRoomSettingsModelImpl implements _ChatRoomSettingsModel { abstract class _ChatRoomSettingsModel implements ChatRoomSettingsModel { const factory _ChatRoomSettingsModel( - {required final int id, - @JsonKey(name: 'room_name') required final String roomName, - required final String state, - @JsonKey(name: 'access_level') required final String accessLevel, - @JsonKey(name: 'updated_at') required final String updatedAt}) = _$ChatRoomSettingsModelImpl; + {required final int id, + @JsonKey(name: 'room_name') required final String roomName, + required final String state, + @JsonKey(name: 'access_level') required final String accessLevel, + @JsonKey(name: 'updated_at') required final String updatedAt}) = + _$ChatRoomSettingsModelImpl; - factory _ChatRoomSettingsModel.fromJson(Map json) = _$ChatRoomSettingsModelImpl.fromJson; + factory _ChatRoomSettingsModel.fromJson(Map json) = + _$ChatRoomSettingsModelImpl.fromJson; @override int get id; @@ -229,5 +249,6 @@ abstract class _ChatRoomSettingsModel implements ChatRoomSettingsModel { String get updatedAt; @override @JsonKey(ignore: true) - _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> + get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_room_settings_model.g.dart b/lib/features/chat/models/chat_room_settings_model.g.dart index 1a2ef32..7b82433 100644 --- a/lib/features/chat/models/chat_room_settings_model.g.dart +++ b/lib/features/chat/models/chat_room_settings_model.g.dart @@ -6,7 +6,9 @@ part of 'chat_room_settings_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatRoomSettingsModelImpl _$$ChatRoomSettingsModelImplFromJson(Map json) => _$ChatRoomSettingsModelImpl( +_$ChatRoomSettingsModelImpl _$$ChatRoomSettingsModelImplFromJson( + Map json) => + _$ChatRoomSettingsModelImpl( id: (json['id'] as num).toInt(), roomName: json['room_name'] as String, state: json['state'] as String, @@ -14,7 +16,9 @@ _$ChatRoomSettingsModelImpl _$$ChatRoomSettingsModelImplFromJson(Map _$$ChatRoomSettingsModelImplToJson(_$ChatRoomSettingsModelImpl instance) => { +Map _$$ChatRoomSettingsModelImplToJson( + _$ChatRoomSettingsModelImpl instance) => + { 'id': instance.id, 'room_name': instance.roomName, 'state': instance.state, diff --git a/lib/features/chat/models/chat_user_model.freezed.dart b/lib/features/chat/models/chat_user_model.freezed.dart index 2827fa1..095c09e 100644 --- a/lib/features/chat/models/chat_user_model.freezed.dart +++ b/lib/features/chat/models/chat_user_model.freezed.dart @@ -29,18 +29,26 @@ mixin _$ChatUserModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $ChatUserModelCopyWith get copyWith => throw _privateConstructorUsedError; + $ChatUserModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatUserModelCopyWith<$Res> { - factory $ChatUserModelCopyWith(ChatUserModel value, $Res Function(ChatUserModel) then) = _$ChatUserModelCopyWithImpl<$Res, ChatUserModel>; + factory $ChatUserModelCopyWith( + ChatUserModel value, $Res Function(ChatUserModel) then) = + _$ChatUserModelCopyWithImpl<$Res, ChatUserModel>; @useResult - $Res call({int id, String name, @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); + $Res call( + {int id, + String name, + @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, + @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); } /// @nodoc -class _$ChatUserModelCopyWithImpl<$Res, $Val extends ChatUserModel> implements $ChatUserModelCopyWith<$Res> { +class _$ChatUserModelCopyWithImpl<$Res, $Val extends ChatUserModel> + implements $ChatUserModelCopyWith<$Res> { _$ChatUserModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -78,16 +86,27 @@ class _$ChatUserModelCopyWithImpl<$Res, $Val extends ChatUserModel> implements $ } /// @nodoc -abstract class _$$ChatUserModelImplCopyWith<$Res> implements $ChatUserModelCopyWith<$Res> { - factory _$$ChatUserModelImplCopyWith(_$ChatUserModelImpl value, $Res Function(_$ChatUserModelImpl) then) = __$$ChatUserModelImplCopyWithImpl<$Res>; +abstract class _$$ChatUserModelImplCopyWith<$Res> + implements $ChatUserModelCopyWith<$Res> { + factory _$$ChatUserModelImplCopyWith( + _$ChatUserModelImpl value, $Res Function(_$ChatUserModelImpl) then) = + __$$ChatUserModelImplCopyWithImpl<$Res>; @override @useResult - $Res call({int id, String name, @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); + $Res call( + {int id, + String name, + @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, + @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); } /// @nodoc -class __$$ChatUserModelImplCopyWithImpl<$Res> extends _$ChatUserModelCopyWithImpl<$Res, _$ChatUserModelImpl> implements _$$ChatUserModelImplCopyWith<$Res> { - __$$ChatUserModelImplCopyWithImpl(_$ChatUserModelImpl _value, $Res Function(_$ChatUserModelImpl) _then) : super(_value, _then); +class __$$ChatUserModelImplCopyWithImpl<$Res> + extends _$ChatUserModelCopyWithImpl<$Res, _$ChatUserModelImpl> + implements _$$ChatUserModelImplCopyWith<$Res> { + __$$ChatUserModelImplCopyWithImpl( + _$ChatUserModelImpl _value, $Res Function(_$ChatUserModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -127,7 +146,8 @@ class _$ChatUserModelImpl implements _ChatUserModel { @JsonKey(name: 'profile_photo_path') this.profilePhotoPath, @JsonKey(name: 'profile_photo_url') this.profilePhotoUrl}); - factory _$ChatUserModelImpl.fromJson(Map json) => _$$ChatUserModelImplFromJson(json); + factory _$ChatUserModelImpl.fromJson(Map json) => + _$$ChatUserModelImplFromJson(json); @override final int id; @@ -152,18 +172,22 @@ class _$ChatUserModelImpl implements _ChatUserModel { other is _$ChatUserModelImpl && (identical(other.id, id) || other.id == id) && (identical(other.name, name) || other.name == name) && - (identical(other.profilePhotoPath, profilePhotoPath) || other.profilePhotoPath == profilePhotoPath) && - (identical(other.profilePhotoUrl, profilePhotoUrl) || other.profilePhotoUrl == profilePhotoUrl)); + (identical(other.profilePhotoPath, profilePhotoPath) || + other.profilePhotoPath == profilePhotoPath) && + (identical(other.profilePhotoUrl, profilePhotoUrl) || + other.profilePhotoUrl == profilePhotoUrl)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, name, profilePhotoPath, profilePhotoUrl); + int get hashCode => + Object.hash(runtimeType, id, name, profilePhotoPath, profilePhotoUrl); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => __$$ChatUserModelImplCopyWithImpl<_$ChatUserModelImpl>(this, _$identity); + _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => + __$$ChatUserModelImplCopyWithImpl<_$ChatUserModelImpl>(this, _$identity); @override Map toJson() { @@ -175,12 +199,14 @@ class _$ChatUserModelImpl implements _ChatUserModel { abstract class _ChatUserModel implements ChatUserModel { const factory _ChatUserModel( - {required final int id, - required final String name, - @JsonKey(name: 'profile_photo_path') final String? profilePhotoPath, - @JsonKey(name: 'profile_photo_url') final String? profilePhotoUrl}) = _$ChatUserModelImpl; + {required final int id, + required final String name, + @JsonKey(name: 'profile_photo_path') final String? profilePhotoPath, + @JsonKey(name: 'profile_photo_url') final String? profilePhotoUrl}) = + _$ChatUserModelImpl; - factory _ChatUserModel.fromJson(Map json) = _$ChatUserModelImpl.fromJson; + factory _ChatUserModel.fromJson(Map json) = + _$ChatUserModelImpl.fromJson; @override int get id; @@ -194,5 +220,6 @@ abstract class _ChatUserModel implements ChatUserModel { String? get profilePhotoUrl; @override @JsonKey(ignore: true) - _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_user_model.g.dart b/lib/features/chat/models/chat_user_model.g.dart index 06fa92a..78e0f98 100644 --- a/lib/features/chat/models/chat_user_model.g.dart +++ b/lib/features/chat/models/chat_user_model.g.dart @@ -6,14 +6,16 @@ part of 'chat_user_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatUserModelImpl _$$ChatUserModelImplFromJson(Map json) => _$ChatUserModelImpl( +_$ChatUserModelImpl _$$ChatUserModelImplFromJson(Map json) => + _$ChatUserModelImpl( id: (json['id'] as num).toInt(), name: json['name'] as String, profilePhotoPath: json['profile_photo_path'] as String?, profilePhotoUrl: json['profile_photo_url'] as String?, ); -Map _$$ChatUserModelImplToJson(_$ChatUserModelImpl instance) => { +Map _$$ChatUserModelImplToJson(_$ChatUserModelImpl instance) => + { 'id': instance.id, 'name': instance.name, 'profile_photo_path': instance.profilePhotoPath, diff --git a/lib/features/chat/models/websocket_info_model.freezed.dart b/lib/features/chat/models/websocket_info_model.freezed.dart index 2f50540..cd383a2 100644 --- a/lib/features/chat/models/websocket_info_model.freezed.dart +++ b/lib/features/chat/models/websocket_info_model.freezed.dart @@ -29,19 +29,27 @@ mixin _$WebsocketInfoModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $WebsocketInfoModelCopyWith get copyWith => throw _privateConstructorUsedError; + $WebsocketInfoModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $WebsocketInfoModelCopyWith<$Res> { - factory $WebsocketInfoModelCopyWith(WebsocketInfoModel value, $Res Function(WebsocketInfoModel) then) = + factory $WebsocketInfoModelCopyWith( + WebsocketInfoModel value, $Res Function(WebsocketInfoModel) then) = _$WebsocketInfoModelCopyWithImpl<$Res, WebsocketInfoModel>; @useResult - $Res call({String key, String host, String port, String cluster, @JsonKey(name: 'user_id') int userId}); + $Res call( + {String key, + String host, + String port, + String cluster, + @JsonKey(name: 'user_id') int userId}); } /// @nodoc -class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel> implements $WebsocketInfoModelCopyWith<$Res> { +class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel> + implements $WebsocketInfoModelCopyWith<$Res> { _$WebsocketInfoModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -84,18 +92,28 @@ class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel> im } /// @nodoc -abstract class _$$WebsocketInfoModelImplCopyWith<$Res> implements $WebsocketInfoModelCopyWith<$Res> { - factory _$$WebsocketInfoModelImplCopyWith(_$WebsocketInfoModelImpl value, $Res Function(_$WebsocketInfoModelImpl) then) = +abstract class _$$WebsocketInfoModelImplCopyWith<$Res> + implements $WebsocketInfoModelCopyWith<$Res> { + factory _$$WebsocketInfoModelImplCopyWith(_$WebsocketInfoModelImpl value, + $Res Function(_$WebsocketInfoModelImpl) then) = __$$WebsocketInfoModelImplCopyWithImpl<$Res>; @override @useResult - $Res call({String key, String host, String port, String cluster, @JsonKey(name: 'user_id') int userId}); + $Res call( + {String key, + String host, + String port, + String cluster, + @JsonKey(name: 'user_id') int userId}); } /// @nodoc -class __$$WebsocketInfoModelImplCopyWithImpl<$Res> extends _$WebsocketInfoModelCopyWithImpl<$Res, _$WebsocketInfoModelImpl> +class __$$WebsocketInfoModelImplCopyWithImpl<$Res> + extends _$WebsocketInfoModelCopyWithImpl<$Res, _$WebsocketInfoModelImpl> implements _$$WebsocketInfoModelImplCopyWith<$Res> { - __$$WebsocketInfoModelImplCopyWithImpl(_$WebsocketInfoModelImpl _value, $Res Function(_$WebsocketInfoModelImpl) _then) : super(_value, _then); + __$$WebsocketInfoModelImplCopyWithImpl(_$WebsocketInfoModelImpl _value, + $Res Function(_$WebsocketInfoModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -135,9 +153,14 @@ class __$$WebsocketInfoModelImplCopyWithImpl<$Res> extends _$WebsocketInfoModelC @JsonSerializable() class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { const _$WebsocketInfoModelImpl( - {required this.key, required this.host, required this.port, required this.cluster, @JsonKey(name: 'user_id') required this.userId}); + {required this.key, + required this.host, + required this.port, + required this.cluster, + @JsonKey(name: 'user_id') required this.userId}); - factory _$WebsocketInfoModelImpl.fromJson(Map json) => _$$WebsocketInfoModelImplFromJson(json); + factory _$WebsocketInfoModelImpl.fromJson(Map json) => + _$$WebsocketInfoModelImplFromJson(json); @override final String key; @@ -170,13 +193,15 @@ class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, key, host, port, cluster, userId); + int get hashCode => + Object.hash(runtimeType, key, host, port, cluster, userId); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith => - __$$WebsocketInfoModelImplCopyWithImpl<_$WebsocketInfoModelImpl>(this, _$identity); + __$$WebsocketInfoModelImplCopyWithImpl<_$WebsocketInfoModelImpl>( + this, _$identity); @override Map toJson() { @@ -188,13 +213,15 @@ class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { abstract class _WebsocketInfoModel implements WebsocketInfoModel { const factory _WebsocketInfoModel( - {required final String key, - required final String host, - required final String port, - required final String cluster, - @JsonKey(name: 'user_id') required final int userId}) = _$WebsocketInfoModelImpl; + {required final String key, + required final String host, + required final String port, + required final String cluster, + @JsonKey(name: 'user_id') required final int userId}) = + _$WebsocketInfoModelImpl; - factory _WebsocketInfoModel.fromJson(Map json) = _$WebsocketInfoModelImpl.fromJson; + factory _WebsocketInfoModel.fromJson(Map json) = + _$WebsocketInfoModelImpl.fromJson; @override String get key; @@ -209,5 +236,6 @@ abstract class _WebsocketInfoModel implements WebsocketInfoModel { int get userId; @override @JsonKey(ignore: true) - _$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/websocket_info_model.g.dart b/lib/features/chat/models/websocket_info_model.g.dart index 91c386f..b2bb124 100644 --- a/lib/features/chat/models/websocket_info_model.g.dart +++ b/lib/features/chat/models/websocket_info_model.g.dart @@ -6,7 +6,9 @@ part of 'websocket_info_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson(Map json) => _$WebsocketInfoModelImpl( +_$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson( + Map json) => + _$WebsocketInfoModelImpl( key: json['key'] as String, host: json['host'] as String, port: json['port'] as String, @@ -14,7 +16,9 @@ _$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson(Map userId: (json['user_id'] as num).toInt(), ); -Map _$$WebsocketInfoModelImplToJson(_$WebsocketInfoModelImpl instance) => { +Map _$$WebsocketInfoModelImplToJson( + _$WebsocketInfoModelImpl instance) => + { 'key': instance.key, 'host': instance.host, 'port': instance.port, diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart index 715c1ab..43bf9df 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart @@ -20,7 +20,9 @@ mixin _$ChatRoomState { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, + required TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading) + loaded, required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; @@ -28,7 +30,9 @@ mixin _$ChatRoomState { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult? Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult? Function(String errorMessage)? error, }) => throw _privateConstructorUsedError; @@ -36,7 +40,9 @@ mixin _$ChatRoomState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) => @@ -70,11 +76,14 @@ mixin _$ChatRoomState { /// @nodoc abstract class $ChatRoomStateCopyWith<$Res> { - factory $ChatRoomStateCopyWith(ChatRoomState value, $Res Function(ChatRoomState) then) = _$ChatRoomStateCopyWithImpl<$Res, ChatRoomState>; + factory $ChatRoomStateCopyWith( + ChatRoomState value, $Res Function(ChatRoomState) then) = + _$ChatRoomStateCopyWithImpl<$Res, ChatRoomState>; } /// @nodoc -class _$ChatRoomStateCopyWithImpl<$Res, $Val extends ChatRoomState> implements $ChatRoomStateCopyWith<$Res> { +class _$ChatRoomStateCopyWithImpl<$Res, $Val extends ChatRoomState> + implements $ChatRoomStateCopyWith<$Res> { _$ChatRoomStateCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -85,12 +94,18 @@ class _$ChatRoomStateCopyWithImpl<$Res, $Val extends ChatRoomState> implements $ /// @nodoc abstract class _$$ChatRoomStateImplCopyWith<$Res> { - factory _$$ChatRoomStateImplCopyWith(_$ChatRoomStateImpl value, $Res Function(_$ChatRoomStateImpl) then) = __$$ChatRoomStateImplCopyWithImpl<$Res>; + factory _$$ChatRoomStateImplCopyWith( + _$ChatRoomStateImpl value, $Res Function(_$ChatRoomStateImpl) then) = + __$$ChatRoomStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$ChatRoomStateImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateImpl> implements _$$ChatRoomStateImplCopyWith<$Res> { - __$$ChatRoomStateImplCopyWithImpl(_$ChatRoomStateImpl _value, $Res Function(_$ChatRoomStateImpl) _then) : super(_value, _then); +class __$$ChatRoomStateImplCopyWithImpl<$Res> + extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateImpl> + implements _$$ChatRoomStateImplCopyWith<$Res> { + __$$ChatRoomStateImplCopyWithImpl( + _$ChatRoomStateImpl _value, $Res Function(_$ChatRoomStateImpl) _then) + : super(_value, _then); } /// @nodoc @@ -105,7 +120,8 @@ class _$ChatRoomStateImpl implements _ChatRoomState { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$ChatRoomStateImpl); } @override @@ -116,7 +132,9 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, + required TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading) + loaded, required TResult Function(String errorMessage) error, }) { return $default(); @@ -127,7 +145,9 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult? Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult? Function(String errorMessage)? error, }) { return $default?.call(); @@ -138,7 +158,9 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -192,14 +214,18 @@ abstract class _ChatRoomState implements ChatRoomState { /// @nodoc abstract class _$$ChatRoomStateLoadingImplCopyWith<$Res> { - factory _$$ChatRoomStateLoadingImplCopyWith(_$ChatRoomStateLoadingImpl value, $Res Function(_$ChatRoomStateLoadingImpl) then) = + factory _$$ChatRoomStateLoadingImplCopyWith(_$ChatRoomStateLoadingImpl value, + $Res Function(_$ChatRoomStateLoadingImpl) then) = __$$ChatRoomStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$ChatRoomStateLoadingImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadingImpl> +class __$$ChatRoomStateLoadingImplCopyWithImpl<$Res> + extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadingImpl> implements _$$ChatRoomStateLoadingImplCopyWith<$Res> { - __$$ChatRoomStateLoadingImplCopyWithImpl(_$ChatRoomStateLoadingImpl _value, $Res Function(_$ChatRoomStateLoadingImpl) _then) : super(_value, _then); + __$$ChatRoomStateLoadingImplCopyWithImpl(_$ChatRoomStateLoadingImpl _value, + $Res Function(_$ChatRoomStateLoadingImpl) _then) + : super(_value, _then); } /// @nodoc @@ -214,7 +240,9 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateLoadingImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ChatRoomStateLoadingImpl); } @override @@ -225,7 +253,9 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, + required TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading) + loaded, required TResult Function(String errorMessage) error, }) { return loading(); @@ -236,7 +266,9 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult? Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult? Function(String errorMessage)? error, }) { return loading?.call(); @@ -247,7 +279,9 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -301,18 +335,26 @@ abstract class ChatRoomStateLoading implements ChatRoomState { /// @nodoc abstract class _$$ChatRoomStateLoadedImplCopyWith<$Res> { - factory _$$ChatRoomStateLoadedImplCopyWith(_$ChatRoomStateLoadedImpl value, $Res Function(_$ChatRoomStateLoadedImpl) then) = + factory _$$ChatRoomStateLoadedImplCopyWith(_$ChatRoomStateLoadedImpl value, + $Res Function(_$ChatRoomStateLoadedImpl) then) = __$$ChatRoomStateLoadedImplCopyWithImpl<$Res>; @useResult - $Res call({ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading}); + $Res call( + {ChatRoomModel chatRoom, + List chatMessages, + bool isTyping, + bool isLoading}); $ChatRoomModelCopyWith<$Res> get chatRoom; } /// @nodoc -class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadedImpl> +class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> + extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadedImpl> implements _$$ChatRoomStateLoadedImplCopyWith<$Res> { - __$$ChatRoomStateLoadedImplCopyWithImpl(_$ChatRoomStateLoadedImpl _value, $Res Function(_$ChatRoomStateLoadedImpl) _then) : super(_value, _then); + __$$ChatRoomStateLoadedImplCopyWithImpl(_$ChatRoomStateLoadedImpl _value, + $Res Function(_$ChatRoomStateLoadedImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -354,7 +396,11 @@ class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyW /// @nodoc class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { - const _$ChatRoomStateLoadedImpl({required this.chatRoom, required final List chatMessages, required this.isTyping, required this.isLoading}) + const _$ChatRoomStateLoadedImpl( + {required this.chatRoom, + required final List chatMessages, + required this.isTyping, + required this.isLoading}) : _chatMessages = chatMessages; @override @@ -382,27 +428,35 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateLoadedImpl && - (identical(other.chatRoom, chatRoom) || other.chatRoom == chatRoom) && - const DeepCollectionEquality().equals(other._chatMessages, _chatMessages) && - (identical(other.isTyping, isTyping) || other.isTyping == isTyping) && - (identical(other.isLoading, isLoading) || other.isLoading == isLoading)); + (identical(other.chatRoom, chatRoom) || + other.chatRoom == chatRoom) && + const DeepCollectionEquality() + .equals(other._chatMessages, _chatMessages) && + (identical(other.isTyping, isTyping) || + other.isTyping == isTyping) && + (identical(other.isLoading, isLoading) || + other.isLoading == isLoading)); } @override - int get hashCode => Object.hash(runtimeType, chatRoom, const DeepCollectionEquality().hash(_chatMessages), isTyping, isLoading); + int get hashCode => Object.hash(runtimeType, chatRoom, + const DeepCollectionEquality().hash(_chatMessages), isTyping, isLoading); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$ChatRoomStateLoadedImplCopyWith<_$ChatRoomStateLoadedImpl> get copyWith => - __$$ChatRoomStateLoadedImplCopyWithImpl<_$ChatRoomStateLoadedImpl>(this, _$identity); + __$$ChatRoomStateLoadedImplCopyWithImpl<_$ChatRoomStateLoadedImpl>( + this, _$identity); @override @optionalTypeArgs TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, + required TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading) + loaded, required TResult Function(String errorMessage) error, }) { return loaded(chatRoom, chatMessages, isTyping, isLoading); @@ -413,7 +467,9 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult? Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult? Function(String errorMessage)? error, }) { return loaded?.call(chatRoom, chatMessages, isTyping, isLoading); @@ -424,7 +480,9 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -484,21 +542,26 @@ abstract class ChatRoomStateLoaded implements ChatRoomState { bool get isTyping; bool get isLoading; @JsonKey(ignore: true) - _$$ChatRoomStateLoadedImplCopyWith<_$ChatRoomStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatRoomStateLoadedImplCopyWith<_$ChatRoomStateLoadedImpl> get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class _$$ChatRoomStateErrorImplCopyWith<$Res> { - factory _$$ChatRoomStateErrorImplCopyWith(_$ChatRoomStateErrorImpl value, $Res Function(_$ChatRoomStateErrorImpl) then) = + factory _$$ChatRoomStateErrorImplCopyWith(_$ChatRoomStateErrorImpl value, + $Res Function(_$ChatRoomStateErrorImpl) then) = __$$ChatRoomStateErrorImplCopyWithImpl<$Res>; @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$ChatRoomStateErrorImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateErrorImpl> +class __$$ChatRoomStateErrorImplCopyWithImpl<$Res> + extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateErrorImpl> implements _$$ChatRoomStateErrorImplCopyWith<$Res> { - __$$ChatRoomStateErrorImplCopyWithImpl(_$ChatRoomStateErrorImpl _value, $Res Function(_$ChatRoomStateErrorImpl) _then) : super(_value, _then); + __$$ChatRoomStateErrorImplCopyWithImpl(_$ChatRoomStateErrorImpl _value, + $Res Function(_$ChatRoomStateErrorImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -532,7 +595,8 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateErrorImpl && - (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); } @override @@ -542,14 +606,17 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { @override @pragma('vm:prefer-inline') _$$ChatRoomStateErrorImplCopyWith<_$ChatRoomStateErrorImpl> get copyWith => - __$$ChatRoomStateErrorImplCopyWithImpl<_$ChatRoomStateErrorImpl>(this, _$identity); + __$$ChatRoomStateErrorImplCopyWithImpl<_$ChatRoomStateErrorImpl>( + this, _$identity); @override @optionalTypeArgs TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, + required TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading) + loaded, required TResult Function(String errorMessage) error, }) { return error(errorMessage); @@ -560,7 +627,9 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult? Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult? Function(String errorMessage)? error, }) { return error?.call(errorMessage); @@ -571,7 +640,9 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -620,9 +691,11 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { } abstract class ChatRoomStateError implements ChatRoomState { - const factory ChatRoomStateError({required final String errorMessage}) = _$ChatRoomStateErrorImpl; + const factory ChatRoomStateError({required final String errorMessage}) = + _$ChatRoomStateErrorImpl; String get errorMessage; @JsonKey(ignore: true) - _$$ChatRoomStateErrorImplCopyWith<_$ChatRoomStateErrorImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatRoomStateErrorImplCopyWith<_$ChatRoomStateErrorImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/chat/services/chat_service.g.dart b/lib/features/chat/services/chat_service.g.dart index 8d212c4..2f0674b 100644 --- a/lib/features/chat/services/chat_service.g.dart +++ b/lib/features/chat/services/chat_service.g.dart @@ -24,23 +24,25 @@ class _ChatService implements ChatService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType>(Options( + final _result = await _dio.fetch>( + _setStreamType>(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/chat/show/${id}', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - var _value = _result.data!.map((k, dynamic v) => MapEntry(k, ChatRoomModel.fromJson(v as Map))); + .compose( + _dio.options, + '/api/chat/show/${id}', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + var _value = _result.data!.map((k, dynamic v) => + MapEntry(k, ChatRoomModel.fromJson(v as Map))); return _value; } @@ -96,22 +98,23 @@ class _ChatService implements ChatService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio + .fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/chat/show/${id}/messages?page=${page}', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/chat/show/${id}/messages?page=${page}', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = ChatMessagesModel.fromJson(_result.data!); return _value; } @@ -122,28 +125,31 @@ class _ChatService implements ChatService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio + .fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/profile/ws/params', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/profile/ws/params', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = WebsocketInfoModel.fromJson(_result.data!); return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && + !(requestOptions.responseType == ResponseType.bytes || + requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { diff --git a/lib/features/diary/models/diary_model.freezed.dart b/lib/features/diary/models/diary_model.freezed.dart index b593541..5ede010 100644 --- a/lib/features/diary/models/diary_model.freezed.dart +++ b/lib/features/diary/models/diary_model.freezed.dart @@ -30,18 +30,29 @@ mixin _$DiaryModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $DiaryModelCopyWith get copyWith => throw _privateConstructorUsedError; + $DiaryModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $DiaryModelCopyWith<$Res> { - factory $DiaryModelCopyWith(DiaryModel value, $Res Function(DiaryModel) then) = _$DiaryModelCopyWithImpl<$Res, DiaryModel>; + factory $DiaryModelCopyWith( + DiaryModel value, $Res Function(DiaryModel) then) = + _$DiaryModelCopyWithImpl<$Res, DiaryModel>; @useResult - $Res call({int id, DateTime date, DateTime wakeup, DateTime retire, int closed, String comment, List meals}); + $Res call( + {int id, + DateTime date, + DateTime wakeup, + DateTime retire, + int closed, + String comment, + List meals}); } /// @nodoc -class _$DiaryModelCopyWithImpl<$Res, $Val extends DiaryModel> implements $DiaryModelCopyWith<$Res> { +class _$DiaryModelCopyWithImpl<$Res, $Val extends DiaryModel> + implements $DiaryModelCopyWith<$Res> { _$DiaryModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -94,16 +105,30 @@ class _$DiaryModelCopyWithImpl<$Res, $Val extends DiaryModel> implements $DiaryM } /// @nodoc -abstract class _$$DiaryModelImplCopyWith<$Res> implements $DiaryModelCopyWith<$Res> { - factory _$$DiaryModelImplCopyWith(_$DiaryModelImpl value, $Res Function(_$DiaryModelImpl) then) = __$$DiaryModelImplCopyWithImpl<$Res>; +abstract class _$$DiaryModelImplCopyWith<$Res> + implements $DiaryModelCopyWith<$Res> { + factory _$$DiaryModelImplCopyWith( + _$DiaryModelImpl value, $Res Function(_$DiaryModelImpl) then) = + __$$DiaryModelImplCopyWithImpl<$Res>; @override @useResult - $Res call({int id, DateTime date, DateTime wakeup, DateTime retire, int closed, String comment, List meals}); + $Res call( + {int id, + DateTime date, + DateTime wakeup, + DateTime retire, + int closed, + String comment, + List meals}); } /// @nodoc -class __$$DiaryModelImplCopyWithImpl<$Res> extends _$DiaryModelCopyWithImpl<$Res, _$DiaryModelImpl> implements _$$DiaryModelImplCopyWith<$Res> { - __$$DiaryModelImplCopyWithImpl(_$DiaryModelImpl _value, $Res Function(_$DiaryModelImpl) _then) : super(_value, _then); +class __$$DiaryModelImplCopyWithImpl<$Res> + extends _$DiaryModelCopyWithImpl<$Res, _$DiaryModelImpl> + implements _$$DiaryModelImplCopyWith<$Res> { + __$$DiaryModelImplCopyWithImpl( + _$DiaryModelImpl _value, $Res Function(_$DiaryModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -162,7 +187,8 @@ class _$DiaryModelImpl implements _DiaryModel { required final List meals}) : _meals = meals; - factory _$DiaryModelImpl.fromJson(Map json) => _$$DiaryModelImplFromJson(json); + factory _$DiaryModelImpl.fromJson(Map json) => + _$$DiaryModelImplFromJson(json); @override final int id; @@ -205,12 +231,14 @@ class _$DiaryModelImpl implements _DiaryModel { @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, date, wakeup, retire, closed, comment, const DeepCollectionEquality().hash(_meals)); + int get hashCode => Object.hash(runtimeType, id, date, wakeup, retire, closed, + comment, const DeepCollectionEquality().hash(_meals)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$DiaryModelImplCopyWith<_$DiaryModelImpl> get copyWith => __$$DiaryModelImplCopyWithImpl<_$DiaryModelImpl>(this, _$identity); + _$$DiaryModelImplCopyWith<_$DiaryModelImpl> get copyWith => + __$$DiaryModelImplCopyWithImpl<_$DiaryModelImpl>(this, _$identity); @override Map toJson() { @@ -230,7 +258,8 @@ abstract class _DiaryModel implements DiaryModel { required final String comment, required final List meals}) = _$DiaryModelImpl; - factory _DiaryModel.fromJson(Map json) = _$DiaryModelImpl.fromJson; + factory _DiaryModel.fromJson(Map json) = + _$DiaryModelImpl.fromJson; @override int get id; @@ -248,5 +277,6 @@ abstract class _DiaryModel implements DiaryModel { List get meals; @override @JsonKey(ignore: true) - _$$DiaryModelImplCopyWith<_$DiaryModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$DiaryModelImplCopyWith<_$DiaryModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/diary/models/diary_model.g.dart b/lib/features/diary/models/diary_model.g.dart index 79a0e92..cab25b6 100644 --- a/lib/features/diary/models/diary_model.g.dart +++ b/lib/features/diary/models/diary_model.g.dart @@ -6,17 +6,21 @@ part of 'diary_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$DiaryModelImpl _$$DiaryModelImplFromJson(Map json) => _$DiaryModelImpl( +_$DiaryModelImpl _$$DiaryModelImplFromJson(Map json) => + _$DiaryModelImpl( id: (json['id'] as num).toInt(), date: DateTime.parse(json['date'] as String), wakeup: DateTime.parse(json['wakeup'] as String), retire: DateTime.parse(json['retire'] as String), closed: (json['closed'] as num).toInt(), comment: json['comment'] as String, - meals: (json['meals'] as List).map((e) => Meals.fromJson(e as Map)).toList(), + meals: (json['meals'] as List) + .map((e) => Meals.fromJson(e as Map)) + .toList(), ); -Map _$$DiaryModelImplToJson(_$DiaryModelImpl instance) => { +Map _$$DiaryModelImplToJson(_$DiaryModelImpl instance) => + { 'id': instance.id, 'date': instance.date.toIso8601String(), 'wakeup': instance.wakeup.toIso8601String(), diff --git a/lib/features/feed/models/feed_blog_post_model.freezed.dart b/lib/features/feed/models/feed_blog_post_model.freezed.dart index 9afd21e..4d753a1 100644 --- a/lib/features/feed/models/feed_blog_post_model.freezed.dart +++ b/lib/features/feed/models/feed_blog_post_model.freezed.dart @@ -34,12 +34,15 @@ mixin _$FeedBlogPostModel { Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $FeedBlogPostModelCopyWith get copyWith => throw _privateConstructorUsedError; + $FeedBlogPostModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $FeedBlogPostModelCopyWith<$Res> { - factory $FeedBlogPostModelCopyWith(FeedBlogPostModel value, $Res Function(FeedBlogPostModel) then) = _$FeedBlogPostModelCopyWithImpl<$Res, FeedBlogPostModel>; + factory $FeedBlogPostModelCopyWith( + FeedBlogPostModel value, $Res Function(FeedBlogPostModel) then) = + _$FeedBlogPostModelCopyWithImpl<$Res, FeedBlogPostModel>; @useResult $Res call( {int id, @@ -53,7 +56,8 @@ abstract class $FeedBlogPostModelCopyWith<$Res> { } /// @nodoc -class _$FeedBlogPostModelCopyWithImpl<$Res, $Val extends FeedBlogPostModel> implements $FeedBlogPostModelCopyWith<$Res> { +class _$FeedBlogPostModelCopyWithImpl<$Res, $Val extends FeedBlogPostModel> + implements $FeedBlogPostModelCopyWith<$Res> { _$FeedBlogPostModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -111,8 +115,10 @@ class _$FeedBlogPostModelCopyWithImpl<$Res, $Val extends FeedBlogPostModel> impl } /// @nodoc -abstract class _$$FeedBlogPostModelImplCopyWith<$Res> implements $FeedBlogPostModelCopyWith<$Res> { - factory _$$FeedBlogPostModelImplCopyWith(_$FeedBlogPostModelImpl value, $Res Function(_$FeedBlogPostModelImpl) then) = +abstract class _$$FeedBlogPostModelImplCopyWith<$Res> + implements $FeedBlogPostModelCopyWith<$Res> { + factory _$$FeedBlogPostModelImplCopyWith(_$FeedBlogPostModelImpl value, + $Res Function(_$FeedBlogPostModelImpl) then) = __$$FeedBlogPostModelImplCopyWithImpl<$Res>; @override @useResult @@ -128,9 +134,12 @@ abstract class _$$FeedBlogPostModelImplCopyWith<$Res> implements $FeedBlogPostMo } /// @nodoc -class __$$FeedBlogPostModelImplCopyWithImpl<$Res> extends _$FeedBlogPostModelCopyWithImpl<$Res, _$FeedBlogPostModelImpl> +class __$$FeedBlogPostModelImplCopyWithImpl<$Res> + extends _$FeedBlogPostModelCopyWithImpl<$Res, _$FeedBlogPostModelImpl> implements _$$FeedBlogPostModelImplCopyWith<$Res> { - __$$FeedBlogPostModelImplCopyWithImpl(_$FeedBlogPostModelImpl _value, $Res Function(_$FeedBlogPostModelImpl) _then) : super(_value, _then); + __$$FeedBlogPostModelImplCopyWithImpl(_$FeedBlogPostModelImpl _value, + $Res Function(_$FeedBlogPostModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -194,7 +203,8 @@ class _$FeedBlogPostModelImpl implements _FeedBlogPostModel { @JsonKey(name: "updated_at") required this.updatedAt, required this.title}); - factory _$FeedBlogPostModelImpl.fromJson(Map json) => _$$FeedBlogPostModelImplFromJson(json); + factory _$FeedBlogPostModelImpl.fromJson(Map json) => + _$$FeedBlogPostModelImplFromJson(json); @override final int id; @@ -229,21 +239,28 @@ class _$FeedBlogPostModelImpl implements _FeedBlogPostModel { (identical(other.id, id) || other.id == id) && (identical(other.state, state) || other.state == state) && (identical(other.image, image) || other.image == image) && - (identical(other.description, description) || other.description == description) && - (identical(other.youtubeUrl, youtubeUrl) || other.youtubeUrl == youtubeUrl) && - (identical(other.createdAt, createdAt) || other.createdAt == createdAt) && - (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt) && + (identical(other.description, description) || + other.description == description) && + (identical(other.youtubeUrl, youtubeUrl) || + other.youtubeUrl == youtubeUrl) && + (identical(other.createdAt, createdAt) || + other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt) && (identical(other.title, title) || other.title == title)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, state, image, description, youtubeUrl, createdAt, updatedAt, title); + int get hashCode => Object.hash(runtimeType, id, state, image, description, + youtubeUrl, createdAt, updatedAt, title); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => __$$FeedBlogPostModelImplCopyWithImpl<_$FeedBlogPostModelImpl>(this, _$identity); + _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => + __$$FeedBlogPostModelImplCopyWithImpl<_$FeedBlogPostModelImpl>( + this, _$identity); @override Map toJson() { @@ -264,7 +281,8 @@ abstract class _FeedBlogPostModel implements FeedBlogPostModel { @JsonKey(name: "updated_at") required final DateTime updatedAt, required final String title}) = _$FeedBlogPostModelImpl; - factory _FeedBlogPostModel.fromJson(Map json) = _$FeedBlogPostModelImpl.fromJson; + factory _FeedBlogPostModel.fromJson(Map json) = + _$FeedBlogPostModelImpl.fromJson; @override int get id; @@ -287,5 +305,6 @@ abstract class _FeedBlogPostModel implements FeedBlogPostModel { String get title; @override @JsonKey(ignore: true) - _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/feed/models/feed_blog_post_model.g.dart b/lib/features/feed/models/feed_blog_post_model.g.dart index e680864..93cc70f 100644 --- a/lib/features/feed/models/feed_blog_post_model.g.dart +++ b/lib/features/feed/models/feed_blog_post_model.g.dart @@ -6,7 +6,9 @@ part of 'feed_blog_post_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$FeedBlogPostModelImpl _$$FeedBlogPostModelImplFromJson(Map json) => _$FeedBlogPostModelImpl( +_$FeedBlogPostModelImpl _$$FeedBlogPostModelImplFromJson( + Map json) => + _$FeedBlogPostModelImpl( id: (json['id'] as num).toInt(), state: json['state'] as String, image: json['image'] as String, @@ -17,7 +19,9 @@ _$FeedBlogPostModelImpl _$$FeedBlogPostModelImplFromJson(Map js title: json['title'] as String, ); -Map _$$FeedBlogPostModelImplToJson(_$FeedBlogPostModelImpl instance) => { +Map _$$FeedBlogPostModelImplToJson( + _$FeedBlogPostModelImpl instance) => + { 'id': instance.id, 'state': instance.state, 'image': instance.image, 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 index cab47d2..7fd8a12 100644 --- a/lib/features/feed/models/feed_blog_post_settings_model.freezed.dart +++ b/lib/features/feed/models/feed_blog_post_settings_model.freezed.dart @@ -14,30 +14,36 @@ 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) { +FeedBlogPostSettingsModel _$FeedBlogPostSettingsModelFromJson( + Map json) { return _FeedBlogPostSettingsModel.fromJson(json); } /// @nodoc mixin _$FeedBlogPostSettingsModel { @JsonKey(name: 'data') - List get feedBlogPostList => throw _privateConstructorUsedError; + List get feedBlogPostList => + throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $FeedBlogPostSettingsModelCopyWith get copyWith => throw _privateConstructorUsedError; + $FeedBlogPostSettingsModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $FeedBlogPostSettingsModelCopyWith<$Res> { - factory $FeedBlogPostSettingsModelCopyWith(FeedBlogPostSettingsModel value, $Res Function(FeedBlogPostSettingsModel) then) = + 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> { +class _$FeedBlogPostSettingsModelCopyWithImpl<$Res, + $Val extends FeedBlogPostSettingsModel> + implements $FeedBlogPostSettingsModelCopyWith<$Res> { _$FeedBlogPostSettingsModelCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -60,8 +66,11 @@ class _$FeedBlogPostSettingsModelCopyWithImpl<$Res, $Val extends FeedBlogPostSet } /// @nodoc -abstract class _$$FeedBlogPostSettingsModelImplCopyWith<$Res> implements $FeedBlogPostSettingsModelCopyWith<$Res> { - factory _$$FeedBlogPostSettingsModelImplCopyWith(_$FeedBlogPostSettingsModelImpl value, $Res Function(_$FeedBlogPostSettingsModelImpl) then) = +abstract class _$$FeedBlogPostSettingsModelImplCopyWith<$Res> + implements $FeedBlogPostSettingsModelCopyWith<$Res> { + factory _$$FeedBlogPostSettingsModelImplCopyWith( + _$FeedBlogPostSettingsModelImpl value, + $Res Function(_$FeedBlogPostSettingsModelImpl) then) = __$$FeedBlogPostSettingsModelImplCopyWithImpl<$Res>; @override @useResult @@ -69,9 +78,13 @@ abstract class _$$FeedBlogPostSettingsModelImplCopyWith<$Res> implements $FeedBl } /// @nodoc -class __$$FeedBlogPostSettingsModelImplCopyWithImpl<$Res> extends _$FeedBlogPostSettingsModelCopyWithImpl<$Res, _$FeedBlogPostSettingsModelImpl> +class __$$FeedBlogPostSettingsModelImplCopyWithImpl<$Res> + extends _$FeedBlogPostSettingsModelCopyWithImpl<$Res, + _$FeedBlogPostSettingsModelImpl> implements _$$FeedBlogPostSettingsModelImplCopyWith<$Res> { - __$$FeedBlogPostSettingsModelImplCopyWithImpl(_$FeedBlogPostSettingsModelImpl _value, $Res Function(_$FeedBlogPostSettingsModelImpl) _then) + __$$FeedBlogPostSettingsModelImplCopyWithImpl( + _$FeedBlogPostSettingsModelImpl _value, + $Res Function(_$FeedBlogPostSettingsModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -91,16 +104,20 @@ class __$$FeedBlogPostSettingsModelImplCopyWithImpl<$Res> extends _$FeedBlogPost /// @nodoc @JsonSerializable() class _$FeedBlogPostSettingsModelImpl implements _FeedBlogPostSettingsModel { - const _$FeedBlogPostSettingsModelImpl({@JsonKey(name: 'data') required final List feedBlogPostList}) + const _$FeedBlogPostSettingsModelImpl( + {@JsonKey(name: 'data') + required final List feedBlogPostList}) : _feedBlogPostList = feedBlogPostList; - factory _$FeedBlogPostSettingsModelImpl.fromJson(Map json) => _$$FeedBlogPostSettingsModelImplFromJson(json); + factory _$FeedBlogPostSettingsModelImpl.fromJson(Map json) => + _$$FeedBlogPostSettingsModelImplFromJson(json); final List _feedBlogPostList; @override @JsonKey(name: 'data') List get feedBlogPostList { - if (_feedBlogPostList is EqualUnmodifiableListView) return _feedBlogPostList; + if (_feedBlogPostList is EqualUnmodifiableListView) + return _feedBlogPostList; // ignore: implicit_dynamic_type return EqualUnmodifiableListView(_feedBlogPostList); } @@ -115,18 +132,21 @@ class _$FeedBlogPostSettingsModelImpl implements _FeedBlogPostSettingsModel { return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedBlogPostSettingsModelImpl && - const DeepCollectionEquality().equals(other._feedBlogPostList, _feedBlogPostList)); + const DeepCollectionEquality() + .equals(other._feedBlogPostList, _feedBlogPostList)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_feedBlogPostList)); + 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); + _$$FeedBlogPostSettingsModelImplCopyWith<_$FeedBlogPostSettingsModelImpl> + get copyWith => __$$FeedBlogPostSettingsModelImplCopyWithImpl< + _$FeedBlogPostSettingsModelImpl>(this, _$identity); @override Map toJson() { @@ -137,14 +157,19 @@ class _$FeedBlogPostSettingsModelImpl implements _FeedBlogPostSettingsModel { } abstract class _FeedBlogPostSettingsModel implements FeedBlogPostSettingsModel { - const factory _FeedBlogPostSettingsModel({@JsonKey(name: 'data') required final List feedBlogPostList}) = _$FeedBlogPostSettingsModelImpl; + const factory _FeedBlogPostSettingsModel( + {@JsonKey(name: 'data') + required final List feedBlogPostList}) = + _$FeedBlogPostSettingsModelImpl; - factory _FeedBlogPostSettingsModel.fromJson(Map json) = _$FeedBlogPostSettingsModelImpl.fromJson; + factory _FeedBlogPostSettingsModel.fromJson(Map json) = + _$FeedBlogPostSettingsModelImpl.fromJson; @override @JsonKey(name: 'data') List get feedBlogPostList; @override @JsonKey(ignore: true) - _$$FeedBlogPostSettingsModelImplCopyWith<_$FeedBlogPostSettingsModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$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 index c960067..3f48be1 100644 --- a/lib/features/feed/models/feed_blog_post_settings_model.g.dart +++ b/lib/features/feed/models/feed_blog_post_settings_model.g.dart @@ -6,10 +6,16 @@ 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(), +_$FeedBlogPostSettingsModelImpl _$$FeedBlogPostSettingsModelImplFromJson( + Map json) => + _$FeedBlogPostSettingsModelImpl( + feedBlogPostList: (json['data'] as List) + .map((e) => FeedBlogPostModel.fromJson(e as Map)) + .toList(), ); -Map _$$FeedBlogPostSettingsModelImplToJson(_$FeedBlogPostSettingsModelImpl instance) => { +Map _$$FeedBlogPostSettingsModelImplToJson( + _$FeedBlogPostSettingsModelImpl instance) => + { 'data': instance.feedBlogPostList, }; diff --git a/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart b/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart index f3b70a9..ab3385f 100644 --- a/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart +++ b/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart @@ -70,11 +70,13 @@ mixin _$FeedState { /// @nodoc abstract class $FeedStateCopyWith<$Res> { - factory $FeedStateCopyWith(FeedState value, $Res Function(FeedState) then) = _$FeedStateCopyWithImpl<$Res, FeedState>; + factory $FeedStateCopyWith(FeedState value, $Res Function(FeedState) then) = + _$FeedStateCopyWithImpl<$Res, FeedState>; } /// @nodoc -class _$FeedStateCopyWithImpl<$Res, $Val extends FeedState> implements $FeedStateCopyWith<$Res> { +class _$FeedStateCopyWithImpl<$Res, $Val extends FeedState> + implements $FeedStateCopyWith<$Res> { _$FeedStateCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -85,12 +87,18 @@ class _$FeedStateCopyWithImpl<$Res, $Val extends FeedState> implements $FeedStat /// @nodoc abstract class _$$FeedStateImplCopyWith<$Res> { - factory _$$FeedStateImplCopyWith(_$FeedStateImpl value, $Res Function(_$FeedStateImpl) then) = __$$FeedStateImplCopyWithImpl<$Res>; + factory _$$FeedStateImplCopyWith( + _$FeedStateImpl value, $Res Function(_$FeedStateImpl) then) = + __$$FeedStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$FeedStateImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateImpl> implements _$$FeedStateImplCopyWith<$Res> { - __$$FeedStateImplCopyWithImpl(_$FeedStateImpl _value, $Res Function(_$FeedStateImpl) _then) : super(_value, _then); +class __$$FeedStateImplCopyWithImpl<$Res> + extends _$FeedStateCopyWithImpl<$Res, _$FeedStateImpl> + implements _$$FeedStateImplCopyWith<$Res> { + __$$FeedStateImplCopyWithImpl( + _$FeedStateImpl _value, $Res Function(_$FeedStateImpl) _then) + : super(_value, _then); } /// @nodoc @@ -105,7 +113,8 @@ class _$FeedStateImpl implements _FeedState { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$FeedStateImpl); } @override @@ -192,14 +201,18 @@ abstract class _FeedState implements FeedState { /// @nodoc abstract class _$$FeedStateLoadingImplCopyWith<$Res> { - factory _$$FeedStateLoadingImplCopyWith(_$FeedStateLoadingImpl value, $Res Function(_$FeedStateLoadingImpl) then) = + factory _$$FeedStateLoadingImplCopyWith(_$FeedStateLoadingImpl value, + $Res Function(_$FeedStateLoadingImpl) then) = __$$FeedStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$FeedStateLoadingImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadingImpl> +class __$$FeedStateLoadingImplCopyWithImpl<$Res> + extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadingImpl> implements _$$FeedStateLoadingImplCopyWith<$Res> { - __$$FeedStateLoadingImplCopyWithImpl(_$FeedStateLoadingImpl _value, $Res Function(_$FeedStateLoadingImpl) _then) : super(_value, _then); + __$$FeedStateLoadingImplCopyWithImpl(_$FeedStateLoadingImpl _value, + $Res Function(_$FeedStateLoadingImpl) _then) + : super(_value, _then); } /// @nodoc @@ -214,7 +227,8 @@ class _$FeedStateLoadingImpl implements FeedStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateLoadingImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$FeedStateLoadingImpl); } @override @@ -301,14 +315,20 @@ abstract class FeedStateLoading implements FeedState { /// @nodoc abstract class _$$FeedStateLoadedImplCopyWith<$Res> { - factory _$$FeedStateLoadedImplCopyWith(_$FeedStateLoadedImpl value, $Res Function(_$FeedStateLoadedImpl) then) = __$$FeedStateLoadedImplCopyWithImpl<$Res>; + factory _$$FeedStateLoadedImplCopyWith(_$FeedStateLoadedImpl value, + $Res Function(_$FeedStateLoadedImpl) then) = + __$$FeedStateLoadedImplCopyWithImpl<$Res>; @useResult $Res call({List feedBlogPostList}); } /// @nodoc -class __$$FeedStateLoadedImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadedImpl> implements _$$FeedStateLoadedImplCopyWith<$Res> { - __$$FeedStateLoadedImplCopyWithImpl(_$FeedStateLoadedImpl _value, $Res Function(_$FeedStateLoadedImpl) _then) : super(_value, _then); +class __$$FeedStateLoadedImplCopyWithImpl<$Res> + extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadedImpl> + implements _$$FeedStateLoadedImplCopyWith<$Res> { + __$$FeedStateLoadedImplCopyWithImpl( + _$FeedStateLoadedImpl _value, $Res Function(_$FeedStateLoadedImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -327,12 +347,15 @@ class __$$FeedStateLoadedImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl< /// @nodoc class _$FeedStateLoadedImpl implements FeedStateLoaded { - const _$FeedStateLoadedImpl({required final List feedBlogPostList}) : _feedBlogPostList = feedBlogPostList; + const _$FeedStateLoadedImpl( + {required final List feedBlogPostList}) + : _feedBlogPostList = feedBlogPostList; final List _feedBlogPostList; @override List get feedBlogPostList { - if (_feedBlogPostList is EqualUnmodifiableListView) return _feedBlogPostList; + if (_feedBlogPostList is EqualUnmodifiableListView) + return _feedBlogPostList; // ignore: implicit_dynamic_type return EqualUnmodifiableListView(_feedBlogPostList); } @@ -347,16 +370,20 @@ class _$FeedStateLoadedImpl implements FeedStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateLoadedImpl && - const DeepCollectionEquality().equals(other._feedBlogPostList, _feedBlogPostList)); + const DeepCollectionEquality() + .equals(other._feedBlogPostList, _feedBlogPostList)); } @override - int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_feedBlogPostList)); + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_feedBlogPostList)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => __$$FeedStateLoadedImplCopyWithImpl<_$FeedStateLoadedImpl>(this, _$identity); + _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => + __$$FeedStateLoadedImplCopyWithImpl<_$FeedStateLoadedImpl>( + this, _$identity); @override @optionalTypeArgs @@ -434,23 +461,32 @@ class _$FeedStateLoadedImpl implements FeedStateLoaded { } abstract class FeedStateLoaded implements FeedState { - const factory FeedStateLoaded({required final List feedBlogPostList}) = _$FeedStateLoadedImpl; + const factory FeedStateLoaded( + {required final List feedBlogPostList}) = + _$FeedStateLoadedImpl; List get feedBlogPostList; @JsonKey(ignore: true) - _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; + _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class _$$FeedStateErrorImplCopyWith<$Res> { - factory _$$FeedStateErrorImplCopyWith(_$FeedStateErrorImpl value, $Res Function(_$FeedStateErrorImpl) then) = __$$FeedStateErrorImplCopyWithImpl<$Res>; + factory _$$FeedStateErrorImplCopyWith(_$FeedStateErrorImpl value, + $Res Function(_$FeedStateErrorImpl) then) = + __$$FeedStateErrorImplCopyWithImpl<$Res>; @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$FeedStateErrorImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateErrorImpl> implements _$$FeedStateErrorImplCopyWith<$Res> { - __$$FeedStateErrorImplCopyWithImpl(_$FeedStateErrorImpl _value, $Res Function(_$FeedStateErrorImpl) _then) : super(_value, _then); +class __$$FeedStateErrorImplCopyWithImpl<$Res> + extends _$FeedStateCopyWithImpl<$Res, _$FeedStateErrorImpl> + implements _$$FeedStateErrorImplCopyWith<$Res> { + __$$FeedStateErrorImplCopyWithImpl( + _$FeedStateErrorImpl _value, $Res Function(_$FeedStateErrorImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -484,7 +520,8 @@ class _$FeedStateErrorImpl implements FeedStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateErrorImpl && - (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); } @override @@ -493,7 +530,9 @@ class _$FeedStateErrorImpl implements FeedStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => __$$FeedStateErrorImplCopyWithImpl<_$FeedStateErrorImpl>(this, _$identity); + _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => + __$$FeedStateErrorImplCopyWithImpl<_$FeedStateErrorImpl>( + this, _$identity); @override @optionalTypeArgs @@ -571,9 +610,11 @@ class _$FeedStateErrorImpl implements FeedStateError { } abstract class FeedStateError implements FeedState { - const factory FeedStateError({required final String errorMessage}) = _$FeedStateErrorImpl; + const factory FeedStateError({required final String errorMessage}) = + _$FeedStateErrorImpl; String get errorMessage; @JsonKey(ignore: true) - _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => throw _privateConstructorUsedError; + _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/feed/services/feed_service.g.dart b/lib/features/feed/services/feed_service.g.dart index 0e66eb4..89003f6 100644 --- a/lib/features/feed/services/feed_service.g.dart +++ b/lib/features/feed/services/feed_service.g.dart @@ -24,28 +24,31 @@ class _FeedService implements FeedService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio.fetch>( + _setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/blogPosts/index', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/blogPosts/index', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = FeedBlogPostSettingsModel.fromJson(_result.data!); return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && + !(requestOptions.responseType == ResponseType.bytes || + requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { diff --git a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart index c39f834..4d06c95 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart @@ -1,7 +1,10 @@ +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; @@ -42,12 +45,13 @@ class RegistrationCubit extends Cubit { updateSheet(UserRegistrationSheet sheet) => emit(RegistrationState(sheet: sheet)); - tryRegistration() async { + Future tryRegistration() async { try { - final response = await registrationRepository.tryRegister(state.sheet); - print(response); + final token = await registrationRepository.tryRegister(state.sheet); + await TokenStorage.saveTokenInStorage(token); + AppRouter.navigatorKey.currentContext?.go('/my-profile-screen'); } catch (e) { - print(e); + rethrow; } } } 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 index 70a7f33..dcb4923 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_state.freezed.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_state.freezed.dart @@ -19,12 +19,15 @@ mixin _$RegistrationState { UserRegistrationSheet get sheet => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $RegistrationStateCopyWith get copyWith => throw _privateConstructorUsedError; + $RegistrationStateCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $RegistrationStateCopyWith<$Res> { - factory $RegistrationStateCopyWith(RegistrationState value, $Res Function(RegistrationState) then) = _$RegistrationStateCopyWithImpl<$Res, RegistrationState>; + factory $RegistrationStateCopyWith( + RegistrationState value, $Res Function(RegistrationState) then) = + _$RegistrationStateCopyWithImpl<$Res, RegistrationState>; @useResult $Res call({UserRegistrationSheet sheet}); @@ -32,7 +35,8 @@ abstract class $RegistrationStateCopyWith<$Res> { } /// @nodoc -class _$RegistrationStateCopyWithImpl<$Res, $Val extends RegistrationState> implements $RegistrationStateCopyWith<$Res> { +class _$RegistrationStateCopyWithImpl<$Res, $Val extends RegistrationState> + implements $RegistrationStateCopyWith<$Res> { _$RegistrationStateCopyWithImpl(this._value, this._then); // ignore: unused_field @@ -63,8 +67,10 @@ class _$RegistrationStateCopyWithImpl<$Res, $Val extends RegistrationState> impl } /// @nodoc -abstract class _$$RegistrationStateImplCopyWith<$Res> implements $RegistrationStateCopyWith<$Res> { - factory _$$RegistrationStateImplCopyWith(_$RegistrationStateImpl value, $Res Function(_$RegistrationStateImpl) then) = +abstract class _$$RegistrationStateImplCopyWith<$Res> + implements $RegistrationStateCopyWith<$Res> { + factory _$$RegistrationStateImplCopyWith(_$RegistrationStateImpl value, + $Res Function(_$RegistrationStateImpl) then) = __$$RegistrationStateImplCopyWithImpl<$Res>; @override @useResult @@ -75,9 +81,12 @@ abstract class _$$RegistrationStateImplCopyWith<$Res> implements $RegistrationSt } /// @nodoc -class __$$RegistrationStateImplCopyWithImpl<$Res> extends _$RegistrationStateCopyWithImpl<$Res, _$RegistrationStateImpl> +class __$$RegistrationStateImplCopyWithImpl<$Res> + extends _$RegistrationStateCopyWithImpl<$Res, _$RegistrationStateImpl> implements _$$RegistrationStateImplCopyWith<$Res> { - __$$RegistrationStateImplCopyWithImpl(_$RegistrationStateImpl _value, $Res Function(_$RegistrationStateImpl) _then) : super(_value, _then); + __$$RegistrationStateImplCopyWithImpl(_$RegistrationStateImpl _value, + $Res Function(_$RegistrationStateImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -109,7 +118,9 @@ class _$RegistrationStateImpl implements _RegistrationState { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && other is _$RegistrationStateImpl && (identical(other.sheet, sheet) || other.sheet == sheet)); + (other.runtimeType == runtimeType && + other is _$RegistrationStateImpl && + (identical(other.sheet, sheet) || other.sheet == sheet)); } @override @@ -118,15 +129,19 @@ class _$RegistrationStateImpl implements _RegistrationState { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => __$$RegistrationStateImplCopyWithImpl<_$RegistrationStateImpl>(this, _$identity); + _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => + __$$RegistrationStateImplCopyWithImpl<_$RegistrationStateImpl>( + this, _$identity); } abstract class _RegistrationState implements RegistrationState { - const factory _RegistrationState({required final UserRegistrationSheet sheet}) = _$RegistrationStateImpl; + const factory _RegistrationState( + {required final UserRegistrationSheet sheet}) = _$RegistrationStateImpl; @override UserRegistrationSheet get sheet; @override @JsonKey(ignore: true) - _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => throw _privateConstructorUsedError; + _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/registration/presentation/pages/registration_screen.dart b/lib/features/registration/presentation/pages/registration_screen.dart index eae9818..93a5eae 100644 --- a/lib/features/registration/presentation/pages/registration_screen.dart +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -113,8 +113,8 @@ class _RegistrationScreenState extends State { borderRadius: BorderRadius.circular(16), ), backgroundColor: appTheme.blueA400, - onPressed: () { - if (canGoNext(state)) { + onPressed: () async { + if (await canGoNext(state)) { setState(() { pageController.nextPage( duration: const Duration(milliseconds: 350), @@ -197,7 +197,7 @@ class _RegistrationScreenState extends State { ); } - bool canGoNext(state) { + Future canGoNext(state) async { switch (step) { case 2: List errors = validateCredentialsFields(state.sheet.email, state.sheet.name, state.sheet.password, state.sheet.passwordConfirmation); @@ -285,8 +285,30 @@ class _RegistrationScreenState extends State { return false; } case 15: - registrationCubit.tryRegistration(); - return true; + 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; } diff --git a/lib/features/registration/repositories/registration_repository.dart b/lib/features/registration/repositories/registration_repository.dart index 8642094..aa38880 100644 --- a/lib/features/registration/repositories/registration_repository.dart +++ b/lib/features/registration/repositories/registration_repository.dart @@ -6,9 +6,9 @@ class RegistrationRepository { RegistrationRepository({required this.registrationService}); - tryRegister(UserRegistrationSheet sheet) async { + Future tryRegister(UserRegistrationSheet sheet) async { try { - return await registrationService.register(sheet: sheet.copyWith(country: 'Россия', city: 'Москва').toJson()); + 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 index 00ae673..fefca6a 100644 --- a/lib/features/registration/services/registration_service.dart +++ b/lib/features/registration/services/registration_service.dart @@ -8,7 +8,7 @@ abstract class RegistrationService { factory RegistrationService(Dio dio, {String baseUrl}) = _RegistrationService; @POST('/api/register') - Future 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 index 1268b0b..269d16c 100644 --- a/lib/features/registration/services/registration_service.g.dart +++ b/lib/features/registration/services/registration_service.g.dart @@ -19,32 +19,38 @@ class _RegistrationService implements RegistrationService { String? baseUrl; @override - Future register({required Map sheet}) async { + Future> register( + {required Map sheet}) async { final _extra = {}; final queryParameters = {}; final _headers = {}; final _data = {}; _data.addAll(sheet); - await _dio.fetch(_setStreamType(Options( + 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, - )))); + .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 != dynamic && + !(requestOptions.responseType == ResponseType.bytes || + requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { -- 2.49.1 From 8610cacc6f832b776d4eac0b2c44356b39a281c3 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Mon, 15 Jul 2024 17:44:33 +0300 Subject: [PATCH 065/110] refactor(diary): Refactor product input --- .../diary/presentation/bloc/diary_bloc.dart | 63 ++--- .../diary/repositories/diary_repository.dart | 8 + .../diary/services/diary_service.dart | 3 + .../diary/services/diary_service.g.dart | 254 ------------------ 4 files changed, 35 insertions(+), 293 deletions(-) delete mode 100644 lib/features/diary/services/diary_service.g.dart diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index c50210b..06d76c4 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -228,11 +228,34 @@ class DiaryBloc extends Bloc { selectedMood: meal.mood, selectedSatiety: meal.satiety, ); - print(updatedState.currentMeal.id); emit(updatedState); } } + Future _inputProduct( + ProductInput event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + + final productNutritionalValues = await diaryRepository.inputProduct(event.input); + + // Create a new controller with the input text and update the autocomplete list + var updatedState = currentState.copyWith( + productNameController: TextEditingController(text: event.input), + autocompleteList: productNutritionalValues.map((product) => product['name']).toList(), + ); + if (event.input.length > 3) { + updatedState = updatedState.copyWith(moderationExpanded: true); + } else { + updatedState = updatedState.copyWith(moderationExpanded: false); + } + + emit(updatedState); // Emit the updated state + } + } + FutureOr _clearInput( ClearInput event, Emitter emit, @@ -332,44 +355,6 @@ class DiaryBloc extends Bloc { return response; } - Future _inputProduct( - ProductInput event, - Emitter emit, - ) async { - if (state is DiaryStateLoaded) { - var currentState = state as DiaryStateLoaded; - - final Map credentials = {'name': event.input}; - final uri = Uri.parse( - '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/filter?${Uri(queryParameters: credentials).query}', - ); - - final response = await http.get( - uri, - headers: { - 'Content-Type': 'application/json', - }, - ); - - final productNutritionalValues = jsonDecode(response.body)['product_nutritional_value']; - - if (productNutritionalValues is List) { - // Create a new controller with the input text and update the autocomplete list - var updatedState = currentState.copyWith( - productNameController: TextEditingController(text: event.input), - autocompleteList: productNutritionalValues.map((product) => product['name']).toList(), - ); - if (event.input.length > 3) { - updatedState = updatedState.copyWith(moderationExpanded: true); - } else { - updatedState = updatedState.copyWith(moderationExpanded: false); - } - - emit(updatedState); // Emit the updated state - } - } - } - Future _removePortion( RemovePortionEvent event, Emitter emit, diff --git a/lib/features/diary/repositories/diary_repository.dart b/lib/features/diary/repositories/diary_repository.dart index 68511c7..ce9e0fa 100644 --- a/lib/features/diary/repositories/diary_repository.dart +++ b/lib/features/diary/repositories/diary_repository.dart @@ -22,6 +22,14 @@ class DiaryRepository { } } + Future> inputProduct(String name) async { + try { + return await diaryService.sendInputProduct(name); + } catch (e) { + rethrow; + } + } + Future changeSatiety(int satiety, int mealID, int diaryID) async { try { await diaryService.sendSatietyData( diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart index b412594..f1ad9d9 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -17,6 +17,9 @@ abstract class DiaryService { @GET('/diary/{id}/dailyNutritionData/') Future getChart(@Path() String id); + @GET('/diary/product_nutritional_values/filter?{name}') + Future> sendInputProduct(@Path() String name); + @POST('/diary/{diary_id}/meal/{meal_id}/satiety/fill') Future> sendSatietyData( @Path() int diary_id, diff --git a/lib/features/diary/services/diary_service.g.dart b/lib/features/diary/services/diary_service.g.dart deleted file mode 100644 index a33a19e..0000000 --- a/lib/features/diary/services/diary_service.g.dart +++ /dev/null @@ -1,254 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND - -part of 'diary_service.dart'; - -// ************************************************************************** -// RetrofitGenerator -// ************************************************************************** - -// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers,unused_element - -class _DiaryService implements DiaryService { - _DiaryService( - this._dio, { - this.baseUrl, - }); - - final Dio _dio; - - String? baseUrl; - - @override - Future> getDiaryID() async { - final _extra = {}; - final queryParameters = {}; - final _headers = {}; - const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType>(Options( - method: 'GET', - headers: _headers, - extra: _extra, - ) - .compose( - _dio.options, - '/diary/index', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - final _value = _result.data!.cast(); - return _value; - } - - @override - Future> getDiary(int id) async { - final _extra = {}; - final queryParameters = {}; - final _headers = {}; - const Map? _data = null; - final _result = await _dio.fetch>( - _setStreamType>(Options( - method: 'GET', - headers: _headers, - extra: _extra, - ) - .compose( - _dio.options, - '/diary/${id}/show/', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - var _value = _result.data!.map((k, dynamic v) => - MapEntry(k, DiaryModel.fromJson(v as Map))); - return _value; - } - - @override - Future getChart(String id) async { - final _extra = {}; - final queryParameters = {}; - final _headers = {}; - const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType(Options( - method: 'GET', - headers: _headers, - extra: _extra, - ) - .compose( - _dio.options, - '/diary/${id}/dailyNutritionData/', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - final _value = DiaryModel.fromJson(_result.data!); - return _value; - } - - @override - Future> sendSatietyData( - int diary_id, - int meal_id, - int satiety, - ) async { - final _extra = {}; - final queryParameters = {r'satiety': satiety}; - final _headers = {}; - const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType>(Options( - method: 'POST', - headers: _headers, - extra: _extra, - ) - .compose( - _dio.options, - '/diary/${diary_id}/meal/${meal_id}/satiety/fill', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - final _value = _result.data!.cast(); - return _value; - } - - @override - Future> sendMoodData( - int diary_id, - int meal_id, - int mood, - ) async { - final _extra = {}; - final queryParameters = {r'mood': mood}; - final _headers = {}; - const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType>(Options( - method: 'POST', - headers: _headers, - extra: _extra, - ) - .compose( - _dio.options, - '/diary/${diary_id}/meal/${meal_id}/mood/fill', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - final _value = _result.data!.cast(); - return _value; - } - - @override - Future sendWakeupData( - int diary_id, - String wakeup, - ) async { - final _extra = {}; - final queryParameters = {r'wakeup': wakeup}; - final _headers = {}; - const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType(Options( - method: 'POST', - headers: _headers, - extra: _extra, - ) - .compose( - _dio.options, - '/diary/${diary_id}/wakeup/fill', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - final _value = DiaryModel.fromJson(_result.data!); - return _value; - } - - @override - Future sendRetire( - int diary_id, - String retire, - ) async { - final _extra = {}; - final queryParameters = {r'retire': retire}; - final _headers = {}; - const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType(Options( - method: 'POST', - headers: _headers, - extra: _extra, - ) - .compose( - _dio.options, - '/diary/${diary_id}/retire/fill', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - final _value = DiaryModel.fromJson(_result.data!); - 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(); - } -} -- 2.49.1 From 20d253313a2d4174bb79884b151bad08bcd3ba8d Mon Sep 17 00:00:00 2001 From: maxxkim Date: Mon, 15 Jul 2024 18:13:44 +0300 Subject: [PATCH 066/110] refactor(diary): Merge conflic resolve --- .../diary/presentation/bloc/diary_bloc.dart | 4 +- .../diary/repositories/diary_repository.dart | 2 +- .../diary/services/diary_service.dart | 2 +- .../diary/services/diary_service.g.dart | 270 ++++++++++++++++++ 4 files changed, 274 insertions(+), 4 deletions(-) create mode 100644 lib/features/diary/services/diary_service.g.dart diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index 06d76c4..3bd4a6e 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -242,7 +242,7 @@ class DiaryBloc extends Bloc { final productNutritionalValues = await diaryRepository.inputProduct(event.input); // Create a new controller with the input text and update the autocomplete list - var updatedState = currentState.copyWith( + /*var updatedState = currentState.copyWith( productNameController: TextEditingController(text: event.input), autocompleteList: productNutritionalValues.map((product) => product['name']).toList(), ); @@ -252,7 +252,7 @@ class DiaryBloc extends Bloc { updatedState = updatedState.copyWith(moderationExpanded: false); } - emit(updatedState); // Emit the updated state + emit(updatedState); */ } } diff --git a/lib/features/diary/repositories/diary_repository.dart b/lib/features/diary/repositories/diary_repository.dart index ce9e0fa..57aa142 100644 --- a/lib/features/diary/repositories/diary_repository.dart +++ b/lib/features/diary/repositories/diary_repository.dart @@ -22,7 +22,7 @@ class DiaryRepository { } } - Future> inputProduct(String name) async { + Future inputProduct(String name) async { try { return await diaryService.sendInputProduct(name); } catch (e) { diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart index f1ad9d9..01b6b93 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -18,7 +18,7 @@ abstract class DiaryService { Future getChart(@Path() String id); @GET('/diary/product_nutritional_values/filter?{name}') - Future> sendInputProduct(@Path() String name); + Future sendInputProduct(@Path() String name); @POST('/diary/{diary_id}/meal/{meal_id}/satiety/fill') Future> sendSatietyData( diff --git a/lib/features/diary/services/diary_service.g.dart b/lib/features/diary/services/diary_service.g.dart new file mode 100644 index 0000000..e0bff56 --- /dev/null +++ b/lib/features/diary/services/diary_service.g.dart @@ -0,0 +1,270 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'diary_service.dart'; + +// ************************************************************************** +// RetrofitGenerator +// ************************************************************************** + +// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers,unused_element + +class _DiaryService implements DiaryService { + _DiaryService( + this._dio, { + this.baseUrl, + }); + + final Dio _dio; + + String? baseUrl; + + @override + Future> getDiaryID() async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio.fetch>(_setStreamType>(Options( + method: 'GET', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/index', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = _result.data!.cast(); + return _value; + } + + @override + Future> getDiary(int id) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio.fetch>(_setStreamType>(Options( + method: 'GET', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${id}/show/', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + var _value = _result.data!.map((k, dynamic v) => MapEntry(k, DiaryModel.fromJson(v as Map))); + return _value; + } + + @override + Future getChart(String id) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio.fetch>(_setStreamType(Options( + method: 'GET', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${id}/dailyNutritionData/', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = DiaryModel.fromJson(_result.data!); + return _value; + } + + @override + Future sendInputProduct(String name) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio.fetch>(_setStreamType(Options( + method: 'GET', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/product_nutritional_values/filter?${name}', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = DiaryModel.fromJson(_result.data!); + return _value; + } + + @override + Future> sendSatietyData( + int diary_id, + int meal_id, + int satiety, + ) async { + final _extra = {}; + final queryParameters = {r'satiety': satiety}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio.fetch>(_setStreamType>(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${diary_id}/meal/${meal_id}/satiety/fill', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = _result.data!.cast(); + return _value; + } + + @override + Future> sendMoodData( + int diary_id, + int meal_id, + int mood, + ) async { + final _extra = {}; + final queryParameters = {r'mood': mood}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio.fetch>(_setStreamType>(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${diary_id}/meal/${meal_id}/mood/fill', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = _result.data!.cast(); + return _value; + } + + @override + Future sendWakeupData( + int diary_id, + String wakeup, + ) async { + final _extra = {}; + final queryParameters = {r'wakeup': wakeup}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio.fetch>(_setStreamType(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${diary_id}/wakeup/fill', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = DiaryModel.fromJson(_result.data!); + return _value; + } + + @override + Future sendRetire( + int diary_id, + String retire, + ) async { + final _extra = {}; + final queryParameters = {r'retire': retire}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio.fetch>(_setStreamType(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${diary_id}/retire/fill', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = DiaryModel.fromJson(_result.data!); + 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(); + } +} -- 2.49.1 From b5becbe6656d38ebbe89554f62a4731bfd369a37 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 17 Jul 2024 12:39:09 +0300 Subject: [PATCH 067/110] refactor(diary): API mor produc nutritional and new Product model --- lib/features/diary/models/diary,dart | 19 - lib/features/diary/models/product.dart | 32 + .../diary/models/product.freezed.dart | 548 ++++++++++++++++++ lib/features/diary/models/product.g.dart | 53 ++ .../diary/presentation/bloc/diary_bloc.dart | 119 ++-- .../diary/repositories/diary_repository.dart | 41 +- .../diary/services/diary_service.dart | 24 +- .../diary/services/diary_service.g.dart | 287 +++++---- 8 files changed, 935 insertions(+), 188 deletions(-) delete mode 100644 lib/features/diary/models/diary,dart create mode 100644 lib/features/diary/models/product.dart create mode 100644 lib/features/diary/models/product.freezed.dart create mode 100644 lib/features/diary/models/product.g.dart diff --git a/lib/features/diary/models/diary,dart b/lib/features/diary/models/diary,dart deleted file mode 100644 index f7c5935..0000000 --- a/lib/features/diary/models/diary,dart +++ /dev/null @@ -1,19 +0,0 @@ -import 'package:freezed_annotation/freezed_annotation.dart'; - -part 'diary.freezed.dart'; -part 'diary.g.dart'; - -@freezed -class Diary with _$Diary { - const factory Diary({ - required int id, - required DateTime date, - required int closed, - String? comment, - DateTime? wakeup, - DateTime? retire, - }) = _Diary; - - factory Diary.fromJson(Map json) => - _$DiaryFromJson(json); -} diff --git a/lib/features/diary/models/product.dart b/lib/features/diary/models/product.dart new file mode 100644 index 0000000..fdac1bf --- /dev/null +++ b/lib/features/diary/models/product.dart @@ -0,0 +1,32 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'product.freezed.dart'; +part 'product.g.dart'; + +@freezed +class Product with _$Product { + const factory Product({ + required int id, + required String name, + required String image, + required int productGroupId, + required String description, + required String formulations, + required int energyOn100gr, + required double proteinsOn100gr, + required double fatsOn100gr, + required double carbohydratesOn100gr, + required int portionMassGr, + required int energyOnPortion, + required int proteinsOnPortion, + required int fatsOnPortion, + required int carbohydratesOnPortion, + required String createdAt, + required String updatedAt, + required String lastState, + String? reqjectReason, + }) = _Product; + + factory Product.fromJson(Map json) => + _$ProductFromJson(json); +} diff --git a/lib/features/diary/models/product.freezed.dart b/lib/features/diary/models/product.freezed.dart new file mode 100644 index 0000000..0b829eb --- /dev/null +++ b/lib/features/diary/models/product.freezed.dart @@ -0,0 +1,548 @@ +// 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 'product.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'); + +Product _$ProductFromJson(Map json) { + return _Product.fromJson(json); +} + +/// @nodoc +mixin _$Product { + int get id => throw _privateConstructorUsedError; + String get name => throw _privateConstructorUsedError; + String get image => throw _privateConstructorUsedError; + int get productGroupId => throw _privateConstructorUsedError; + String get description => throw _privateConstructorUsedError; + String get formulations => throw _privateConstructorUsedError; + int get energyOn100gr => throw _privateConstructorUsedError; + double get proteinsOn100gr => throw _privateConstructorUsedError; + double get fatsOn100gr => throw _privateConstructorUsedError; + double get carbohydratesOn100gr => throw _privateConstructorUsedError; + int get portionMassGr => throw _privateConstructorUsedError; + int get energyOnPortion => throw _privateConstructorUsedError; + int get proteinsOnPortion => throw _privateConstructorUsedError; + int get fatsOnPortion => throw _privateConstructorUsedError; + int get carbohydratesOnPortion => throw _privateConstructorUsedError; + String get createdAt => throw _privateConstructorUsedError; + String get updatedAt => throw _privateConstructorUsedError; + String get lastState => throw _privateConstructorUsedError; + String? get reqjectReason => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $ProductCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $ProductCopyWith<$Res> { + factory $ProductCopyWith(Product value, $Res Function(Product) then) = + _$ProductCopyWithImpl<$Res, Product>; + @useResult + $Res call( + {int id, + String name, + String image, + int productGroupId, + String description, + String formulations, + int energyOn100gr, + double proteinsOn100gr, + double fatsOn100gr, + double carbohydratesOn100gr, + int portionMassGr, + int energyOnPortion, + int proteinsOnPortion, + int fatsOnPortion, + int carbohydratesOnPortion, + String createdAt, + String updatedAt, + String lastState, + String? reqjectReason}); +} + +/// @nodoc +class _$ProductCopyWithImpl<$Res, $Val extends Product> + implements $ProductCopyWith<$Res> { + _$ProductCopyWithImpl(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 = null, + Object? name = null, + Object? image = null, + Object? productGroupId = null, + Object? description = null, + Object? formulations = null, + Object? energyOn100gr = null, + Object? proteinsOn100gr = null, + Object? fatsOn100gr = null, + Object? carbohydratesOn100gr = null, + Object? portionMassGr = null, + Object? energyOnPortion = null, + Object? proteinsOnPortion = null, + Object? fatsOnPortion = null, + Object? carbohydratesOnPortion = null, + Object? createdAt = null, + Object? updatedAt = null, + Object? lastState = null, + Object? reqjectReason = freezed, + }) { + return _then(_value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + image: null == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as String, + productGroupId: null == productGroupId + ? _value.productGroupId + : productGroupId // ignore: cast_nullable_to_non_nullable + as int, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + formulations: null == formulations + ? _value.formulations + : formulations // ignore: cast_nullable_to_non_nullable + as String, + energyOn100gr: null == energyOn100gr + ? _value.energyOn100gr + : energyOn100gr // ignore: cast_nullable_to_non_nullable + as int, + proteinsOn100gr: null == proteinsOn100gr + ? _value.proteinsOn100gr + : proteinsOn100gr // ignore: cast_nullable_to_non_nullable + as double, + fatsOn100gr: null == fatsOn100gr + ? _value.fatsOn100gr + : fatsOn100gr // ignore: cast_nullable_to_non_nullable + as double, + carbohydratesOn100gr: null == carbohydratesOn100gr + ? _value.carbohydratesOn100gr + : carbohydratesOn100gr // ignore: cast_nullable_to_non_nullable + as double, + portionMassGr: null == portionMassGr + ? _value.portionMassGr + : portionMassGr // ignore: cast_nullable_to_non_nullable + as int, + energyOnPortion: null == energyOnPortion + ? _value.energyOnPortion + : energyOnPortion // ignore: cast_nullable_to_non_nullable + as int, + proteinsOnPortion: null == proteinsOnPortion + ? _value.proteinsOnPortion + : proteinsOnPortion // ignore: cast_nullable_to_non_nullable + as int, + fatsOnPortion: null == fatsOnPortion + ? _value.fatsOnPortion + : fatsOnPortion // ignore: cast_nullable_to_non_nullable + as int, + carbohydratesOnPortion: null == carbohydratesOnPortion + ? _value.carbohydratesOnPortion + : carbohydratesOnPortion // ignore: cast_nullable_to_non_nullable + as int, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as String, + updatedAt: null == updatedAt + ? _value.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as String, + lastState: null == lastState + ? _value.lastState + : lastState // ignore: cast_nullable_to_non_nullable + as String, + reqjectReason: freezed == reqjectReason + ? _value.reqjectReason + : reqjectReason // ignore: cast_nullable_to_non_nullable + as String?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$ProductImplCopyWith<$Res> implements $ProductCopyWith<$Res> { + factory _$$ProductImplCopyWith( + _$ProductImpl value, $Res Function(_$ProductImpl) then) = + __$$ProductImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {int id, + String name, + String image, + int productGroupId, + String description, + String formulations, + int energyOn100gr, + double proteinsOn100gr, + double fatsOn100gr, + double carbohydratesOn100gr, + int portionMassGr, + int energyOnPortion, + int proteinsOnPortion, + int fatsOnPortion, + int carbohydratesOnPortion, + String createdAt, + String updatedAt, + String lastState, + String? reqjectReason}); +} + +/// @nodoc +class __$$ProductImplCopyWithImpl<$Res> + extends _$ProductCopyWithImpl<$Res, _$ProductImpl> + implements _$$ProductImplCopyWith<$Res> { + __$$ProductImplCopyWithImpl( + _$ProductImpl _value, $Res Function(_$ProductImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? name = null, + Object? image = null, + Object? productGroupId = null, + Object? description = null, + Object? formulations = null, + Object? energyOn100gr = null, + Object? proteinsOn100gr = null, + Object? fatsOn100gr = null, + Object? carbohydratesOn100gr = null, + Object? portionMassGr = null, + Object? energyOnPortion = null, + Object? proteinsOnPortion = null, + Object? fatsOnPortion = null, + Object? carbohydratesOnPortion = null, + Object? createdAt = null, + Object? updatedAt = null, + Object? lastState = null, + Object? reqjectReason = freezed, + }) { + return _then(_$ProductImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + image: null == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as String, + productGroupId: null == productGroupId + ? _value.productGroupId + : productGroupId // ignore: cast_nullable_to_non_nullable + as int, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + formulations: null == formulations + ? _value.formulations + : formulations // ignore: cast_nullable_to_non_nullable + as String, + energyOn100gr: null == energyOn100gr + ? _value.energyOn100gr + : energyOn100gr // ignore: cast_nullable_to_non_nullable + as int, + proteinsOn100gr: null == proteinsOn100gr + ? _value.proteinsOn100gr + : proteinsOn100gr // ignore: cast_nullable_to_non_nullable + as double, + fatsOn100gr: null == fatsOn100gr + ? _value.fatsOn100gr + : fatsOn100gr // ignore: cast_nullable_to_non_nullable + as double, + carbohydratesOn100gr: null == carbohydratesOn100gr + ? _value.carbohydratesOn100gr + : carbohydratesOn100gr // ignore: cast_nullable_to_non_nullable + as double, + portionMassGr: null == portionMassGr + ? _value.portionMassGr + : portionMassGr // ignore: cast_nullable_to_non_nullable + as int, + energyOnPortion: null == energyOnPortion + ? _value.energyOnPortion + : energyOnPortion // ignore: cast_nullable_to_non_nullable + as int, + proteinsOnPortion: null == proteinsOnPortion + ? _value.proteinsOnPortion + : proteinsOnPortion // ignore: cast_nullable_to_non_nullable + as int, + fatsOnPortion: null == fatsOnPortion + ? _value.fatsOnPortion + : fatsOnPortion // ignore: cast_nullable_to_non_nullable + as int, + carbohydratesOnPortion: null == carbohydratesOnPortion + ? _value.carbohydratesOnPortion + : carbohydratesOnPortion // ignore: cast_nullable_to_non_nullable + as int, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as String, + updatedAt: null == updatedAt + ? _value.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as String, + lastState: null == lastState + ? _value.lastState + : lastState // ignore: cast_nullable_to_non_nullable + as String, + reqjectReason: freezed == reqjectReason + ? _value.reqjectReason + : reqjectReason // ignore: cast_nullable_to_non_nullable + as String?, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$ProductImpl implements _Product { + const _$ProductImpl( + {required this.id, + required this.name, + required this.image, + required this.productGroupId, + required this.description, + required this.formulations, + required this.energyOn100gr, + required this.proteinsOn100gr, + required this.fatsOn100gr, + required this.carbohydratesOn100gr, + required this.portionMassGr, + required this.energyOnPortion, + required this.proteinsOnPortion, + required this.fatsOnPortion, + required this.carbohydratesOnPortion, + required this.createdAt, + required this.updatedAt, + required this.lastState, + this.reqjectReason}); + + factory _$ProductImpl.fromJson(Map json) => + _$$ProductImplFromJson(json); + + @override + final int id; + @override + final String name; + @override + final String image; + @override + final int productGroupId; + @override + final String description; + @override + final String formulations; + @override + final int energyOn100gr; + @override + final double proteinsOn100gr; + @override + final double fatsOn100gr; + @override + final double carbohydratesOn100gr; + @override + final int portionMassGr; + @override + final int energyOnPortion; + @override + final int proteinsOnPortion; + @override + final int fatsOnPortion; + @override + final int carbohydratesOnPortion; + @override + final String createdAt; + @override + final String updatedAt; + @override + final String lastState; + @override + final String? reqjectReason; + + @override + String toString() { + return 'Product(id: $id, name: $name, image: $image, productGroupId: $productGroupId, description: $description, formulations: $formulations, energyOn100gr: $energyOn100gr, proteinsOn100gr: $proteinsOn100gr, fatsOn100gr: $fatsOn100gr, carbohydratesOn100gr: $carbohydratesOn100gr, portionMassGr: $portionMassGr, energyOnPortion: $energyOnPortion, proteinsOnPortion: $proteinsOnPortion, fatsOnPortion: $fatsOnPortion, carbohydratesOnPortion: $carbohydratesOnPortion, createdAt: $createdAt, updatedAt: $updatedAt, lastState: $lastState, reqjectReason: $reqjectReason)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ProductImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.name, name) || other.name == name) && + (identical(other.image, image) || other.image == image) && + (identical(other.productGroupId, productGroupId) || + other.productGroupId == productGroupId) && + (identical(other.description, description) || + other.description == description) && + (identical(other.formulations, formulations) || + other.formulations == formulations) && + (identical(other.energyOn100gr, energyOn100gr) || + other.energyOn100gr == energyOn100gr) && + (identical(other.proteinsOn100gr, proteinsOn100gr) || + other.proteinsOn100gr == proteinsOn100gr) && + (identical(other.fatsOn100gr, fatsOn100gr) || + other.fatsOn100gr == fatsOn100gr) && + (identical(other.carbohydratesOn100gr, carbohydratesOn100gr) || + other.carbohydratesOn100gr == carbohydratesOn100gr) && + (identical(other.portionMassGr, portionMassGr) || + other.portionMassGr == portionMassGr) && + (identical(other.energyOnPortion, energyOnPortion) || + other.energyOnPortion == energyOnPortion) && + (identical(other.proteinsOnPortion, proteinsOnPortion) || + other.proteinsOnPortion == proteinsOnPortion) && + (identical(other.fatsOnPortion, fatsOnPortion) || + other.fatsOnPortion == fatsOnPortion) && + (identical(other.carbohydratesOnPortion, carbohydratesOnPortion) || + other.carbohydratesOnPortion == carbohydratesOnPortion) && + (identical(other.createdAt, createdAt) || + other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt) && + (identical(other.lastState, lastState) || + other.lastState == lastState) && + (identical(other.reqjectReason, reqjectReason) || + other.reqjectReason == reqjectReason)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hashAll([ + runtimeType, + id, + name, + image, + productGroupId, + description, + formulations, + energyOn100gr, + proteinsOn100gr, + fatsOn100gr, + carbohydratesOn100gr, + portionMassGr, + energyOnPortion, + proteinsOnPortion, + fatsOnPortion, + carbohydratesOnPortion, + createdAt, + updatedAt, + lastState, + reqjectReason + ]); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$ProductImplCopyWith<_$ProductImpl> get copyWith => + __$$ProductImplCopyWithImpl<_$ProductImpl>(this, _$identity); + + @override + Map toJson() { + return _$$ProductImplToJson( + this, + ); + } +} + +abstract class _Product implements Product { + const factory _Product( + {required final int id, + required final String name, + required final String image, + required final int productGroupId, + required final String description, + required final String formulations, + required final int energyOn100gr, + required final double proteinsOn100gr, + required final double fatsOn100gr, + required final double carbohydratesOn100gr, + required final int portionMassGr, + required final int energyOnPortion, + required final int proteinsOnPortion, + required final int fatsOnPortion, + required final int carbohydratesOnPortion, + required final String createdAt, + required final String updatedAt, + required final String lastState, + final String? reqjectReason}) = _$ProductImpl; + + factory _Product.fromJson(Map json) = _$ProductImpl.fromJson; + + @override + int get id; + @override + String get name; + @override + String get image; + @override + int get productGroupId; + @override + String get description; + @override + String get formulations; + @override + int get energyOn100gr; + @override + double get proteinsOn100gr; + @override + double get fatsOn100gr; + @override + double get carbohydratesOn100gr; + @override + int get portionMassGr; + @override + int get energyOnPortion; + @override + int get proteinsOnPortion; + @override + int get fatsOnPortion; + @override + int get carbohydratesOnPortion; + @override + String get createdAt; + @override + String get updatedAt; + @override + String get lastState; + @override + String? get reqjectReason; + @override + @JsonKey(ignore: true) + _$$ProductImplCopyWith<_$ProductImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/diary/models/product.g.dart b/lib/features/diary/models/product.g.dart new file mode 100644 index 0000000..566a7b4 --- /dev/null +++ b/lib/features/diary/models/product.g.dart @@ -0,0 +1,53 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'product.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$ProductImpl _$$ProductImplFromJson(Map json) => + _$ProductImpl( + id: (json['id'] as num).toInt(), + name: json['name'] as String, + image: json['image'] as String, + productGroupId: (json['productGroupId'] as num).toInt(), + description: json['description'] as String, + formulations: json['formulations'] as String, + energyOn100gr: (json['energyOn100gr'] as num).toInt(), + proteinsOn100gr: (json['proteinsOn100gr'] as num).toDouble(), + fatsOn100gr: (json['fatsOn100gr'] as num).toDouble(), + carbohydratesOn100gr: (json['carbohydratesOn100gr'] as num).toDouble(), + portionMassGr: (json['portionMassGr'] as num).toInt(), + energyOnPortion: (json['energyOnPortion'] as num).toInt(), + proteinsOnPortion: (json['proteinsOnPortion'] as num).toInt(), + fatsOnPortion: (json['fatsOnPortion'] as num).toInt(), + carbohydratesOnPortion: (json['carbohydratesOnPortion'] as num).toInt(), + createdAt: json['createdAt'] as String, + updatedAt: json['updatedAt'] as String, + lastState: json['lastState'] as String, + reqjectReason: json['reqjectReason'] as String?, + ); + +Map _$$ProductImplToJson(_$ProductImpl instance) => + { + 'id': instance.id, + 'name': instance.name, + 'image': instance.image, + 'productGroupId': instance.productGroupId, + 'description': instance.description, + 'formulations': instance.formulations, + 'energyOn100gr': instance.energyOn100gr, + 'proteinsOn100gr': instance.proteinsOn100gr, + 'fatsOn100gr': instance.fatsOn100gr, + 'carbohydratesOn100gr': instance.carbohydratesOn100gr, + 'portionMassGr': instance.portionMassGr, + 'energyOnPortion': instance.energyOnPortion, + 'proteinsOnPortion': instance.proteinsOnPortion, + 'fatsOnPortion': instance.fatsOnPortion, + 'carbohydratesOnPortion': instance.carbohydratesOnPortion, + 'createdAt': instance.createdAt, + 'updatedAt': instance.updatedAt, + 'lastState': instance.lastState, + 'reqjectReason': instance.reqjectReason, + }; diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index 3bd4a6e..4df22df 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:eatvio_app/features/diary/models/meal.dart'; +import 'package:eatvio_app/features/diary/models/product.dart'; import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; import 'package:intl/intl.dart'; import 'package:equatable/equatable.dart'; @@ -18,7 +19,8 @@ part 'diary_event.dart'; class DiaryBloc extends Bloc { final DiaryRepository diaryRepository; - DiaryBloc({required this.diaryRepository}) : super(const DiaryState.loading()) { + DiaryBloc({required this.diaryRepository}) + : super(const DiaryState.loading()) { on(loadDiary); on(_changeSatiety); // пользователь нажимает на шкалу сытости on(_changeMood); // пользователь нажимает на шкалу настроения @@ -57,7 +59,10 @@ class DiaryBloc extends Bloc { final int? diaryID = data['id']; final DiaryModel diary = await diaryRepository.getDiary(diaryID ?? 45); final Meal currentMeal = diary.meals[0]; - List portionList = [SelectionPopupModel(title: "gr"), SelectionPopupModel(title: "pcs")]; + List portionList = [ + SelectionPopupModel(title: "gr"), + SelectionPopupModel(title: "pcs") + ]; List mealList = [ SelectionPopupModel(title: "Прием пищи 1", id: 1), SelectionPopupModel(title: "Прием пищи 2", id: 2), @@ -114,14 +119,22 @@ class DiaryBloc extends Bloc { if (responseChart.statusCode == 200) { final responseBody = jsonDecode(responseChart.body); - final recommendedChartValues = responseBody['dailyNutritionRecommendation'].values.map((value) => convertToInt(value)).toList(); + final recommendedChartValues = + responseBody['dailyNutritionRecommendation'] + .values + .map((value) => convertToInt(value)) + .toList(); - final consumedChartValues = responseBody['dailyNutritionIntake'].values.map((value) => convertToInt(value)).toList(); + final consumedChartValues = responseBody['dailyNutritionIntake'] + .values + .map((value) => convertToInt(value)) + .toList(); print([recommendedChartValues, consumedChartValues]); return [recommendedChartValues, consumedChartValues]; } else { - emit(DiaryStateError(errorMessage: 'Ошибка при декодировании данных КБЖУ')); + emit(DiaryStateError( + errorMessage: 'Ошибка при декодировании данных КБЖУ')); print('fail'); return [[], []]; // Return empty lists instead of -1 } @@ -148,8 +161,10 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = currentState.copyWith(selectedSatiety: event.selectedElement); - diaryRepository.changeSatiety(event.selectedElement, currentState.currentMeal.id, currentState.diary.id); + var updatedState = + currentState.copyWith(selectedSatiety: event.selectedElement); + diaryRepository.changeSatiety(event.selectedElement, + currentState.currentMeal.id, currentState.diary.id); emit(updatedState); } } @@ -160,9 +175,11 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = currentState.copyWith(selectedMood: event.selectedElement); + var updatedState = + currentState.copyWith(selectedMood: event.selectedElement); - diaryRepository.changeMood(event.selectedElement, currentState.currentMeal.id, currentState.diary.id); + diaryRepository.changeMood(event.selectedElement, + currentState.currentMeal.id, currentState.diary.id); emit(updatedState); // Передаем обновленное состояние в emit } @@ -174,9 +191,11 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = currentState.copyWith(wakeupController: event.selectedTime); + var updatedState = + currentState.copyWith(wakeupController: event.selectedTime); final DateFormat formatter = DateFormat('HH:mm'); - final String wakeupString = formatter.format(DateTime(2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); + final String wakeupString = formatter.format(DateTime( + 2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); await diaryRepository.changeWakeup( currentState.diary.id, wakeupString, @@ -191,9 +210,11 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = currentState.copyWith(retireController: event.selectedTime); + var updatedState = + currentState.copyWith(retireController: event.selectedTime); final DateFormat formatter = DateFormat('HH:mm'); - final String retireString = formatter.format(DateTime(2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); + final String retireString = formatter.format(DateTime( + 2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); await diaryRepository.changeRetire( currentState.diary.id, retireString, @@ -219,7 +240,8 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { final currentState = state as DiaryStateLoaded; - final Meal meal = currentState.diary.meals.firstWhere((meal) => meal.type == event.value.id); + final Meal meal = currentState.diary.meals + .firstWhere((meal) => meal.type == event.value.id); DiaryStateLoaded updatedState = currentState.copyWith( currentMeal: meal, portions: meal.portions, @@ -239,8 +261,9 @@ class DiaryBloc extends Bloc { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - final productNutritionalValues = await diaryRepository.inputProduct(event.input); - + final Map> productNutritionalValues = + await diaryRepository.inputProduct(event.input); + print(productNutritionalValues); // Create a new controller with the input text and update the autocomplete list /*var updatedState = currentState.copyWith( productNameController: TextEditingController(text: event.input), @@ -309,52 +332,18 @@ class DiaryBloc extends Bloc { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var response = await sendPortionData( - currentState.productNameController.text, - currentState.portionController.id == 0 ? 'pcs' : 'gr', - int.parse(currentState.productQuantityController.text), - currentState.currentMeal.id, + await diaryRepository.addPortion( currentState.diary.id, + currentState.currentMeal.id, + currentState.productNameController.text, + currentState.portionController.value, + int.parse(currentState.productQuantityController.text), ); - if (response.statusCode == 200) { - emit(currentState.copyWith(isAdded: true)); - await reloadScreen(event, emit); - } else { - print( - 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}', - ); - } + emit(currentState.copyWith(isAdded: true)); } } - FutureOr sendPortionData( - String? name, - String portion, - int? quantity, - int? mealID, - int diaryID, - ) async { - String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/create'; - - final Map credentials = { - 'product_name': name, - 'portion': portion, - 'quantity': quantity, - }; - - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - Future _removePortion( RemovePortionEvent event, Emitter emit, @@ -362,7 +351,8 @@ class DiaryBloc extends Bloc { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - int? mealId = currentState.currentMeal.id; // Rename id to mealId for clarity + int? mealId = + currentState.currentMeal.id; // Rename id to mealId for clarity var response = await sendRemovePortion( event.portionId, @@ -385,7 +375,8 @@ class DiaryBloc extends Bloc { int? mealID, int diaryID, ) async { - String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete'; + String url = + '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete'; var response = await http.delete( Uri.parse(url), @@ -428,7 +419,8 @@ class DiaryBloc extends Bloc { int? mealID, int diaryID, ) async { - String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete'; + String url = + '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete'; final Map credentials = { 'id': photoID, 'path': path, @@ -469,8 +461,10 @@ class DiaryBloc extends Bloc { String? comment, ) async { final formatter = DateFormat('HH:mm'); - final wakeupString = formatter.format(DateTime(2022, 1, 1, wakeup!.hour, wakeup.minute)); - final retireString = formatter.format(DateTime(2022, 1, 1, retire!.hour, retire.minute)); + final wakeupString = + formatter.format(DateTime(2022, 1, 1, wakeup!.hour, wakeup.minute)); + final retireString = + formatter.format(DateTime(2022, 1, 1, retire!.hour, retire.minute)); final Map credentials = { 'wakeup': wakeupString, @@ -514,7 +508,8 @@ class DiaryBloc extends Bloc { int diaryID, int mealId, ) async { - String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload'; + String url = + '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload'; var request = http.MultipartRequest('POST', Uri.parse(url)); diff --git a/lib/features/diary/repositories/diary_repository.dart b/lib/features/diary/repositories/diary_repository.dart index 57aa142..12268fb 100644 --- a/lib/features/diary/repositories/diary_repository.dart +++ b/lib/features/diary/repositories/diary_repository.dart @@ -1,4 +1,5 @@ import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:eatvio_app/features/diary/models/product.dart'; import 'package:eatvio_app/features/diary/services/diary_service.dart'; class DiaryRepository { @@ -22,9 +23,9 @@ class DiaryRepository { } } - Future inputProduct(String name) async { + Future>> inputProduct(String name) async { try { - return await diaryService.sendInputProduct(name); + return await diaryService.getInputProduct(name); } catch (e) { rethrow; } @@ -81,4 +82,40 @@ class DiaryRepository { rethrow; } } + + Future addPortion( + int diaryID, + int mealID, + String name, + String product, + int quantity, + ) async { + try { + await diaryService.sendPortionData( + diaryID, + mealID, + name, + product, + quantity, + ); + } catch (e) { + rethrow; + } + } + + Future removePortion( + int diaryID, + int mealID, + int portionID, + ) async { + try { + await diaryService.sendRemovePortionData( + diaryID, + mealID, + portionID, + ); + } catch (e) { + rethrow; + } + } } diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart index 01b6b93..3ec5a5b 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -1,5 +1,6 @@ import 'package:dio/dio.dart'; import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:eatvio_app/features/diary/models/product.dart'; import 'package:retrofit/retrofit.dart'; part 'diary_service.g.dart'; @@ -17,8 +18,9 @@ abstract class DiaryService { @GET('/diary/{id}/dailyNutritionData/') Future getChart(@Path() String id); - @GET('/diary/product_nutritional_values/filter?{name}') - Future sendInputProduct(@Path() String name); + @GET('/diary/product_nutritional_values/filter') + Future>> getInputProduct( + @Query('name') String name); @POST('/diary/{diary_id}/meal/{meal_id}/satiety/fill') Future> sendSatietyData( @@ -41,8 +43,24 @@ abstract class DiaryService { ); @POST('/diary/{diary_id}/retire/fill') - Future sendRetire( + Future sendRetireData( @Path() int diary_id, @Query('retire') String retire, ); + + @POST('/diary/{diary_id}/meal/{meal_id}/portions/create') + Future> sendPortionData( + @Path() int diary_id, + @Path() int meal_id, + @Query('product_name') String product_name, + @Query('portion') String portion, + @Query('quantity') int quantity, + ); + + @POST('/diary/{diary_id}/meal/{meal_id}/portions/{portion_id}/delete') + Future> sendRemovePortionData( + @Path() int diary_id, + @Path() int meal_id, + @Path() int portion_id, + ); } diff --git a/lib/features/diary/services/diary_service.g.dart b/lib/features/diary/services/diary_service.g.dart index e0bff56..80461b5 100644 --- a/lib/features/diary/services/diary_service.g.dart +++ b/lib/features/diary/services/diary_service.g.dart @@ -24,22 +24,23 @@ class _DiaryService implements DiaryService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType>(Options( + final _result = await _dio + .fetch>(_setStreamType>(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/diary/index', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/diary/index', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = _result.data!.cast(); return _value; } @@ -50,23 +51,25 @@ class _DiaryService implements DiaryService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType>(Options( + final _result = await _dio.fetch>( + _setStreamType>(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/diary/${id}/show/', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - var _value = _result.data!.map((k, dynamic v) => MapEntry(k, DiaryModel.fromJson(v as Map))); + .compose( + _dio.options, + '/diary/${id}/show/', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + var _value = _result.data!.map((k, dynamic v) => + MapEntry(k, DiaryModel.fromJson(v as Map))); return _value; } @@ -76,49 +79,55 @@ class _DiaryService implements DiaryService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio + .fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/diary/${id}/dailyNutritionData/', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/diary/${id}/dailyNutritionData/', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = DiaryModel.fromJson(_result.data!); return _value; } @override - Future sendInputProduct(String name) async { + Future>> getInputProduct(String name) async { final _extra = {}; - final queryParameters = {}; + final queryParameters = {r'name': name}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio.fetch>( + _setStreamType>>(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/diary/product_nutritional_values/filter?${name}', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - final _value = DiaryModel.fromJson(_result.data!); + .compose( + _dio.options, + '/diary/product_nutritional_values/filter', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + var _value = _result.data!.map((k, dynamic v) => MapEntry( + k, + (v as List) + .map((i) => Product.fromJson(i as Map)) + .toList())); return _value; } @@ -132,22 +141,23 @@ class _DiaryService implements DiaryService { final queryParameters = {r'satiety': satiety}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType>(Options( + final _result = await _dio + .fetch>(_setStreamType>(Options( method: 'POST', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/diary/${diary_id}/meal/${meal_id}/satiety/fill', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/diary/${diary_id}/meal/${meal_id}/satiety/fill', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = _result.data!.cast(); return _value; } @@ -162,22 +172,23 @@ class _DiaryService implements DiaryService { final queryParameters = {r'mood': mood}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType>(Options( + final _result = await _dio + .fetch>(_setStreamType>(Options( method: 'POST', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/diary/${diary_id}/meal/${meal_id}/mood/fill', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/diary/${diary_id}/meal/${meal_id}/mood/fill', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = _result.data!.cast(); return _value; } @@ -191,28 +202,29 @@ class _DiaryService implements DiaryService { final queryParameters = {r'wakeup': wakeup}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio + .fetch>(_setStreamType(Options( method: 'POST', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/diary/${diary_id}/wakeup/fill', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/diary/${diary_id}/wakeup/fill', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = DiaryModel.fromJson(_result.data!); return _value; } @override - Future sendRetire( + Future sendRetireData( int diary_id, String retire, ) async { @@ -220,28 +232,99 @@ class _DiaryService implements DiaryService { final queryParameters = {r'retire': retire}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio + .fetch>(_setStreamType(Options( method: 'POST', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/diary/${diary_id}/retire/fill', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/diary/${diary_id}/retire/fill', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = DiaryModel.fromJson(_result.data!); return _value; } + @override + Future> sendPortionData( + int diary_id, + int meal_id, + String product_name, + String portion, + int quantity, + ) async { + final _extra = {}; + final queryParameters = { + r'product_name': product_name, + r'portion': portion, + r'quantity': quantity, + }; + final _headers = {}; + const Map? _data = null; + final _result = await _dio + .fetch>(_setStreamType>(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${diary_id}/meal/${meal_id}/portions/create', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = _result.data!.cast(); + return _value; + } + + @override + Future> sendRemovePortionData( + int diary_id, + int meal_id, + int portion_id, + ) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio + .fetch>(_setStreamType>(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${diary_id}/meal/${meal_id}/portions/${portion_id}/delete', + 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 != dynamic && + !(requestOptions.responseType == ResponseType.bytes || + requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { -- 2.49.1 From dbe8ac09992eeb26b39b0675db24db0523eeed13 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 17 Jul 2024 12:39:31 +0300 Subject: [PATCH 068/110] refactor(diary): API mor produc nutritional and new Product model --- lib/features/diary/presentation/bloc/diary_bloc.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index 4df22df..216131f 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -259,7 +259,7 @@ class DiaryBloc extends Bloc { Emitter emit, ) async { if (state is DiaryStateLoaded) { - var currentState = state as DiaryStateLoaded; + //var currentState = state as DiaryStateLoaded; final Map> productNutritionalValues = await diaryRepository.inputProduct(event.input); -- 2.49.1 From 220206ae1c3863447317f2076a11c010f50612b5 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Wed, 17 Jul 2024 12:48:38 +0300 Subject: [PATCH 069/110] =?UTF-8?q?feature(registration):=20=D1=80=D0=B5?= =?UTF-8?q?=D0=B4=D0=B8=D0=B7=D0=B0=D0=B9=D0=BD=20=D0=B0=D0=B2=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D0=B8,=20=D0=B4=D0=BE?= =?UTF-8?q?=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B0=20=D0=BE=D1=84=D0=B5?= =?UTF-8?q?=D1=80=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../initialization_cubit.dart | 6 +- .../registration_cubit.dart | 4 +- .../pages/additional_information_screen.dart | 56 ++-- .../presentation/pages/allergies_screen.dart | 44 +-- .../pages/blood_pressure_screen.dart | 180 +++++------ .../pages/body_circumferences_screen.dart | 95 +++--- .../pages/city_of_living_screen.dart | 117 ++++--- .../pages/credentials_screen.dart | 111 +++---- .../pages/date_of_birth_screen.dart | 52 ++-- .../pages/favorite_foods_screen.dart | 79 +++-- .../pages/favorite_sports_screen.dart | 45 ++- .../presentation/pages/gender_screen.dart | 92 +++--- .../presentation/pages/height_screen.dart | 59 ++-- .../pages/language_select_screen.dart | 25 +- .../pages/medicine_intake_screen.dart | 54 ++-- .../presentation/pages/name_screen.dart | 61 ++-- .../pages/registration_screen.dart | 286 +++++++++--------- .../presentation/pages/weight_screen.dart | 59 ++-- .../en_us/en_us_translations.dart | 2 +- lib/localization/ru/ru_translations.dart | 2 +- .../auth/auth_screen/auth_screen.dart | 211 ++++++------- lib/widgets/custom_drop_down.dart | 80 ++--- lib/widgets/custom_text_form_field.dart | 223 +++++--------- 23 files changed, 899 insertions(+), 1044 deletions(-) diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index 2052a25..4a1bcaf 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -9,7 +9,7 @@ import 'package:eatvio_app/locator_service.dart'; class InitializationCubit extends Cubit { final ChatRepository chatRepository; - bool wasInitializated = false; + bool wasInitialized = false; InitializationCubit({required this.chatRepository}) : super(const InitializationState.loading()); @@ -50,8 +50,8 @@ class InitializationCubit extends Cubit { } Future runInitialization() async { - if (!wasInitializated) { - wasInitializated = true; + if (!wasInitialized) { + wasInitialized = true; try { await TokenStorage.haveTokenInStorage(); final wsUrl = await chatRepository.getWebsocket(); diff --git a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart index 4d06c95..f9e767f 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart @@ -19,11 +19,11 @@ class RegistrationCubit extends Cubit { email: '', password: '', passwordConfirmation: '', - birthdate: DateTime.now().toString(), + birthdate: '', gender: '', country: '', city: '', - lang: 'Русский', + lang: '', weight: 0, height: 0, chestCircumference: 0, diff --git a/lib/features/registration/presentation/pages/additional_information_screen.dart b/lib/features/registration/presentation/pages/additional_information_screen.dart index b1838fd..159a599 100644 --- a/lib/features/registration/presentation/pages/additional_information_screen.dart +++ b/lib/features/registration/presentation/pages/additional_information_screen.dart @@ -15,46 +15,42 @@ class AdditionalInformationScreen extends StatefulWidget { class _AdditionalInformationScreenState extends State { final editTextController = TextEditingController(); + final editFocusNode = FocusNode(); @override void initState() { super.initState(); editTextController.text = widget.sheet.additionalInfo; + editFocusNode.requestFocus(); } @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)); - }, - ), - ], - ), + padding: EdgeInsets.only(bottom: 80, left: 16, right: 16, top: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Дополнительная информация', + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.start, + ), + SizedBox(height: 4), + CustomTextFormField( + controller: editTextController, + hintText: "У меня крепкое здоровье, но последнее время часто утомляюсь, однако, это мне не мешает радоваться жизни", + textInputAction: TextInputAction.done, + maxLines: 8, + focusNode: editFocusNode, + autofocus: true, + 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 index 3261c92..5a4e4bc 100644 --- a/lib/features/registration/presentation/pages/allergies_screen.dart +++ b/lib/features/registration/presentation/pages/allergies_screen.dart @@ -15,38 +15,38 @@ class AllergiesScreen extends StatefulWidget { class _AllergiesScreenState extends State { final enterInformationController = TextEditingController(); + final infoFocusNode = FocusNode(); @override void initState() { super.initState(); enterInformationController.text = widget.sheet.aboutAllergy; + infoFocusNode.requestFocus(); } @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)); - }, - ), - ], - ), + padding: EdgeInsets.only(bottom: 80, left: 16, right: 16, top: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("allergies_presence".tr), + SizedBox(height: 4), + CustomTextFormField( + controller: enterInformationController, + hintText: 'Например: орехи, мёд и т.д.', + textInputAction: TextInputAction.done, + focusNode: infoFocusNode, + autofocus: true, + minLines: 2, + 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 index ef69278..d22cf32 100644 --- a/lib/features/registration/presentation/pages/blood_pressure_screen.dart +++ b/lib/features/registration/presentation/pages/blood_pressure_screen.dart @@ -33,125 +33,93 @@ class _BloodPressureScreenState extends State { final digitsOnly = FilteringTextInputFormatter.digitsOnly; final upPressureController = TextEditingController(); final downPressureController = TextEditingController(); + final upFocusNode = FocusNode(); @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]; + if (widget.sheet.bloodPressureUp != 0) upPressureController.text = widget.sheet.bloodPressureUp.toString(); + if (widget.sheet.bloodPressureDown != 0) 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]; + upFocusNode.requestFocus(); } @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, - ), + padding: EdgeInsets.only(bottom: 80, left: 16, right: 16, top: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("up_pressure".tr), + SizedBox(height: 4), + CustomTextFormField( + inputFormatters: [digitsOnly], + controller: upPressureController, + autofocus: true, + focusNode: upFocusNode, + hintText: "90".tr, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(bloodPressureUp: int.parse(newValue))); + }, + ), + SizedBox(height: 16), + Text("down_pressure".tr), + SizedBox(height: 4), + 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: 16), + Text("do_you_have_hypotension_tendency".tr), + SizedBox(height: 4), + 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), ), - 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))); - }, - ), - ], - ), + 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: 16), + Text("do_you_have_hypertension_tendency".tr), + SizedBox(height: 4), + 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), ), - 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!)); - }); - }, - ), - ), - ], - ), + 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 index c537084..a086da3 100644 --- a/lib/features/registration/presentation/pages/body_circumferences_screen.dart +++ b/lib/features/registration/presentation/pages/body_circumferences_screen.dart @@ -19,6 +19,7 @@ class _BodyCircumferencesScreenState extends State { final chestCircumferenceController = TextEditingController(); final waistCircumferenceController = TextEditingController(); final hipCircumferenceController = TextEditingController(); + final chestFocus = FocusNode(); @override void initState() { @@ -26,61 +27,55 @@ class _BodyCircumferencesScreenState extends State { 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(); + chestFocus.requestFocus(); } @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))); - }, - ), - ], - ), + padding: EdgeInsets.only(bottom: 80, left: 16, right: 16, top: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("chest_circumference".tr), + SizedBox(height: 4), + CustomTextFormField( + inputFormatters: [digitsOnly], + autofocus: true, + focusNode: chestFocus, + controller: chestCircumferenceController, + hintText: "90".tr, + onChanged: (value) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(chestCircumference: int.parse(value))); + }, + ), + SizedBox(height: 16), + Text("waist_circumference".tr), + SizedBox(height: 4), + 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: 16), + Text("hip_circumference".tr), + SizedBox(height: 4), + 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 index 0372d8b..02e5c65 100644 --- a/lib/features/registration/presentation/pages/city_of_living_screen.dart +++ b/lib/features/registration/presentation/pages/city_of_living_screen.dart @@ -3,6 +3,7 @@ import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_m 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:eatvio_app/widgets/custom_edit_text_form_field.dart'; import 'package:flutter/material.dart'; import 'package:flutter_typeahead/flutter_typeahead.dart'; @@ -26,62 +27,82 @@ class _CityOfLivingScreenState extends State { @override void initState() { super.initState(); - selectedItem = dropdownItemList[0]; - final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(country: selectedItem.title)); + if (widget.sheet.country.isNotEmpty) { + selectedItem = dropdownItemList.firstWhere((item) => item.title == widget.sheet.country); + } else { + selectedItem = dropdownItemList.first; + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(country: selectedItem.title)); + } + if (widget.sheet.city.isNotEmpty) { + cityController.text = widget.sheet.city; + } } @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)); - }, + padding: EdgeInsets.only(bottom: 80, right: 16, left: 16, top: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("country".tr), + SizedBox(height: 4), + 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), ), - SizedBox(height: 22.v), - Text("Населенный пункт", style: theme.textTheme.bodyLarge), - SizedBox(height: 2.v), - TypeAheadField( + 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: 16), + Text("Населенный пункт"), + SizedBox(height: 4), + TypeAheadField( + debounceDuration: Duration.zero, + controller: cityController, + builder: (context, controller, focus) => CustomTextFormField( 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(); - }, + focusNode: focus, + textStyle: TextStyle( + fontSize: 16, + color: Colors.black, + ) ), - ], - ), + itemBuilder: (BuildContext context, String item) { + return Padding( + padding: const EdgeInsets.all(8.0), + child: Text(item, style: theme.textTheme.bodyLarge?.copyWith(color: Colors.black)), + ); + }, + decorationBuilder: (context, child) => Material( + type: MaterialType.card, + elevation: 4, + borderRadius: BorderRadius.circular(8), + child: child, + ), + 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 index 3175b5c..7fa37be 100644 --- a/lib/features/registration/presentation/pages/credentials_screen.dart +++ b/lib/features/registration/presentation/pages/credentials_screen.dart @@ -34,61 +34,62 @@ class _CredentialsScreenState extends State { @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)); - }, - ), - ], - ), + padding: EdgeInsets.only(bottom: 80, top: 16, left: 16, right: 16), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("email".tr), + SizedBox(height: 4), + CustomTextFormField( + controller: emailController, + textInputType: TextInputType.emailAddress, + hintText: 'Введите email', + textInputAction: TextInputAction.next, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(email: newValue)); + }, + ), + SizedBox(height: 16), + Text("username".tr), + SizedBox(height: 4), + CustomTextFormField( + controller: nameController, + hintText: 'Введите имя пользователя', + textInputAction: TextInputAction.next, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(name: newValue)); + }, + ), + SizedBox(height: 16), + Text("password".tr), + SizedBox(height: 4), + CustomTextFormField( + obscureText: true, + controller: passwordController, + hintText: 'Введите пароль', + textInputAction: TextInputAction.next, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(password: newValue)); + }, + ), + SizedBox(height: 16), + Text("password_confirmation".tr), + SizedBox(height: 4), + CustomTextFormField( + obscureText: true, + controller: passwordConfirmationController, + textInputAction: TextInputAction.done, + hintText: 'Подтвердите пароль', + 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 index 54e1935..8d510c1 100644 --- a/lib/features/registration/presentation/pages/date_of_birth_screen.dart +++ b/lib/features/registration/presentation/pages/date_of_birth_screen.dart @@ -2,6 +2,7 @@ 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:flutter/material.dart'; import 'package:intl/intl.dart'; class DateOfBirthScreen extends StatefulWidget { @@ -23,48 +24,33 @@ class _DateOfBirthScreenState extends State { selectedDate = DateFormat('yyyy-mm-dd').parse(widget.sheet.birthdate); } else { selectedDate = DateTime.now(); + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(birthdate: DateTime.now().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("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), + padding: EdgeInsets.only(bottom: 80, top: 16, left: 16, right: 16), 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), + Text("date_of_birth".tr), + SizedBox(height: 4), + ListTile( + onTap: onTapCalendar(context), + leading: Icon(Icons.calendar_month_rounded, color: appTheme.blueA400), + trailing: Icon(Icons.keyboard_arrow_down_rounded), + title: Text(selectedDate.format('dd MMMM yyyy', 'ru')), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + side: BorderSide( + color: Colors.grey.shade400, + width: 1, + ), ), ), - SizedBox(height: 6.v), ], ), ); @@ -74,7 +60,9 @@ class _DateOfBirthScreenState extends State { return () { _showDialog( CupertinoDatePicker( - initialDateTime: DateTime.now(), + initialDateTime: selectedDate, + maximumDate: DateTime.now(), + minimumDate: DateTime(1900), mode: CupertinoDatePickerMode.date, onDateTimeChanged: (DateTime newDateTime) { setState(() { diff --git a/lib/features/registration/presentation/pages/favorite_foods_screen.dart b/lib/features/registration/presentation/pages/favorite_foods_screen.dart index d17b5e1..bab999a 100644 --- a/lib/features/registration/presentation/pages/favorite_foods_screen.dart +++ b/lib/features/registration/presentation/pages/favorite_foods_screen.dart @@ -16,61 +16,52 @@ class FavoriteFoodsScreen extends StatefulWidget { class _FavoriteFoodsScreenState extends State { final favoriteFoodsController = TextEditingController(); final unFavoriteFoodsController = TextEditingController(); + final favoriteFocusNode = FocusNode(); @override void initState() { super.initState(); favoriteFoodsController.text = widget.sheet.favoriteFoods; unFavoriteFoodsController.text = widget.sheet.unfavoriteFoods; + favoriteFocusNode.requestFocus(); } @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)); - }, - ), - ], - ), + padding: EdgeInsets.only(bottom: 80, left: 16, right: 16, top: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("favorite_foods".tr), + SizedBox(height: 4), + CustomTextFormField( + controller: favoriteFoodsController, + hintText: "enter_information".tr, + maxLines: 7, + minLines: 2, + focusNode: favoriteFocusNode, + autofocus: true, + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(favoriteFoods: newValue)); + }, + ), + SizedBox(height: 16), + Text("unfavorite_foods".tr), + SizedBox(height: 4), + CustomTextFormField( + controller: unFavoriteFoodsController, + hintText: "enter_information".tr, + textInputAction: TextInputAction.done, + maxLines: 7, + minLines: 2, + 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 index 55273ec..2856ea7 100644 --- a/lib/features/registration/presentation/pages/favorite_sports_screen.dart +++ b/lib/features/registration/presentation/pages/favorite_sports_screen.dart @@ -15,40 +15,37 @@ class FavoriteSportsScreen extends StatefulWidget { class _FavoriteSportsScreenState extends State { final enterInformationController = TextEditingController(); + final infoFocusNode = FocusNode(); @override void initState() { super.initState(); enterInformationController.text = widget.sheet.aboutSportHobbies; + infoFocusNode.requestFocus(); } @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)); - }, - ), - ], - ), + padding: EdgeInsets.only(bottom: 80, left: 16, right: 16, top: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("your_favorite_sports".tr), + SizedBox(height: 4), + CustomTextFormField( + controller: enterInformationController, + hintText: "Я занимаюсь плаванием , почти каждый вечер прогулки на свежем воздухе, пару раз в месяц играю в волейбол. Стараюсь не сидеть на месте!", + textInputAction: TextInputAction.done, + focusNode: infoFocusNode, + autofocus: true, + 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 index 6225826..d1bec2f 100644 --- a/lib/features/registration/presentation/pages/gender_screen.dart +++ b/lib/features/registration/presentation/pages/gender_screen.dart @@ -24,55 +24,53 @@ class _GenderScreenState extends State { @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, - ), + padding: EdgeInsets.only(bottom: 80, top: 16, left: 16, right: 16), + child: Column( + children: [ + RadioListTile( + contentPadding: EdgeInsets.zero, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), ), - 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, - ), + 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, ), - ], - ), + ), + SizedBox(height: 16), + RadioListTile( + contentPadding: EdgeInsets.zero, + 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 index 98fc71f..2aea369 100644 --- a/lib/features/registration/presentation/pages/height_screen.dart +++ b/lib/features/registration/presentation/pages/height_screen.dart @@ -16,51 +16,40 @@ class HeightScreen extends StatefulWidget { class _HeightScreenState extends State { final heightController = TextEditingController(); + final heightFocus = FocusNode(); @override void initState() { super.initState(); if (widget.sheet.height != 0) heightController.text = widget.sheet.height.toString(); + heightFocus.requestFocus(); } @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))); - }, - ), - ], - ), - ], - ), + padding: EdgeInsets.only(bottom: 80, left: 16, right: 16, top: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("your_height".tr), + SizedBox(height: 4), + CustomTextFormField( + textInputAction: TextInputAction.done, + autofocus: true, + focusNode: heightFocus, + hintText: 'см', + 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 index c770c0c..4d95033 100644 --- a/lib/features/registration/presentation/pages/language_select_screen.dart +++ b/lib/features/registration/presentation/pages/language_select_screen.dart @@ -18,34 +18,31 @@ class _LanguageSelectScreenState extends State { SelectionPopupModel(id: 1, title: "Русский", isSelected: true), ]; - SelectionPopupModel? value; + late SelectionPopupModel value; @override void initState() { super.initState(); if (widget.sheet.lang.isNotEmpty) { + value = dropdownItemList.firstWhere((item) => item.title == widget.sheet.lang); + } else { value = dropdownItemList.first; + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(lang: value.title)); } } @override Widget build(BuildContext context) { return SingleChildScrollView( - padding: EdgeInsets.only(bottom: 80), + padding: EdgeInsets.only(bottom: 80, right: 16, left: 16, top: 16), child: Column( + crossAxisAlignment: CrossAxisAlignment.start, 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, - ), + Text( + "preferred_language".tr, ), - const SizedBox(height: 32), + const SizedBox(height: 4), CustomDropDown( value: value, hintText: "Не выбрано".tr, @@ -53,7 +50,7 @@ class _LanguageSelectScreenState extends State { onChanged: (SelectionPopupModel newValue) => setState(() { value = newValue; final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(lang: value!.title)); + 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 index d6ea9fb..fc09d08 100644 --- a/lib/features/registration/presentation/pages/medicine_intake_screen.dart +++ b/lib/features/registration/presentation/pages/medicine_intake_screen.dart @@ -15,48 +15,38 @@ class MedicineIntakeScreen extends StatefulWidget { class _MedicineIntakeScreenState extends State { final enterInformationController = TextEditingController(); + final infoFocusNode = FocusNode(); @override void initState() { super.initState(); enterInformationController.text = widget.sheet.aboutTakingPils; + infoFocusNode.requestFocus(); } @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)); - }, - ), - ], - ), + padding: EdgeInsets.only(bottom: 80, left: 16, right: 16, top: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("do_you_take_pills".tr), + SizedBox(height: 4), + CustomTextFormField( + controller: enterInformationController, + hintText: "enter_information".tr, + textInputAction: TextInputAction.done, + focusNode: infoFocusNode, + autofocus: true, + minLines: 2, + 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 index 2f1e4c5..ae817ed 100644 --- a/lib/features/registration/presentation/pages/name_screen.dart +++ b/lib/features/registration/presentation/pages/name_screen.dart @@ -16,47 +16,48 @@ class NameScreen extends StatefulWidget { class _NameScreenState extends State { final firstNameController = TextEditingController(); final lastNameController = TextEditingController(); + final nameFocus = FocusNode(); @override void initState() { super.initState(); firstNameController.text = widget.sheet.firstName; lastNameController.text = widget.sheet.lastName; + nameFocus.requestFocus(); } @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)); - }, - ) - ], - ), + padding: EdgeInsets.only(bottom: 80, top: 16, left: 16, right: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("first_name".tr), + SizedBox(height: 4), + CustomTextFormField( + controller: firstNameController, + focusNode: nameFocus, + textInputAction: TextInputAction.next, + hintText: 'Введите имя', + onChanged: (newValue) { + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(firstName: newValue)); + }, + ), + SizedBox(height: 16), + Text("last_name".tr), + SizedBox(height: 4), + CustomTextFormField( + controller: lastNameController, + textInputAction: TextInputAction.done, + hintText: 'Введите фамилию', + 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 index 93a5eae..1688ef2 100644 --- a/lib/features/registration/presentation/pages/registration_screen.dart +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -18,9 +18,7 @@ import 'package:eatvio_app/features/registration/presentation/pages/name_screen. 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 { @@ -36,160 +34,132 @@ class _RegistrationScreenState extends State { 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(); + return 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, + focusElevation: 0, + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + backgroundColor: Color(0xFFEAF2FD), + onPressed: () async { + 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, + focusElevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + backgroundColor: appTheme.blueA400, + onPressed: () async { + if (await canGoNext(state)) { setState(() { - pageController.previousPage( + pageController.nextPage( duration: const Duration(milliseconds: 350), curve: Curves.easeInOut, ); }); - }, - label: Icon( - Icons.arrow_back_ios_new_rounded, - color: appTheme.blueA400, - ), + } + }, + label: Text( + 'Продолжить', + style: theme.textTheme.titleSmall, ), ), - 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, ), - ), - ], - ), - 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), - ), + 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), - ], - ), + ), + 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), + 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), + ], ), ); }, @@ -197,7 +167,7 @@ class _RegistrationScreenState extends State { ); } - Future canGoNext(state) async { + Future canGoNext(RegistrationState state) async { switch (step) { case 2: List errors = validateCredentialsFields(state.sheet.email, state.sheet.name, state.sheet.password, state.sheet.passwordConfirmation); @@ -254,6 +224,44 @@ class _RegistrationScreenState extends State { ); return false; } + case 4: + if (state.sheet.gender.isNotEmpty) + return true; + else { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text('Ошибка'), + content: Text('Выберете пол'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text('OK'), + ), + ], + ), + ); + return false; + } + case 6: + if (state.sheet.country.isNotEmpty && state.sheet.city.isNotEmpty) + return true; + else { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text('Ошибка'), + content: Text('Заполните все поля'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text('OK'), + ), + ], + ), + ); + return false; + } case 7: List errors = validateCircumferencesFields( state.sheet.chestCircumference.toString(), diff --git a/lib/features/registration/presentation/pages/weight_screen.dart b/lib/features/registration/presentation/pages/weight_screen.dart index 855593e..300296d 100644 --- a/lib/features/registration/presentation/pages/weight_screen.dart +++ b/lib/features/registration/presentation/pages/weight_screen.dart @@ -16,51 +16,40 @@ class WeightScreen extends StatefulWidget { class _WeightScreenState extends State { final weightController = TextEditingController(); + final weightFocus = FocusNode(); @override void initState() { super.initState(); if (widget.sheet.weight != 0) weightController.text = widget.sheet.weight.toString(); + weightFocus.requestFocus(); } @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))); - }, - ), - ], - ), - ], - ), + padding: EdgeInsets.only(bottom: 80, left: 16, right: 16, top: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("your_weight".tr), + SizedBox(height: 4), + CustomTextFormField( + autofocus: true, + hintText: 'кг', + focusNode: weightFocus, + 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/localization/en_us/en_us_translations.dart b/lib/localization/en_us/en_us_translations.dart index 4c0df24..c68f131 100644 --- a/lib/localization/en_us/en_us_translations.dart +++ b/lib/localization/en_us/en_us_translations.dart @@ -50,7 +50,7 @@ final Map enUs = { // language_select Screen "lbl_english": "English", - "preferred_language": "Preferred Language?", + "preferred_language": "Preferred Language", // Common String "continue": "Continue", "skip": "Skip", diff --git a/lib/localization/ru/ru_translations.dart b/lib/localization/ru/ru_translations.dart index 8d7f708..faf5359 100644 --- a/lib/localization/ru/ru_translations.dart +++ b/lib/localization/ru/ru_translations.dart @@ -66,7 +66,7 @@ final Map ru = { // language_select Screen "lbl_english": "English", "finish": "Завершить", - "preferred_language": "Предпочитаемый язык общения?", + "preferred_language": "Предпочитаемый язык общения", // Common String "continue": "Продолжить", "skip": "Пропустить", diff --git a/lib/presentation/auth/auth_screen/auth_screen.dart b/lib/presentation/auth/auth_screen/auth_screen.dart index ec01a98..adf6cf5 100644 --- a/lib/presentation/auth/auth_screen/auth_screen.dart +++ b/lib/presentation/auth/auth_screen/auth_screen.dart @@ -3,13 +3,12 @@ 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:url_launcher/url_launcher.dart'; import 'package:validators/validators.dart'; import 'bloc/auth_bloc.dart'; @@ -38,71 +37,111 @@ class _AuthScreenState extends State { @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( - text: "Тест дневника".toUpperCase(), - margin: - EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: onTapDiaryTest(context)), - NextStepButton( - text: "authentificate".tr.toUpperCase(), - margin: - 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: 16.v), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, + appBar: AppBar( + centerTitle: true, + title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio), + ), + body: Padding( + padding: EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text("email".tr), + SizedBox(height: 4), + BlocSelector( + selector: (state) => state.emailController, + builder: (context, emailController) { + return CustomTextFormField( + controller: emailController, + textInputAction: TextInputAction.next, + textInputType: TextInputType.emailAddress, + hintText: 'Введите email', + ); + }, + ), + SizedBox(height: 16), + Text("password".tr), + SizedBox(height: 4), + BlocSelector( + selector: (state) => state.passwordController, + builder: (context, passwordController) { + return CustomTextFormField( + obscureText: true, + controller: passwordController, + hintText: 'Введите пароль', + ); + }, + ), + SizedBox(height: 16), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text('Нет аккаунта? '), + GestureDetector( + onTap: () => GoRouter.of(context).goNamed('registrationScreen'), + child: Text( + 'Зарегистрироваться', + style: TextStyle( + color: appTheme.blueA400, + decorationColor: appTheme.blueA400, + decoration: TextDecoration.underline, + ), + ), + ), + ], + ), + Spacer(), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + 'Нажимая "Войти", Вы соглашаетесь с ', + style: TextStyle( + fontSize: 12, + ), + ), + GestureDetector( + onTap: () async { + await launchUrl(Uri.parse(baseUrl + '/oferta_bs.pdf')); + }, + child: Text( + 'Публичной офертой', + style: TextStyle( + fontSize: 12, + color: appTheme.blueA400, + decorationColor: appTheme.blueA400, + decoration: TextDecoration.underline, + ), + ), + ), + ], + ), + SizedBox(height: 16), + BlocBuilder( + builder: (context, state) { + return Container( + height: 48, + width: MediaQuery.of(context).size.width - 32, + child: FloatingActionButton.extended( + heroTag: 'nextButtonRegistration', + highlightElevation: 0, + elevation: 0, + focusElevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + backgroundColor: appTheme.blueA400, onPressed: onTapAuth(state, context), - ); - }, - ), - ], - ), + label: Text( + 'Войти', + style: theme.textTheme.titleSmall, + ), + ), + ); + }, + ), + ], ), ), ); @@ -138,7 +177,7 @@ class _AuthScreenState extends State { content: Text('wrong_credentials'.tr), actions: [ TextButton( - onPressed: onTapOk(context), + onPressed: () => Navigator.pop(context), child: Text('OK'), ), ], @@ -159,7 +198,7 @@ class _AuthScreenState extends State { content: Text(errorMessage), actions: [ TextButton( - onPressed: onTapOk(context), + onPressed: () => Navigator.pop(context), child: Text('OK'), ), ], @@ -169,44 +208,6 @@ class _AuthScreenState extends State { }; } - onTapOk(BuildContext context) { - return () { - GoRouter.of(context).pop(context); - }; - } - - onTapDiaryTest(BuildContext context) { - return () { - GoRouter.of(context).goNamed('diaryScreen'); - }; - } - - onTapProfileTest(BuildContext context) { - return () { - GoRouter.of(context).goNamed('mySettingsScreen'); - }; - } - - onTapNoAccount(BuildContext context) { - return () { - GoRouter.of(context).goNamed('registrationScreen'); - }; - // return () { - // GoRouter.of(context).goNamed('languageSelectScreen'); - // }; - } - - /// Section Widget - _buildAppBar(BuildContext context) { - return CustomAppBar( - leadingWidth: 29.h, - centerTitle: true, - title: AppbarTitleImage( - imagePath: ImageConstant.imgLogoEatvio, - ), - ); - } - List validateFields(String email, String password) { List errors = []; diff --git a/lib/widgets/custom_drop_down.dart b/lib/widgets/custom_drop_down.dart index ff80bac..fc166b2 100644 --- a/lib/widgets/custom_drop_down.dart +++ b/lib/widgets/custom_drop_down.dart @@ -79,28 +79,32 @@ class CustomDropDown extends StatelessWidget { } _buildDropDownWidget(BuildContext context) { - return SizedBox( - width: width ?? MediaQuery.of(context).size.width - 20, - child: DropdownButtonFormField( - focusNode: focusNode ?? FocusNode(), - icon: icon, - autofocus: autofocus!, - value: value, - isExpanded: true, - style: textStyle ?? Theme.of(context).textTheme.titleMedium, - items: items?.map((SelectionPopupModel item) { - return DropdownMenuItem( - value: item, - child: Text( - item.title, - style: hintStyle ?? Theme.of(context).textTheme.titleMedium, - ), - ); - }).toList(), - decoration: _buildInputDecoration(context), - validator: validator, - onChanged: onDropDownChanged, + return DropdownButtonFormField( + focusNode: focusNode ?? FocusNode(), + icon: Icon(Icons.keyboard_arrow_down_rounded), + autofocus: autofocus!, + value: value, + isExpanded: true, + style: textStyle ?? TextStyle( + fontSize: 16, + fontWeight: FontWeight.w400, ), + items: items?.map((SelectionPopupModel item) { + return DropdownMenuItem( + value: item, + child: Text( + item.title, + style: hintStyle ?? TextStyle( + fontSize: 16, + fontWeight: FontWeight.w400, + color: Colors.black, + ), + ), + ); + }).toList(), + decoration: _buildInputDecoration(context), + validator: validator, + onChanged: onDropDownChanged, ); } @@ -111,34 +115,42 @@ class CustomDropDown extends StatelessWidget { InputDecoration _buildInputDecoration(BuildContext context) { return InputDecoration( hintText: hintText ?? "", - hintStyle: hintStyle ?? Theme.of(context).textTheme.titleMedium, + hintStyle: hintStyle ?? TextStyle( + fontSize: 16, + fontWeight: FontWeight.w400, + color: Colors.grey.shade400, + ), prefixIcon: prefix, prefixIconConstraints: prefixConstraints, suffixIcon: suffix, suffixIconConstraints: suffixConstraints, isDense: true, - contentPadding: contentPadding ?? - EdgeInsets.only( - left: 6, - top: 6, - bottom: 6, - ), + contentPadding: contentPadding ?? EdgeInsets.all(8), fillColor: fillColor ?? Theme.of(context).colorScheme.onPrimary, filled: filled, border: borderDecoration ?? OutlineInputBorder( - borderRadius: const BorderRadius.all(Radius.circular(8)), - borderSide: BorderSide(color: appTheme.blueA400, width: 1), + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide( + color: Colors.grey.shade400, + width: 1, + ), ), enabledBorder: borderDecoration ?? OutlineInputBorder( - borderRadius: const BorderRadius.all(Radius.circular(8)), - borderSide: BorderSide(color: appTheme.blueA400, width: 1), + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide( + color: Colors.grey.shade400, + width: 1, + ), ), focusedBorder: borderDecoration ?? OutlineInputBorder( - borderRadius: const BorderRadius.all(Radius.circular(8)), - borderSide: BorderSide(color: appTheme.blueA400, width: 1), + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide( + color: appTheme.blueA400, + width: 1, + ), ), ); } diff --git a/lib/widgets/custom_text_form_field.dart b/lib/widgets/custom_text_form_field.dart index 862cc10..11aa7d4 100644 --- a/lib/widgets/custom_text_form_field.dart +++ b/lib/widgets/custom_text_form_field.dart @@ -4,12 +4,11 @@ import 'package:flutter/services.dart'; class CustomTextFormField extends StatelessWidget { CustomTextFormField({ - Key? key, this.alignment, this.width, this.controller, this.focusNode, - this.autofocus = true, + this.autofocus = false, this.textStyle, this.obscureText = false, this.textInputAction = TextInputAction.next, @@ -32,21 +31,23 @@ class CustomTextFormField extends StatelessWidget { this.onSaved, this.initialValue, this.onChanged, - }) : super( - key: key, - ); + this.onEditingComplete, + this.minLines = 1, + super.key, + }); final Alignment? alignment; final double? width; final TextEditingController? controller; final FocusNode? focusNode; - final bool? autofocus; + final bool autofocus; final TextStyle? textStyle; final bool? obscureText; final List? inputFormatters; final TextInputAction? textInputAction; final TextInputType? textInputType; final int? maxLines; + final int minLines; final String? hintText; final TextStyle? hintStyle; final Widget? prefix; @@ -61,162 +62,74 @@ class CustomTextFormField extends StatelessWidget { final FormFieldValidator? validator; final String? initialValue; final Function(String)? onFieldSubmitted; + final Function()? onEditingComplete; final void Function(String?)? onSaved; final void Function(String)? onChanged; @override Widget build(BuildContext context) { - return alignment != null - ? Align( - alignment: alignment ?? Alignment.center, - child: SizedBox( - width: width ?? double.maxFinite, - child: TextFormField( - controller: controller, - focusNode: focusNode ?? null, - autofocus: autofocus!, - style: textStyle ?? theme.textTheme.titleMedium, - obscureText: obscureText!, - textInputAction: textInputAction, - maxLines: maxLines ?? 1, - onFieldSubmitted: onFieldSubmitted, - onChanged: onChanged, - decoration: InputDecoration( - hintText: hintText ?? "", - hintStyle: hintStyle ?? theme.textTheme.bodyLarge, - prefixIcon: prefix, - prefixIconConstraints: prefixConstraints, - suffixIcon: suffix, - suffixIconConstraints: suffixConstraints, - isDense: true, - contentPadding: contentPadding ?? EdgeInsets.all(6.h), - fillColor: fillColor ?? theme.colorScheme.onPrimary, - filled: filled, - border: borderDecoration ?? - OutlineInputBorder( - borderRadius: BorderRadius.circular(8.h), - borderSide: BorderSide( - color: appTheme.blueA400, - width: 1, - ), - ), - enabledBorder: borderDecoration ?? - OutlineInputBorder( - borderRadius: BorderRadius.circular(8.h), - borderSide: BorderSide( - color: appTheme.blueA400, - width: 1, - ), - ), - focusedBorder: borderDecoration ?? - OutlineInputBorder( - borderRadius: BorderRadius.circular(8.h), - borderSide: BorderSide( - color: appTheme.blueA400, - width: 1, - ), - ), + return Align( + alignment: alignment ?? Alignment.center, + child: TextFormField( + minLines: minLines, + onChanged: onChanged, + controller: controller, + focusNode: focusNode ?? null, + autofocus: autofocus, + style: TextStyle( + fontSize: 16, + color: Colors.black, + ), + obscureText: obscureText!, + textInputAction: textInputAction, + maxLines: maxLines ?? 1, + initialValue: initialValue, + cursorColor: appTheme.blueA400, + decoration: InputDecoration( + hintText: hintText ?? "", + hintStyle: TextStyle( + fontSize: 16, + color: Colors.grey.shade400, + fontWeight: FontWeight.w400, + ), + prefixIcon: prefix, + prefixIconConstraints: prefixConstraints, + suffixIcon: suffix, + suffixIconConstraints: suffixConstraints, + isDense: false, + contentPadding: EdgeInsets.all(8), + fillColor: fillColor ?? theme.colorScheme.onPrimary, + filled: filled, + border: borderDecoration ?? + OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide( + color: Colors.grey.shade400, + width: 1, ), - keyboardType: keyboardType, - validator: validator, - onSaved: onSaved, - inputFormatters: inputFormatters, - initialValue: initialValue, ), - ), - ) - : SizedBox( - width: width ?? double.maxFinite, - child: TextFormField( - onChanged: onChanged, - controller: controller, - focusNode: focusNode ?? null, - autofocus: autofocus!, - style: textStyle ?? theme.textTheme.titleMedium, - obscureText: obscureText!, - textInputAction: textInputAction, - maxLines: maxLines ?? 1, - initialValue: initialValue, - decoration: InputDecoration( - hintText: hintText ?? "", - hintStyle: hintStyle ?? theme.textTheme.bodyLarge, - prefixIcon: prefix, - prefixIconConstraints: prefixConstraints, - suffixIcon: suffix, - suffixIconConstraints: suffixConstraints, - isDense: true, - contentPadding: contentPadding ?? EdgeInsets.all(6.h), - fillColor: fillColor ?? theme.colorScheme.onPrimary, - filled: filled, - border: borderDecoration ?? - OutlineInputBorder( - borderRadius: BorderRadius.circular(8.h), - borderSide: BorderSide( - color: appTheme.blueA400, - width: 1, - ), - ), - enabledBorder: borderDecoration ?? - OutlineInputBorder( - borderRadius: BorderRadius.circular(8.h), - borderSide: BorderSide( - color: appTheme.blueA400, - width: 1, - ), - ), - focusedBorder: borderDecoration ?? - OutlineInputBorder( - borderRadius: BorderRadius.circular(8.h), - borderSide: BorderSide( - color: appTheme.blueA400, - width: 1, - ), - ), + enabledBorder: borderDecoration ?? + OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide( + color: Colors.grey.shade400, + width: 1, + ), ), - keyboardType: keyboardType, - validator: validator, - onSaved: onSaved, - inputFormatters: inputFormatters, - ), - ); - } -} -/* InputDecoration _buildInputDecoration() { - return InputDecoration( - hintText: hintText ?? "", - hintStyle: hintStyle ?? theme.textTheme.bodyLarge, - prefixIcon: prefix, - prefixIconConstraints: prefixConstraints, - suffixIcon: suffix, - suffixIconConstraints: suffixConstraints, - isDense: true, - contentPadding: contentPadding ?? EdgeInsets.all(6.h), - fillColor: fillColor ?? theme.colorScheme.onPrimary, - filled: filled, - border: borderDecoration ?? - OutlineInputBorder( - borderRadius: BorderRadius.circular(8.h), - borderSide: BorderSide( - color: appTheme.blueA400, - width: 1, - ), - ), - enabledBorder: borderDecoration ?? - OutlineInputBorder( - borderRadius: BorderRadius.circular(8.h), - borderSide: BorderSide( - color: appTheme.blueA400, - width: 1, - ), - ), - focusedBorder: borderDecoration ?? - OutlineInputBorder( - borderRadius: BorderRadius.circular(8.h), - borderSide: BorderSide( - color: appTheme.blueA400, - width: 1, - ), - ), + focusedBorder: borderDecoration ?? + OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide( + color: appTheme.blueA400, + width: 1, + ), + ), + ), + keyboardType: keyboardType, + validator: validator, + onSaved: onSaved, + inputFormatters: inputFormatters, + ), ); } -}*/ +} -- 2.49.1 From a94e2b9db487fe64ea41a15e2651a00ff6761399 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Wed, 17 Jul 2024 17:04:00 +0300 Subject: [PATCH 070/110] feature(blogPosts): add image load, fix blog post view --- .../blog_post/services/blog_post_service.dart | 2 +- .../services/blog_post_service.g.dart | 2 +- .../pages/blog_post_create_screen.dart | 1 - .../bloc/feed_cubit/feed_cubit.dart | 1 - .../bloc/blog_post_create_bloc.dart | 31 ++++++++----------- .../bloc/blog_post_create_state.dart | 13 +++++++- .../bloc/blog_post_edit_bloc.dart | 2 +- lib/widgets/custom_edit_text_form_field.dart | 2 +- 8 files changed, 29 insertions(+), 25 deletions(-) diff --git a/lib/features/blog_post/services/blog_post_service.dart b/lib/features/blog_post/services/blog_post_service.dart index 00d8e56..dfbc361 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('/api/feed/show/{id}') + @GET('/api/blogPosts/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 4090577..5ea30fc 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, - '/api/feed/show/${id}', + '/api/blogPosts/show/${id}', queryParameters: queryParameters, data: _data, ) 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 755ce12..53628bc 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 @@ -44,7 +44,6 @@ class BlogPostCreateScreen extends StatelessWidget { } _buildBlogPostCreate(BuildContext context, BlogPostCreateLoadedState state) { - print(state.image); return Scaffold( resizeToAvoidBottomInset: false, body: Container( diff --git a/lib/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart b/lib/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart index 02ee767..c052c26 100644 --- a/lib/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart +++ b/lib/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart @@ -8,7 +8,6 @@ class FeedCubit extends Cubit { FeedCubit({required this.feedRepository}) : super(const FeedState.loading()); loadFeedBlogPostList() async { - emit(const FeedState.loading()); try { final feedBlogPostList = await feedRepository.getFeedBlogPostList(); emit(FeedState.loaded(feedBlogPostList: feedBlogPostList)); 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 624a1ef..654e963 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,6 +1,4 @@ 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'; @@ -14,6 +12,7 @@ import 'package:image_picker/image_picker.dart'; import '/core/app_export.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. @@ -70,30 +69,30 @@ class BlogPostCreateBloc extends Bloc currentState.image, ); - if (response.statusCode == 200) { + if (response.statusCode == 200 || response.statusCode == 201) { AppRouter.navigatorKey.currentContext?.goNamed('feedScreen'); } else { print( - 'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}', + 'Failed to create blog post. Status Code: ${response.statusCode} ${response.data}', ); } } } - sendBlogPost(String? title, String? youtubeURL, String? description, XFile? image) async { - String url = '/blog_post/create'; + Future sendBlogPost(String? title, String? youtubeURL, String? description, XFile? image) async { + String url = baseUrl + '/api/blogPosts/create'; - final Map credentials = { + FormData formData = FormData.fromMap({ 'title': title, 'description': description, - 'youtube_url': youtubeURL, - 'status': 'active', - 'image': image, - }; + 'videoUrl': youtubeURL, + 'state': 'active', + 'image': await MultipartFile.fromFile(image!.path, filename: image.name), + }); - var response = await sl().post( + final response = await sl().post( url, - data: json.encode(credentials), + data: formData, ); return response; @@ -102,11 +101,7 @@ class BlogPostCreateBloc extends Bloc FutureOr _uploadImages(UploadImages event, Emitter emit) { if (state is BlogPostCreateLoadedState) { var currentState = state as BlogPostCreateLoadedState; - emit( - currentState.copyWith( - image: event.image, - ), - ); + emit(currentState.copyWith(image: event.image)); } } } 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 33dc59b..8e0c8e8 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 @@ -14,6 +14,7 @@ class BlogPostCreateState extends Equatable { @override List get props => [blog_postModelObj]; + BlogPostCreateState copyWith({BlogPostCreateModel? blog_postModelObj}) { return BlogPostCreateState( blog_postModelObj: blog_postModelObj ?? this.blog_postModelObj, @@ -39,8 +40,18 @@ class BlogPostCreateLoadedState extends BlogPostCreateState { String? token; bool isLoading; XFile? image; + @override - List get props => [blog_postModelObj, title, description, youtubeURL]; + List get props => [ + blog_postModelObj, + title, + description, + youtubeURL, + token, + image, + isLoading, + ]; + BlogPostCreateLoadedState copyWith({ BlogPostCreateModel? blog_postModelObj, TextEditingController? title, 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 02e496f..c9c6bf9 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 @@ -33,7 +33,7 @@ class BlogPostEditBloc extends Bloc { } final String? blog_postID = state.blog_postModelObj?.blog_postID; final response = await http.get( - Uri.parse(baseUrl + '/api/feed/show/$blog_postID'), + Uri.parse(baseUrl + '/api/blogPosts/show/$blog_postID'), headers: { 'Authorization': 'Bearer $token', }, diff --git a/lib/widgets/custom_edit_text_form_field.dart b/lib/widgets/custom_edit_text_form_field.dart index 0853d3e..13a3df8 100644 --- a/lib/widgets/custom_edit_text_form_field.dart +++ b/lib/widgets/custom_edit_text_form_field.dart @@ -8,7 +8,7 @@ class CustomTextFormField extends StatelessWidget { this.width, this.controller, this.focusNode, - this.autofocus = true, + this.autofocus = false, this.textStyle, this.obscureText = false, this.textInputAction = TextInputAction.next, -- 2.49.1 From e472121bbc95770f189da3b3ea4713ca79365fe5 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Wed, 17 Jul 2024 17:08:01 +0300 Subject: [PATCH 071/110] feature(blogPosts): pick only one image --- .../presentation/pages/blog_post_create_screen.dart | 8 +++----- .../bloc/blog_post_create_event.dart | 2 ++ 2 files changed, 5 insertions(+), 5 deletions(-) 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 53628bc..39c3f4e 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 @@ -191,11 +191,9 @@ addImage(BuildContext context, bool isLoading) { if (!isLoading) { return () async { final picker = ImagePicker(); - List? images = await picker.pickMultiImage(); - if (images.isNotEmpty) { - for (var image in images) { - context.read().add(UploadImages(image)); - } + XFile? image = await picker.pickImage(source: ImageSource.gallery); + if (image != null) { + context.read().add(UploadImages(image)); } }; } diff --git a/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_event.dart b/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_event.dart index 778cd85..6ce10ca 100644 --- a/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_event.dart +++ b/lib/presentation/feed/blog_post_create_screen/bloc/blog_post_create_event.dart @@ -22,7 +22,9 @@ class CreateBlogPost extends BlogPostCreateEvent { class UploadImages extends BlogPostCreateEvent { UploadImages(this.image); + final XFile image; + @override List get props => [image]; } -- 2.49.1 From be461e4183fe196db53fb2a284b112e9440fe4a6 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 19 Jul 2024 11:55:48 +0300 Subject: [PATCH 072/110] feat(diary): New models for calendar and autocomplete fix --- .../calendar/models/calendar_model.dart | 21 + .../models/calendar_model.freezed.dart | 309 +++++++++ .../calendar/models/calendar_model.g.dart | 31 + .../presentation/bloc/calendar_cubit.dart | 20 + .../presentation/bloc/calendar_state.dart | 19 + .../bloc/calendar_state.freezed.dart | 621 ++++++++++++++++++ .../repositories/calendar_repository.dart | 19 + .../calendar/services/calendar_service.dart | 13 + .../calendar/services/calendar_service.g.dart | 78 +++ lib/features/diary/models/product.dart | 17 - .../diary/models/product.freezed.dart | 400 +---------- lib/features/diary/models/product.g.dart | 34 - .../diary/presentation/bloc/diary_bloc.dart | 2 +- 13 files changed, 1140 insertions(+), 444 deletions(-) create mode 100644 lib/features/calendar/models/calendar_model.dart create mode 100644 lib/features/calendar/models/calendar_model.freezed.dart create mode 100644 lib/features/calendar/models/calendar_model.g.dart create mode 100644 lib/features/calendar/presentation/bloc/calendar_cubit.dart create mode 100644 lib/features/calendar/presentation/bloc/calendar_state.dart create mode 100644 lib/features/calendar/presentation/bloc/calendar_state.freezed.dart create mode 100644 lib/features/calendar/repositories/calendar_repository.dart create mode 100644 lib/features/calendar/services/calendar_service.dart create mode 100644 lib/features/calendar/services/calendar_service.g.dart diff --git a/lib/features/calendar/models/calendar_model.dart b/lib/features/calendar/models/calendar_model.dart new file mode 100644 index 0000000..c206175 --- /dev/null +++ b/lib/features/calendar/models/calendar_model.dart @@ -0,0 +1,21 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'calendar_model.freezed.dart'; +part 'calendar_model.g.dart'; + +@freezed +class CalendarModel with _$CalendarModel { + const factory CalendarModel({ + required int id, + required String state, + required String image, + required String description, + @JsonKey(name: "youtube_url") required String youtubeUrl, + @JsonKey(name: "created_at") required DateTime createdAt, + @JsonKey(name: "updated_at") required DateTime updatedAt, + required String title, + }) = _CalendarModel; + + factory CalendarModel.fromJson(Map json) => + _$CalendarModelFromJson(json); +} diff --git a/lib/features/calendar/models/calendar_model.freezed.dart b/lib/features/calendar/models/calendar_model.freezed.dart new file mode 100644 index 0000000..7f0d320 --- /dev/null +++ b/lib/features/calendar/models/calendar_model.freezed.dart @@ -0,0 +1,309 @@ +// 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 'calendar_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'); + +CalendarModel _$CalendarModelFromJson(Map json) { + return _CalendarModel.fromJson(json); +} + +/// @nodoc +mixin _$CalendarModel { + int get id => throw _privateConstructorUsedError; + String get state => throw _privateConstructorUsedError; + String get image => throw _privateConstructorUsedError; + String get description => throw _privateConstructorUsedError; + @JsonKey(name: "youtube_url") + String get youtubeUrl => throw _privateConstructorUsedError; + @JsonKey(name: "created_at") + DateTime get createdAt => throw _privateConstructorUsedError; + @JsonKey(name: "updated_at") + DateTime get updatedAt => throw _privateConstructorUsedError; + String get title => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $CalendarModelCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CalendarModelCopyWith<$Res> { + factory $CalendarModelCopyWith( + CalendarModel value, $Res Function(CalendarModel) then) = + _$CalendarModelCopyWithImpl<$Res, CalendarModel>; + @useResult + $Res call( + {int id, + String state, + String image, + String description, + @JsonKey(name: "youtube_url") String youtubeUrl, + @JsonKey(name: "created_at") DateTime createdAt, + @JsonKey(name: "updated_at") DateTime updatedAt, + String title}); +} + +/// @nodoc +class _$CalendarModelCopyWithImpl<$Res, $Val extends CalendarModel> + implements $CalendarModelCopyWith<$Res> { + _$CalendarModelCopyWithImpl(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 = null, + Object? state = null, + Object? image = null, + Object? description = null, + Object? youtubeUrl = null, + Object? createdAt = null, + Object? updatedAt = null, + Object? title = null, + }) { + return _then(_value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + state: null == state + ? _value.state + : state // ignore: cast_nullable_to_non_nullable + as String, + image: null == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as String, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + youtubeUrl: null == youtubeUrl + ? _value.youtubeUrl + : youtubeUrl // ignore: cast_nullable_to_non_nullable + as String, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + updatedAt: null == updatedAt + ? _value.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as DateTime, + title: null == title + ? _value.title + : title // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$CalendarModelImplCopyWith<$Res> + implements $CalendarModelCopyWith<$Res> { + factory _$$CalendarModelImplCopyWith( + _$CalendarModelImpl value, $Res Function(_$CalendarModelImpl) then) = + __$$CalendarModelImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {int id, + String state, + String image, + String description, + @JsonKey(name: "youtube_url") String youtubeUrl, + @JsonKey(name: "created_at") DateTime createdAt, + @JsonKey(name: "updated_at") DateTime updatedAt, + String title}); +} + +/// @nodoc +class __$$CalendarModelImplCopyWithImpl<$Res> + extends _$CalendarModelCopyWithImpl<$Res, _$CalendarModelImpl> + implements _$$CalendarModelImplCopyWith<$Res> { + __$$CalendarModelImplCopyWithImpl( + _$CalendarModelImpl _value, $Res Function(_$CalendarModelImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? state = null, + Object? image = null, + Object? description = null, + Object? youtubeUrl = null, + Object? createdAt = null, + Object? updatedAt = null, + Object? title = null, + }) { + return _then(_$CalendarModelImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + state: null == state + ? _value.state + : state // ignore: cast_nullable_to_non_nullable + as String, + image: null == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as String, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + youtubeUrl: null == youtubeUrl + ? _value.youtubeUrl + : youtubeUrl // ignore: cast_nullable_to_non_nullable + as String, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + updatedAt: null == updatedAt + ? _value.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as DateTime, + title: null == title + ? _value.title + : title // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$CalendarModelImpl implements _CalendarModel { + const _$CalendarModelImpl( + {required this.id, + required this.state, + required this.image, + required this.description, + @JsonKey(name: "youtube_url") required this.youtubeUrl, + @JsonKey(name: "created_at") required this.createdAt, + @JsonKey(name: "updated_at") required this.updatedAt, + required this.title}); + + factory _$CalendarModelImpl.fromJson(Map json) => + _$$CalendarModelImplFromJson(json); + + @override + final int id; + @override + final String state; + @override + final String image; + @override + final String description; + @override + @JsonKey(name: "youtube_url") + final String youtubeUrl; + @override + @JsonKey(name: "created_at") + final DateTime createdAt; + @override + @JsonKey(name: "updated_at") + final DateTime updatedAt; + @override + final String title; + + @override + String toString() { + return 'CalendarModel(id: $id, state: $state, image: $image, description: $description, youtubeUrl: $youtubeUrl, createdAt: $createdAt, updatedAt: $updatedAt, title: $title)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CalendarModelImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.state, state) || other.state == state) && + (identical(other.image, image) || other.image == image) && + (identical(other.description, description) || + other.description == description) && + (identical(other.youtubeUrl, youtubeUrl) || + other.youtubeUrl == youtubeUrl) && + (identical(other.createdAt, createdAt) || + other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt) && + (identical(other.title, title) || other.title == title)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, id, state, image, description, + youtubeUrl, createdAt, updatedAt, title); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CalendarModelImplCopyWith<_$CalendarModelImpl> get copyWith => + __$$CalendarModelImplCopyWithImpl<_$CalendarModelImpl>(this, _$identity); + + @override + Map toJson() { + return _$$CalendarModelImplToJson( + this, + ); + } +} + +abstract class _CalendarModel implements CalendarModel { + const factory _CalendarModel( + {required final int id, + required final String state, + required final String image, + required final String description, + @JsonKey(name: "youtube_url") required final String youtubeUrl, + @JsonKey(name: "created_at") required final DateTime createdAt, + @JsonKey(name: "updated_at") required final DateTime updatedAt, + required final String title}) = _$CalendarModelImpl; + + factory _CalendarModel.fromJson(Map json) = + _$CalendarModelImpl.fromJson; + + @override + int get id; + @override + String get state; + @override + String get image; + @override + String get description; + @override + @JsonKey(name: "youtube_url") + String get youtubeUrl; + @override + @JsonKey(name: "created_at") + DateTime get createdAt; + @override + @JsonKey(name: "updated_at") + DateTime get updatedAt; + @override + String get title; + @override + @JsonKey(ignore: true) + _$$CalendarModelImplCopyWith<_$CalendarModelImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/calendar/models/calendar_model.g.dart b/lib/features/calendar/models/calendar_model.g.dart new file mode 100644 index 0000000..d675f9b --- /dev/null +++ b/lib/features/calendar/models/calendar_model.g.dart @@ -0,0 +1,31 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'calendar_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$CalendarModelImpl _$$CalendarModelImplFromJson(Map json) => + _$CalendarModelImpl( + id: (json['id'] as num).toInt(), + state: json['state'] as String, + image: json['image'] as String, + description: json['description'] as String, + youtubeUrl: json['youtube_url'] as String, + createdAt: DateTime.parse(json['created_at'] as String), + updatedAt: DateTime.parse(json['updated_at'] as String), + title: json['title'] as String, + ); + +Map _$$CalendarModelImplToJson(_$CalendarModelImpl instance) => + { + 'id': instance.id, + 'state': instance.state, + 'image': instance.image, + 'description': instance.description, + 'youtube_url': instance.youtubeUrl, + 'created_at': instance.createdAt.toIso8601String(), + 'updated_at': instance.updatedAt.toIso8601String(), + 'title': instance.title, + }; diff --git a/lib/features/calendar/presentation/bloc/calendar_cubit.dart b/lib/features/calendar/presentation/bloc/calendar_cubit.dart new file mode 100644 index 0000000..2b76ab1 --- /dev/null +++ b/lib/features/calendar/presentation/bloc/calendar_cubit.dart @@ -0,0 +1,20 @@ +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_state.dart'; +import 'package:eatvio_app/features/calendar/repositories/calendar_repository.dart'; + +class CalendarCubit extends Cubit { + final CalendarRepository calendarRepository; + + CalendarCubit({required this.calendarRepository}) + : super(const CalendarState.loading()); + + loadCalendarList() async { + emit(const CalendarState.loading()); + try { + final calendarList = await calendarRepository.getCalendar(); + emit(CalendarState.loaded(calendarList: calendarList)); + } catch (e) { + emit(CalendarState.error(errorMessage: e.toString())); + } + } +} diff --git a/lib/features/calendar/presentation/bloc/calendar_state.dart b/lib/features/calendar/presentation/bloc/calendar_state.dart new file mode 100644 index 0000000..6dbf606 --- /dev/null +++ b/lib/features/calendar/presentation/bloc/calendar_state.dart @@ -0,0 +1,19 @@ +import 'package:eatvio_app/features/calendar/models/calendar_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'calendar_state.freezed.dart'; + +@freezed +abstract class CalendarState with _$CalendarState { + const factory CalendarState() = _CalendarState; + + const factory CalendarState.loading() = CalendarStateLoading; + + const factory CalendarState.loaded({ + required List calendarList, + }) = CalendarStateLoaded; + + const factory CalendarState.error({ + required String errorMessage, + }) = CalendarStateError; +} diff --git a/lib/features/calendar/presentation/bloc/calendar_state.freezed.dart b/lib/features/calendar/presentation/bloc/calendar_state.freezed.dart new file mode 100644 index 0000000..c71d522 --- /dev/null +++ b/lib/features/calendar/presentation/bloc/calendar_state.freezed.dart @@ -0,0 +1,621 @@ +// 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 'calendar_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 _$CalendarState { + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(List calendarList) loaded, + required TResult Function(String errorMessage) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(List calendarList)? loaded, + TResult? Function(String errorMessage)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(List calendarList)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map( + TResult Function(_CalendarState value) $default, { + required TResult Function(CalendarStateLoading value) loading, + required TResult Function(CalendarStateLoaded value) loaded, + required TResult Function(CalendarStateError value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_CalendarState value)? $default, { + TResult? Function(CalendarStateLoading value)? loading, + TResult? Function(CalendarStateLoaded value)? loaded, + TResult? Function(CalendarStateError value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap( + TResult Function(_CalendarState value)? $default, { + TResult Function(CalendarStateLoading value)? loading, + TResult Function(CalendarStateLoaded value)? loaded, + TResult Function(CalendarStateError value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CalendarStateCopyWith<$Res> { + factory $CalendarStateCopyWith( + CalendarState value, $Res Function(CalendarState) then) = + _$CalendarStateCopyWithImpl<$Res, CalendarState>; +} + +/// @nodoc +class _$CalendarStateCopyWithImpl<$Res, $Val extends CalendarState> + implements $CalendarStateCopyWith<$Res> { + _$CalendarStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; +} + +/// @nodoc +abstract class _$$CalendarStateImplCopyWith<$Res> { + factory _$$CalendarStateImplCopyWith( + _$CalendarStateImpl value, $Res Function(_$CalendarStateImpl) then) = + __$$CalendarStateImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$CalendarStateImplCopyWithImpl<$Res> + extends _$CalendarStateCopyWithImpl<$Res, _$CalendarStateImpl> + implements _$$CalendarStateImplCopyWith<$Res> { + __$$CalendarStateImplCopyWithImpl( + _$CalendarStateImpl _value, $Res Function(_$CalendarStateImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$CalendarStateImpl implements _CalendarState { + const _$CalendarStateImpl(); + + @override + String toString() { + return 'CalendarState()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$CalendarStateImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(List calendarList) loaded, + required TResult Function(String errorMessage) error, + }) { + return $default(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(List calendarList)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return $default?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(List calendarList)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_CalendarState value) $default, { + required TResult Function(CalendarStateLoading value) loading, + required TResult Function(CalendarStateLoaded value) loaded, + required TResult Function(CalendarStateError value) error, + }) { + return $default(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_CalendarState value)? $default, { + TResult? Function(CalendarStateLoading value)? loading, + TResult? Function(CalendarStateLoaded value)? loaded, + TResult? Function(CalendarStateError value)? error, + }) { + return $default?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_CalendarState value)? $default, { + TResult Function(CalendarStateLoading value)? loading, + TResult Function(CalendarStateLoaded value)? loaded, + TResult Function(CalendarStateError value)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(this); + } + return orElse(); + } +} + +abstract class _CalendarState implements CalendarState { + const factory _CalendarState() = _$CalendarStateImpl; +} + +/// @nodoc +abstract class _$$CalendarStateLoadingImplCopyWith<$Res> { + factory _$$CalendarStateLoadingImplCopyWith(_$CalendarStateLoadingImpl value, + $Res Function(_$CalendarStateLoadingImpl) then) = + __$$CalendarStateLoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$CalendarStateLoadingImplCopyWithImpl<$Res> + extends _$CalendarStateCopyWithImpl<$Res, _$CalendarStateLoadingImpl> + implements _$$CalendarStateLoadingImplCopyWith<$Res> { + __$$CalendarStateLoadingImplCopyWithImpl(_$CalendarStateLoadingImpl _value, + $Res Function(_$CalendarStateLoadingImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$CalendarStateLoadingImpl implements CalendarStateLoading { + const _$CalendarStateLoadingImpl(); + + @override + String toString() { + return 'CalendarState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CalendarStateLoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(List calendarList) loaded, + required TResult Function(String errorMessage) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(List calendarList)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(List calendarList)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_CalendarState value) $default, { + required TResult Function(CalendarStateLoading value) loading, + required TResult Function(CalendarStateLoaded value) loaded, + required TResult Function(CalendarStateError value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_CalendarState value)? $default, { + TResult? Function(CalendarStateLoading value)? loading, + TResult? Function(CalendarStateLoaded value)? loaded, + TResult? Function(CalendarStateError value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_CalendarState value)? $default, { + TResult Function(CalendarStateLoading value)? loading, + TResult Function(CalendarStateLoaded value)? loaded, + TResult Function(CalendarStateError value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class CalendarStateLoading implements CalendarState { + const factory CalendarStateLoading() = _$CalendarStateLoadingImpl; +} + +/// @nodoc +abstract class _$$CalendarStateLoadedImplCopyWith<$Res> { + factory _$$CalendarStateLoadedImplCopyWith(_$CalendarStateLoadedImpl value, + $Res Function(_$CalendarStateLoadedImpl) then) = + __$$CalendarStateLoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({List calendarList}); +} + +/// @nodoc +class __$$CalendarStateLoadedImplCopyWithImpl<$Res> + extends _$CalendarStateCopyWithImpl<$Res, _$CalendarStateLoadedImpl> + implements _$$CalendarStateLoadedImplCopyWith<$Res> { + __$$CalendarStateLoadedImplCopyWithImpl(_$CalendarStateLoadedImpl _value, + $Res Function(_$CalendarStateLoadedImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? calendarList = null, + }) { + return _then(_$CalendarStateLoadedImpl( + calendarList: null == calendarList + ? _value._calendarList + : calendarList // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class _$CalendarStateLoadedImpl implements CalendarStateLoaded { + const _$CalendarStateLoadedImpl( + {required final List calendarList}) + : _calendarList = calendarList; + + final List _calendarList; + @override + List get calendarList { + if (_calendarList is EqualUnmodifiableListView) return _calendarList; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_calendarList); + } + + @override + String toString() { + return 'CalendarState.loaded(calendarList: $calendarList)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CalendarStateLoadedImpl && + const DeepCollectionEquality() + .equals(other._calendarList, _calendarList)); + } + + @override + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_calendarList)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CalendarStateLoadedImplCopyWith<_$CalendarStateLoadedImpl> get copyWith => + __$$CalendarStateLoadedImplCopyWithImpl<_$CalendarStateLoadedImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(List calendarList) loaded, + required TResult Function(String errorMessage) error, + }) { + return loaded(calendarList); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(List calendarList)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return loaded?.call(calendarList); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(List calendarList)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(calendarList); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_CalendarState value) $default, { + required TResult Function(CalendarStateLoading value) loading, + required TResult Function(CalendarStateLoaded value) loaded, + required TResult Function(CalendarStateError value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_CalendarState value)? $default, { + TResult? Function(CalendarStateLoading value)? loading, + TResult? Function(CalendarStateLoaded value)? loaded, + TResult? Function(CalendarStateError value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_CalendarState value)? $default, { + TResult Function(CalendarStateLoading value)? loading, + TResult Function(CalendarStateLoaded value)? loaded, + TResult Function(CalendarStateError value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class CalendarStateLoaded implements CalendarState { + const factory CalendarStateLoaded( + {required final List calendarList}) = + _$CalendarStateLoadedImpl; + + List get calendarList; + @JsonKey(ignore: true) + _$$CalendarStateLoadedImplCopyWith<_$CalendarStateLoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$CalendarStateErrorImplCopyWith<$Res> { + factory _$$CalendarStateErrorImplCopyWith(_$CalendarStateErrorImpl value, + $Res Function(_$CalendarStateErrorImpl) then) = + __$$CalendarStateErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String errorMessage}); +} + +/// @nodoc +class __$$CalendarStateErrorImplCopyWithImpl<$Res> + extends _$CalendarStateCopyWithImpl<$Res, _$CalendarStateErrorImpl> + implements _$$CalendarStateErrorImplCopyWith<$Res> { + __$$CalendarStateErrorImplCopyWithImpl(_$CalendarStateErrorImpl _value, + $Res Function(_$CalendarStateErrorImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? errorMessage = null, + }) { + return _then(_$CalendarStateErrorImpl( + errorMessage: null == errorMessage + ? _value.errorMessage + : errorMessage // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$CalendarStateErrorImpl implements CalendarStateError { + const _$CalendarStateErrorImpl({required this.errorMessage}); + + @override + final String errorMessage; + + @override + String toString() { + return 'CalendarState.error(errorMessage: $errorMessage)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CalendarStateErrorImpl && + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); + } + + @override + int get hashCode => Object.hash(runtimeType, errorMessage); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$CalendarStateErrorImplCopyWith<_$CalendarStateErrorImpl> get copyWith => + __$$CalendarStateErrorImplCopyWithImpl<_$CalendarStateErrorImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(List calendarList) loaded, + required TResult Function(String errorMessage) error, + }) { + return error(errorMessage); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(List calendarList)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return error?.call(errorMessage); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(List calendarList)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(errorMessage); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_CalendarState value) $default, { + required TResult Function(CalendarStateLoading value) loading, + required TResult Function(CalendarStateLoaded value) loaded, + required TResult Function(CalendarStateError value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_CalendarState value)? $default, { + TResult? Function(CalendarStateLoading value)? loading, + TResult? Function(CalendarStateLoaded value)? loaded, + TResult? Function(CalendarStateError value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_CalendarState value)? $default, { + TResult Function(CalendarStateLoading value)? loading, + TResult Function(CalendarStateLoaded value)? loaded, + TResult Function(CalendarStateError value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class CalendarStateError implements CalendarState { + const factory CalendarStateError({required final String errorMessage}) = + _$CalendarStateErrorImpl; + + String get errorMessage; + @JsonKey(ignore: true) + _$$CalendarStateErrorImplCopyWith<_$CalendarStateErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/calendar/repositories/calendar_repository.dart b/lib/features/calendar/repositories/calendar_repository.dart new file mode 100644 index 0000000..97a23dc --- /dev/null +++ b/lib/features/calendar/repositories/calendar_repository.dart @@ -0,0 +1,19 @@ +import 'package:eatvio_app/features/calendar/models/calendar_model.dart'; +import 'package:eatvio_app/features/calendar/services/calendar_service.dart'; + +class CalendarRepository { + final CalendarService calendarService; + + CalendarRepository({required this.calendarService}); + + Future> getCalendar() async { + try { + return (await calendarService.getCalendar()) + .entries + .map((entry) => entry.value) + .toList(); + } catch (e) { + rethrow; + } + } +} diff --git a/lib/features/calendar/services/calendar_service.dart b/lib/features/calendar/services/calendar_service.dart new file mode 100644 index 0000000..80b98e6 --- /dev/null +++ b/lib/features/calendar/services/calendar_service.dart @@ -0,0 +1,13 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/calendar/models/calendar_model.dart'; +import 'package:retrofit/retrofit.dart'; + +part 'calendar_service.g.dart'; + +@RestApi() +abstract class CalendarService { + factory CalendarService(Dio dio, {String baseUrl}) = _CalendarService; + + @GET('/calendar/index') + Future> getCalendar(); +} diff --git a/lib/features/calendar/services/calendar_service.g.dart b/lib/features/calendar/services/calendar_service.g.dart new file mode 100644 index 0000000..5703378 --- /dev/null +++ b/lib/features/calendar/services/calendar_service.g.dart @@ -0,0 +1,78 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'calendar_service.dart'; + +// ************************************************************************** +// RetrofitGenerator +// ************************************************************************** + +// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers,unused_element + +class _CalendarService implements CalendarService { + _CalendarService( + this._dio, { + this.baseUrl, + }); + + final Dio _dio; + + String? baseUrl; + + @override + Future> getCalendar() async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio.fetch>( + _setStreamType>(Options( + method: 'GET', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/calendar/index', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + var _value = _result.data!.map((k, dynamic v) => + MapEntry(k, CalendarModel.fromJson(v as Map))); + 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/features/diary/models/product.dart b/lib/features/diary/models/product.dart index fdac1bf..a11896d 100644 --- a/lib/features/diary/models/product.dart +++ b/lib/features/diary/models/product.dart @@ -8,23 +8,6 @@ class Product with _$Product { const factory Product({ required int id, required String name, - required String image, - required int productGroupId, - required String description, - required String formulations, - required int energyOn100gr, - required double proteinsOn100gr, - required double fatsOn100gr, - required double carbohydratesOn100gr, - required int portionMassGr, - required int energyOnPortion, - required int proteinsOnPortion, - required int fatsOnPortion, - required int carbohydratesOnPortion, - required String createdAt, - required String updatedAt, - required String lastState, - String? reqjectReason, }) = _Product; factory Product.fromJson(Map json) => diff --git a/lib/features/diary/models/product.freezed.dart b/lib/features/diary/models/product.freezed.dart index 0b829eb..d30ada3 100644 --- a/lib/features/diary/models/product.freezed.dart +++ b/lib/features/diary/models/product.freezed.dart @@ -22,23 +22,6 @@ Product _$ProductFromJson(Map json) { mixin _$Product { int get id => throw _privateConstructorUsedError; String get name => throw _privateConstructorUsedError; - String get image => throw _privateConstructorUsedError; - int get productGroupId => throw _privateConstructorUsedError; - String get description => throw _privateConstructorUsedError; - String get formulations => throw _privateConstructorUsedError; - int get energyOn100gr => throw _privateConstructorUsedError; - double get proteinsOn100gr => throw _privateConstructorUsedError; - double get fatsOn100gr => throw _privateConstructorUsedError; - double get carbohydratesOn100gr => throw _privateConstructorUsedError; - int get portionMassGr => throw _privateConstructorUsedError; - int get energyOnPortion => throw _privateConstructorUsedError; - int get proteinsOnPortion => throw _privateConstructorUsedError; - int get fatsOnPortion => throw _privateConstructorUsedError; - int get carbohydratesOnPortion => throw _privateConstructorUsedError; - String get createdAt => throw _privateConstructorUsedError; - String get updatedAt => throw _privateConstructorUsedError; - String get lastState => throw _privateConstructorUsedError; - String? get reqjectReason => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -50,26 +33,7 @@ abstract class $ProductCopyWith<$Res> { factory $ProductCopyWith(Product value, $Res Function(Product) then) = _$ProductCopyWithImpl<$Res, Product>; @useResult - $Res call( - {int id, - String name, - String image, - int productGroupId, - String description, - String formulations, - int energyOn100gr, - double proteinsOn100gr, - double fatsOn100gr, - double carbohydratesOn100gr, - int portionMassGr, - int energyOnPortion, - int proteinsOnPortion, - int fatsOnPortion, - int carbohydratesOnPortion, - String createdAt, - String updatedAt, - String lastState, - String? reqjectReason}); + $Res call({int id, String name}); } /// @nodoc @@ -87,23 +51,6 @@ class _$ProductCopyWithImpl<$Res, $Val extends Product> $Res call({ Object? id = null, Object? name = null, - Object? image = null, - Object? productGroupId = null, - Object? description = null, - Object? formulations = null, - Object? energyOn100gr = null, - Object? proteinsOn100gr = null, - Object? fatsOn100gr = null, - Object? carbohydratesOn100gr = null, - Object? portionMassGr = null, - Object? energyOnPortion = null, - Object? proteinsOnPortion = null, - Object? fatsOnPortion = null, - Object? carbohydratesOnPortion = null, - Object? createdAt = null, - Object? updatedAt = null, - Object? lastState = null, - Object? reqjectReason = freezed, }) { return _then(_value.copyWith( id: null == id @@ -114,74 +61,6 @@ class _$ProductCopyWithImpl<$Res, $Val extends Product> ? _value.name : name // ignore: cast_nullable_to_non_nullable as String, - image: null == image - ? _value.image - : image // ignore: cast_nullable_to_non_nullable - as String, - productGroupId: null == productGroupId - ? _value.productGroupId - : productGroupId // ignore: cast_nullable_to_non_nullable - as int, - description: null == description - ? _value.description - : description // ignore: cast_nullable_to_non_nullable - as String, - formulations: null == formulations - ? _value.formulations - : formulations // ignore: cast_nullable_to_non_nullable - as String, - energyOn100gr: null == energyOn100gr - ? _value.energyOn100gr - : energyOn100gr // ignore: cast_nullable_to_non_nullable - as int, - proteinsOn100gr: null == proteinsOn100gr - ? _value.proteinsOn100gr - : proteinsOn100gr // ignore: cast_nullable_to_non_nullable - as double, - fatsOn100gr: null == fatsOn100gr - ? _value.fatsOn100gr - : fatsOn100gr // ignore: cast_nullable_to_non_nullable - as double, - carbohydratesOn100gr: null == carbohydratesOn100gr - ? _value.carbohydratesOn100gr - : carbohydratesOn100gr // ignore: cast_nullable_to_non_nullable - as double, - portionMassGr: null == portionMassGr - ? _value.portionMassGr - : portionMassGr // ignore: cast_nullable_to_non_nullable - as int, - energyOnPortion: null == energyOnPortion - ? _value.energyOnPortion - : energyOnPortion // ignore: cast_nullable_to_non_nullable - as int, - proteinsOnPortion: null == proteinsOnPortion - ? _value.proteinsOnPortion - : proteinsOnPortion // ignore: cast_nullable_to_non_nullable - as int, - fatsOnPortion: null == fatsOnPortion - ? _value.fatsOnPortion - : fatsOnPortion // ignore: cast_nullable_to_non_nullable - as int, - carbohydratesOnPortion: null == carbohydratesOnPortion - ? _value.carbohydratesOnPortion - : carbohydratesOnPortion // ignore: cast_nullable_to_non_nullable - as int, - createdAt: null == createdAt - ? _value.createdAt - : createdAt // ignore: cast_nullable_to_non_nullable - as String, - updatedAt: null == updatedAt - ? _value.updatedAt - : updatedAt // ignore: cast_nullable_to_non_nullable - as String, - lastState: null == lastState - ? _value.lastState - : lastState // ignore: cast_nullable_to_non_nullable - as String, - reqjectReason: freezed == reqjectReason - ? _value.reqjectReason - : reqjectReason // ignore: cast_nullable_to_non_nullable - as String?, ) as $Val); } } @@ -193,26 +72,7 @@ abstract class _$$ProductImplCopyWith<$Res> implements $ProductCopyWith<$Res> { __$$ProductImplCopyWithImpl<$Res>; @override @useResult - $Res call( - {int id, - String name, - String image, - int productGroupId, - String description, - String formulations, - int energyOn100gr, - double proteinsOn100gr, - double fatsOn100gr, - double carbohydratesOn100gr, - int portionMassGr, - int energyOnPortion, - int proteinsOnPortion, - int fatsOnPortion, - int carbohydratesOnPortion, - String createdAt, - String updatedAt, - String lastState, - String? reqjectReason}); + $Res call({int id, String name}); } /// @nodoc @@ -228,23 +88,6 @@ class __$$ProductImplCopyWithImpl<$Res> $Res call({ Object? id = null, Object? name = null, - Object? image = null, - Object? productGroupId = null, - Object? description = null, - Object? formulations = null, - Object? energyOn100gr = null, - Object? proteinsOn100gr = null, - Object? fatsOn100gr = null, - Object? carbohydratesOn100gr = null, - Object? portionMassGr = null, - Object? energyOnPortion = null, - Object? proteinsOnPortion = null, - Object? fatsOnPortion = null, - Object? carbohydratesOnPortion = null, - Object? createdAt = null, - Object? updatedAt = null, - Object? lastState = null, - Object? reqjectReason = freezed, }) { return _then(_$ProductImpl( id: null == id @@ -255,74 +98,6 @@ class __$$ProductImplCopyWithImpl<$Res> ? _value.name : name // ignore: cast_nullable_to_non_nullable as String, - image: null == image - ? _value.image - : image // ignore: cast_nullable_to_non_nullable - as String, - productGroupId: null == productGroupId - ? _value.productGroupId - : productGroupId // ignore: cast_nullable_to_non_nullable - as int, - description: null == description - ? _value.description - : description // ignore: cast_nullable_to_non_nullable - as String, - formulations: null == formulations - ? _value.formulations - : formulations // ignore: cast_nullable_to_non_nullable - as String, - energyOn100gr: null == energyOn100gr - ? _value.energyOn100gr - : energyOn100gr // ignore: cast_nullable_to_non_nullable - as int, - proteinsOn100gr: null == proteinsOn100gr - ? _value.proteinsOn100gr - : proteinsOn100gr // ignore: cast_nullable_to_non_nullable - as double, - fatsOn100gr: null == fatsOn100gr - ? _value.fatsOn100gr - : fatsOn100gr // ignore: cast_nullable_to_non_nullable - as double, - carbohydratesOn100gr: null == carbohydratesOn100gr - ? _value.carbohydratesOn100gr - : carbohydratesOn100gr // ignore: cast_nullable_to_non_nullable - as double, - portionMassGr: null == portionMassGr - ? _value.portionMassGr - : portionMassGr // ignore: cast_nullable_to_non_nullable - as int, - energyOnPortion: null == energyOnPortion - ? _value.energyOnPortion - : energyOnPortion // ignore: cast_nullable_to_non_nullable - as int, - proteinsOnPortion: null == proteinsOnPortion - ? _value.proteinsOnPortion - : proteinsOnPortion // ignore: cast_nullable_to_non_nullable - as int, - fatsOnPortion: null == fatsOnPortion - ? _value.fatsOnPortion - : fatsOnPortion // ignore: cast_nullable_to_non_nullable - as int, - carbohydratesOnPortion: null == carbohydratesOnPortion - ? _value.carbohydratesOnPortion - : carbohydratesOnPortion // ignore: cast_nullable_to_non_nullable - as int, - createdAt: null == createdAt - ? _value.createdAt - : createdAt // ignore: cast_nullable_to_non_nullable - as String, - updatedAt: null == updatedAt - ? _value.updatedAt - : updatedAt // ignore: cast_nullable_to_non_nullable - as String, - lastState: null == lastState - ? _value.lastState - : lastState // ignore: cast_nullable_to_non_nullable - as String, - reqjectReason: freezed == reqjectReason - ? _value.reqjectReason - : reqjectReason // ignore: cast_nullable_to_non_nullable - as String?, )); } } @@ -330,26 +105,7 @@ class __$$ProductImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() class _$ProductImpl implements _Product { - const _$ProductImpl( - {required this.id, - required this.name, - required this.image, - required this.productGroupId, - required this.description, - required this.formulations, - required this.energyOn100gr, - required this.proteinsOn100gr, - required this.fatsOn100gr, - required this.carbohydratesOn100gr, - required this.portionMassGr, - required this.energyOnPortion, - required this.proteinsOnPortion, - required this.fatsOnPortion, - required this.carbohydratesOnPortion, - required this.createdAt, - required this.updatedAt, - required this.lastState, - this.reqjectReason}); + const _$ProductImpl({required this.id, required this.name}); factory _$ProductImpl.fromJson(Map json) => _$$ProductImplFromJson(json); @@ -358,44 +114,10 @@ class _$ProductImpl implements _Product { final int id; @override final String name; - @override - final String image; - @override - final int productGroupId; - @override - final String description; - @override - final String formulations; - @override - final int energyOn100gr; - @override - final double proteinsOn100gr; - @override - final double fatsOn100gr; - @override - final double carbohydratesOn100gr; - @override - final int portionMassGr; - @override - final int energyOnPortion; - @override - final int proteinsOnPortion; - @override - final int fatsOnPortion; - @override - final int carbohydratesOnPortion; - @override - final String createdAt; - @override - final String updatedAt; - @override - final String lastState; - @override - final String? reqjectReason; @override String toString() { - return 'Product(id: $id, name: $name, image: $image, productGroupId: $productGroupId, description: $description, formulations: $formulations, energyOn100gr: $energyOn100gr, proteinsOn100gr: $proteinsOn100gr, fatsOn100gr: $fatsOn100gr, carbohydratesOn100gr: $carbohydratesOn100gr, portionMassGr: $portionMassGr, energyOnPortion: $energyOnPortion, proteinsOnPortion: $proteinsOnPortion, fatsOnPortion: $fatsOnPortion, carbohydratesOnPortion: $carbohydratesOnPortion, createdAt: $createdAt, updatedAt: $updatedAt, lastState: $lastState, reqjectReason: $reqjectReason)'; + return 'Product(id: $id, name: $name)'; } @override @@ -404,66 +126,12 @@ class _$ProductImpl implements _Product { (other.runtimeType == runtimeType && other is _$ProductImpl && (identical(other.id, id) || other.id == id) && - (identical(other.name, name) || other.name == name) && - (identical(other.image, image) || other.image == image) && - (identical(other.productGroupId, productGroupId) || - other.productGroupId == productGroupId) && - (identical(other.description, description) || - other.description == description) && - (identical(other.formulations, formulations) || - other.formulations == formulations) && - (identical(other.energyOn100gr, energyOn100gr) || - other.energyOn100gr == energyOn100gr) && - (identical(other.proteinsOn100gr, proteinsOn100gr) || - other.proteinsOn100gr == proteinsOn100gr) && - (identical(other.fatsOn100gr, fatsOn100gr) || - other.fatsOn100gr == fatsOn100gr) && - (identical(other.carbohydratesOn100gr, carbohydratesOn100gr) || - other.carbohydratesOn100gr == carbohydratesOn100gr) && - (identical(other.portionMassGr, portionMassGr) || - other.portionMassGr == portionMassGr) && - (identical(other.energyOnPortion, energyOnPortion) || - other.energyOnPortion == energyOnPortion) && - (identical(other.proteinsOnPortion, proteinsOnPortion) || - other.proteinsOnPortion == proteinsOnPortion) && - (identical(other.fatsOnPortion, fatsOnPortion) || - other.fatsOnPortion == fatsOnPortion) && - (identical(other.carbohydratesOnPortion, carbohydratesOnPortion) || - other.carbohydratesOnPortion == carbohydratesOnPortion) && - (identical(other.createdAt, createdAt) || - other.createdAt == createdAt) && - (identical(other.updatedAt, updatedAt) || - other.updatedAt == updatedAt) && - (identical(other.lastState, lastState) || - other.lastState == lastState) && - (identical(other.reqjectReason, reqjectReason) || - other.reqjectReason == reqjectReason)); + (identical(other.name, name) || other.name == name)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hashAll([ - runtimeType, - id, - name, - image, - productGroupId, - description, - formulations, - energyOn100gr, - proteinsOn100gr, - fatsOn100gr, - carbohydratesOn100gr, - portionMassGr, - energyOnPortion, - proteinsOnPortion, - fatsOnPortion, - carbohydratesOnPortion, - createdAt, - updatedAt, - lastState, - reqjectReason - ]); + int get hashCode => Object.hash(runtimeType, id, name); @JsonKey(ignore: true) @override @@ -480,26 +148,8 @@ class _$ProductImpl implements _Product { } abstract class _Product implements Product { - const factory _Product( - {required final int id, - required final String name, - required final String image, - required final int productGroupId, - required final String description, - required final String formulations, - required final int energyOn100gr, - required final double proteinsOn100gr, - required final double fatsOn100gr, - required final double carbohydratesOn100gr, - required final int portionMassGr, - required final int energyOnPortion, - required final int proteinsOnPortion, - required final int fatsOnPortion, - required final int carbohydratesOnPortion, - required final String createdAt, - required final String updatedAt, - required final String lastState, - final String? reqjectReason}) = _$ProductImpl; + const factory _Product({required final int id, required final String name}) = + _$ProductImpl; factory _Product.fromJson(Map json) = _$ProductImpl.fromJson; @@ -508,40 +158,6 @@ abstract class _Product implements Product { @override String get name; @override - String get image; - @override - int get productGroupId; - @override - String get description; - @override - String get formulations; - @override - int get energyOn100gr; - @override - double get proteinsOn100gr; - @override - double get fatsOn100gr; - @override - double get carbohydratesOn100gr; - @override - int get portionMassGr; - @override - int get energyOnPortion; - @override - int get proteinsOnPortion; - @override - int get fatsOnPortion; - @override - int get carbohydratesOnPortion; - @override - String get createdAt; - @override - String get updatedAt; - @override - String get lastState; - @override - String? get reqjectReason; - @override @JsonKey(ignore: true) _$$ProductImplCopyWith<_$ProductImpl> get copyWith => throw _privateConstructorUsedError; diff --git a/lib/features/diary/models/product.g.dart b/lib/features/diary/models/product.g.dart index 566a7b4..7433110 100644 --- a/lib/features/diary/models/product.g.dart +++ b/lib/features/diary/models/product.g.dart @@ -10,44 +10,10 @@ _$ProductImpl _$$ProductImplFromJson(Map json) => _$ProductImpl( id: (json['id'] as num).toInt(), name: json['name'] as String, - image: json['image'] as String, - productGroupId: (json['productGroupId'] as num).toInt(), - description: json['description'] as String, - formulations: json['formulations'] as String, - energyOn100gr: (json['energyOn100gr'] as num).toInt(), - proteinsOn100gr: (json['proteinsOn100gr'] as num).toDouble(), - fatsOn100gr: (json['fatsOn100gr'] as num).toDouble(), - carbohydratesOn100gr: (json['carbohydratesOn100gr'] as num).toDouble(), - portionMassGr: (json['portionMassGr'] as num).toInt(), - energyOnPortion: (json['energyOnPortion'] as num).toInt(), - proteinsOnPortion: (json['proteinsOnPortion'] as num).toInt(), - fatsOnPortion: (json['fatsOnPortion'] as num).toInt(), - carbohydratesOnPortion: (json['carbohydratesOnPortion'] as num).toInt(), - createdAt: json['createdAt'] as String, - updatedAt: json['updatedAt'] as String, - lastState: json['lastState'] as String, - reqjectReason: json['reqjectReason'] as String?, ); Map _$$ProductImplToJson(_$ProductImpl instance) => { 'id': instance.id, 'name': instance.name, - 'image': instance.image, - 'productGroupId': instance.productGroupId, - 'description': instance.description, - 'formulations': instance.formulations, - 'energyOn100gr': instance.energyOn100gr, - 'proteinsOn100gr': instance.proteinsOn100gr, - 'fatsOn100gr': instance.fatsOn100gr, - 'carbohydratesOn100gr': instance.carbohydratesOn100gr, - 'portionMassGr': instance.portionMassGr, - 'energyOnPortion': instance.energyOnPortion, - 'proteinsOnPortion': instance.proteinsOnPortion, - 'fatsOnPortion': instance.fatsOnPortion, - 'carbohydratesOnPortion': instance.carbohydratesOnPortion, - 'createdAt': instance.createdAt, - 'updatedAt': instance.updatedAt, - 'lastState': instance.lastState, - 'reqjectReason': instance.reqjectReason, }; diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index 216131f..faaac8a 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -261,9 +261,9 @@ class DiaryBloc extends Bloc { if (state is DiaryStateLoaded) { //var currentState = state as DiaryStateLoaded; + print(await diaryRepository.inputProduct(event.input)); final Map> productNutritionalValues = await diaryRepository.inputProduct(event.input); - print(productNutritionalValues); // Create a new controller with the input text and update the autocomplete list /*var updatedState = currentState.copyWith( productNameController: TextEditingController(text: event.input), -- 2.49.1 From 7535e824221bbd64ee8883d28016d4468aee2afe Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 19 Jul 2024 15:51:39 +0300 Subject: [PATCH 073/110] fix(diary): Remove portion API call fixed --- lib/features/diary/models/portion.dart | 2 +- .../diary/models/portion.freezed.dart | 38 ++--- lib/features/diary/models/portion.g.dart | 4 +- .../diary/presentation/bloc/diary_bloc.dart | 70 +++------ .../diary/presentation/bloc/diary_state.dart | 5 +- .../bloc/diary_state.freezed.dart | 146 +++++++++--------- .../presentation/pages/diary_screen.dart | 91 +++++++---- .../diary/repositories/diary_repository.dart | 9 +- .../diary/services/diary_service.dart | 7 +- .../diary/services/diary_service.g.dart | 40 +++-- 10 files changed, 217 insertions(+), 195 deletions(-) diff --git a/lib/features/diary/models/portion.dart b/lib/features/diary/models/portion.dart index 9712d9b..ec4ab1d 100644 --- a/lib/features/diary/models/portion.dart +++ b/lib/features/diary/models/portion.dart @@ -7,7 +7,7 @@ part 'portion.g.dart'; class Portion with _$Portion { const factory Portion({ required int id, - required String productName, + required String product_name, required int quantity, required String portion, }) = _Portion; diff --git a/lib/features/diary/models/portion.freezed.dart b/lib/features/diary/models/portion.freezed.dart index ab79213..a7a35a2 100644 --- a/lib/features/diary/models/portion.freezed.dart +++ b/lib/features/diary/models/portion.freezed.dart @@ -21,7 +21,7 @@ Portion _$PortionFromJson(Map json) { /// @nodoc mixin _$Portion { int get id => throw _privateConstructorUsedError; - String get productName => throw _privateConstructorUsedError; + String get product_name => throw _privateConstructorUsedError; int get quantity => throw _privateConstructorUsedError; String get portion => throw _privateConstructorUsedError; @@ -35,7 +35,7 @@ abstract class $PortionCopyWith<$Res> { factory $PortionCopyWith(Portion value, $Res Function(Portion) then) = _$PortionCopyWithImpl<$Res, Portion>; @useResult - $Res call({int id, String productName, int quantity, String portion}); + $Res call({int id, String product_name, int quantity, String portion}); } /// @nodoc @@ -52,7 +52,7 @@ class _$PortionCopyWithImpl<$Res, $Val extends Portion> @override $Res call({ Object? id = null, - Object? productName = null, + Object? product_name = null, Object? quantity = null, Object? portion = null, }) { @@ -61,9 +61,9 @@ class _$PortionCopyWithImpl<$Res, $Val extends Portion> ? _value.id : id // ignore: cast_nullable_to_non_nullable as int, - productName: null == productName - ? _value.productName - : productName // ignore: cast_nullable_to_non_nullable + product_name: null == product_name + ? _value.product_name + : product_name // ignore: cast_nullable_to_non_nullable as String, quantity: null == quantity ? _value.quantity @@ -84,7 +84,7 @@ abstract class _$$PortionImplCopyWith<$Res> implements $PortionCopyWith<$Res> { __$$PortionImplCopyWithImpl<$Res>; @override @useResult - $Res call({int id, String productName, int quantity, String portion}); + $Res call({int id, String product_name, int quantity, String portion}); } /// @nodoc @@ -99,7 +99,7 @@ class __$$PortionImplCopyWithImpl<$Res> @override $Res call({ Object? id = null, - Object? productName = null, + Object? product_name = null, Object? quantity = null, Object? portion = null, }) { @@ -108,9 +108,9 @@ class __$$PortionImplCopyWithImpl<$Res> ? _value.id : id // ignore: cast_nullable_to_non_nullable as int, - productName: null == productName - ? _value.productName - : productName // ignore: cast_nullable_to_non_nullable + product_name: null == product_name + ? _value.product_name + : product_name // ignore: cast_nullable_to_non_nullable as String, quantity: null == quantity ? _value.quantity @@ -129,7 +129,7 @@ class __$$PortionImplCopyWithImpl<$Res> class _$PortionImpl implements _Portion { const _$PortionImpl( {required this.id, - required this.productName, + required this.product_name, required this.quantity, required this.portion}); @@ -139,7 +139,7 @@ class _$PortionImpl implements _Portion { @override final int id; @override - final String productName; + final String product_name; @override final int quantity; @override @@ -147,7 +147,7 @@ class _$PortionImpl implements _Portion { @override String toString() { - return 'Portion(id: $id, productName: $productName, quantity: $quantity, portion: $portion)'; + return 'Portion(id: $id, product_name: $product_name, quantity: $quantity, portion: $portion)'; } @override @@ -156,8 +156,8 @@ class _$PortionImpl implements _Portion { (other.runtimeType == runtimeType && other is _$PortionImpl && (identical(other.id, id) || other.id == id) && - (identical(other.productName, productName) || - other.productName == productName) && + (identical(other.product_name, product_name) || + other.product_name == product_name) && (identical(other.quantity, quantity) || other.quantity == quantity) && (identical(other.portion, portion) || other.portion == portion)); @@ -166,7 +166,7 @@ class _$PortionImpl implements _Portion { @JsonKey(ignore: true) @override int get hashCode => - Object.hash(runtimeType, id, productName, quantity, portion); + Object.hash(runtimeType, id, product_name, quantity, portion); @JsonKey(ignore: true) @override @@ -185,7 +185,7 @@ class _$PortionImpl implements _Portion { abstract class _Portion implements Portion { const factory _Portion( {required final int id, - required final String productName, + required final String product_name, required final int quantity, required final String portion}) = _$PortionImpl; @@ -194,7 +194,7 @@ abstract class _Portion implements Portion { @override int get id; @override - String get productName; + String get product_name; @override int get quantity; @override diff --git a/lib/features/diary/models/portion.g.dart b/lib/features/diary/models/portion.g.dart index aae2162..c8bd109 100644 --- a/lib/features/diary/models/portion.g.dart +++ b/lib/features/diary/models/portion.g.dart @@ -9,7 +9,7 @@ part of 'portion.dart'; _$PortionImpl _$$PortionImplFromJson(Map json) => _$PortionImpl( id: (json['id'] as num).toInt(), - productName: json['productName'] as String, + product_name: json['product_name'] as String, quantity: (json['quantity'] as num).toInt(), portion: json['portion'] as String, ); @@ -17,7 +17,7 @@ _$PortionImpl _$$PortionImplFromJson(Map json) => Map _$$PortionImplToJson(_$PortionImpl instance) => { 'id': instance.id, - 'productName': instance.productName, + 'product_name': instance.product_name, 'quantity': instance.quantity, 'portion': instance.portion, }; diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index faaac8a..37abfdc 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:eatvio_app/features/diary/models/meal.dart'; +import 'package:eatvio_app/features/diary/models/portion.dart'; import 'package:eatvio_app/features/diary/models/product.dart'; import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; import 'package:intl/intl.dart'; @@ -82,7 +83,7 @@ class DiaryBloc extends Bloc { selectedMood: currentMeal.mood, selectedSatiety: currentMeal.satiety, commentController: TextEditingController(), - productNameController: TextEditingController(), + product_nameController: TextEditingController(), productQuantityController: TextEditingController(), caloriesController: TextEditingController(), fatsController: TextEditingController(), @@ -259,15 +260,14 @@ class DiaryBloc extends Bloc { Emitter emit, ) async { if (state is DiaryStateLoaded) { - //var currentState = state as DiaryStateLoaded; + var currentState = state as DiaryStateLoaded; - print(await diaryRepository.inputProduct(event.input)); final Map> productNutritionalValues = await diaryRepository.inputProduct(event.input); - // Create a new controller with the input text and update the autocomplete list - /*var updatedState = currentState.copyWith( - productNameController: TextEditingController(text: event.input), - autocompleteList: productNutritionalValues.map((product) => product['name']).toList(), + var updatedState = currentState.copyWith( + product_nameController: TextEditingController(text: event.input), + autocompleteList: + productNutritionalValues['product_nutritional_value'] ?? [], ); if (event.input.length > 3) { updatedState = updatedState.copyWith(moderationExpanded: true); @@ -275,7 +275,7 @@ class DiaryBloc extends Bloc { updatedState = updatedState.copyWith(moderationExpanded: false); } - emit(updatedState); */ + emit(updatedState); } } @@ -331,16 +331,25 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; + print(currentState.diary.id); + print(currentState.currentMeal.id); + print(currentState.product_nameController.text); + print(currentState.portionController.title); + print(currentState.productQuantityController.text); - await diaryRepository.addPortion( + Map data = await diaryRepository.addPortion( currentState.diary.id, currentState.currentMeal.id, - currentState.productNameController.text, - currentState.portionController.value, + currentState.product_nameController.text, + currentState.portionController.title, int.parse(currentState.productQuantityController.text), ); + List newPortions = currentState.portions; - emit(currentState.copyWith(isAdded: true)); + final Portion newPortion = data['portion'] ?? + new Portion(id: 1, portion: 'gr', product_name: '1', quantity: 1); + newPortions.add(newPortion); + emit(currentState.copyWith(isAdded: true, portions: newPortions)); } } @@ -350,45 +359,14 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - - int? mealId = - currentState.currentMeal.id; // Rename id to mealId for clarity - - var response = await sendRemovePortion( - event.portionId, - mealId, + await diaryRepository.removePortion( currentState.diary.id, + currentState.currentMeal.id, + event.portionId, ); - - if (response.statusCode == 204) { - await reloadScreen(event, emit); - } else { - print( - 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}', - ); - } } } - Future sendRemovePortion( - int? portionID, - int? mealID, - int diaryID, - ) async { - String url = - '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete'; - - var response = await http.delete( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - }, - encoding: utf8, - ); - - return response; - } - FutureOr _removeImage( RemoveImageEvent event, Emitter emit, diff --git a/lib/features/diary/presentation/bloc/diary_state.dart b/lib/features/diary/presentation/bloc/diary_state.dart index fa49016..57b3768 100644 --- a/lib/features/diary/presentation/bloc/diary_state.dart +++ b/lib/features/diary/presentation/bloc/diary_state.dart @@ -2,6 +2,7 @@ import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:eatvio_app/features/diary/models/meal.dart'; import 'package:eatvio_app/features/diary/models/photo.dart'; import 'package:eatvio_app/features/diary/models/portion.dart'; +import 'package:eatvio_app/features/diary/models/product.dart'; import 'package:flutter/material.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; @@ -18,20 +19,20 @@ abstract class DiaryState with _$DiaryState { const factory DiaryState.loaded({ required DiaryModel diary, String? diaryDate, - required List autocompleteList, required List recommendedChartValues, required List consumedChartValues, required List portions, required List photos, required List mealList, required List portionList, + required List autocompleteList, required Meal currentMeal, required SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, required TextEditingController commentController, - required TextEditingController productNameController, + required TextEditingController product_nameController, required TextEditingController productQuantityController, required TextEditingController caloriesController, required TextEditingController fatsController, diff --git a/lib/features/diary/presentation/bloc/diary_state.freezed.dart b/lib/features/diary/presentation/bloc/diary_state.freezed.dart index 2ecc30d..981a027 100644 --- a/lib/features/diary/presentation/bloc/diary_state.freezed.dart +++ b/lib/features/diary/presentation/bloc/diary_state.freezed.dart @@ -23,20 +23,20 @@ mixin _$DiaryState { required TResult Function( DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, @@ -60,20 +60,20 @@ mixin _$DiaryState { TResult? Function( DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, @@ -97,20 +97,20 @@ mixin _$DiaryState { TResult Function( DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, @@ -216,20 +216,20 @@ class _$DiaryStateImpl implements _DiaryState { required TResult Function( DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, @@ -256,20 +256,20 @@ class _$DiaryStateImpl implements _DiaryState { TResult? Function( DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, @@ -296,20 +296,20 @@ class _$DiaryStateImpl implements _DiaryState { TResult Function( DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, @@ -417,20 +417,20 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { required TResult Function( DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, @@ -457,20 +457,20 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { TResult? Function( DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, @@ -497,20 +497,20 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { TResult Function( DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, @@ -584,20 +584,20 @@ abstract class _$$DiaryStateLoadedImplCopyWith<$Res> { $Res call( {DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, @@ -628,20 +628,20 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> $Res call({ Object? diary = null, Object? diaryDate = freezed, - Object? autocompleteList = null, Object? recommendedChartValues = null, Object? consumedChartValues = null, Object? portions = null, Object? photos = null, Object? mealList = null, Object? portionList = null, + Object? autocompleteList = null, Object? currentMeal = null, Object? portionController = null, Object? wakeupController = freezed, Object? retireController = freezed, Object? mealTimeController = freezed, Object? commentController = null, - Object? productNameController = null, + Object? product_nameController = null, Object? productQuantityController = null, Object? caloriesController = null, Object? fatsController = null, @@ -664,10 +664,6 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> ? _value.diaryDate : diaryDate // ignore: cast_nullable_to_non_nullable as String?, - autocompleteList: null == autocompleteList - ? _value._autocompleteList - : autocompleteList // ignore: cast_nullable_to_non_nullable - as List, recommendedChartValues: null == recommendedChartValues ? _value._recommendedChartValues : recommendedChartValues // ignore: cast_nullable_to_non_nullable @@ -692,6 +688,10 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> ? _value._portionList : portionList // ignore: cast_nullable_to_non_nullable as List, + autocompleteList: null == autocompleteList + ? _value._autocompleteList + : autocompleteList // ignore: cast_nullable_to_non_nullable + as List, currentMeal: null == currentMeal ? _value.currentMeal : currentMeal // ignore: cast_nullable_to_non_nullable @@ -716,9 +716,9 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> ? _value.commentController : commentController // ignore: cast_nullable_to_non_nullable as TextEditingController, - productNameController: null == productNameController - ? _value.productNameController - : productNameController // ignore: cast_nullable_to_non_nullable + product_nameController: null == product_nameController + ? _value.product_nameController + : product_nameController // ignore: cast_nullable_to_non_nullable as TextEditingController, productQuantityController: null == productQuantityController ? _value.productQuantityController @@ -794,20 +794,20 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { const _$DiaryStateLoadedImpl( {required this.diary, this.diaryDate, - required final List autocompleteList, required final List recommendedChartValues, required final List consumedChartValues, required final List portions, required final List photos, required final List mealList, required final List portionList, + required final List autocompleteList, required this.currentMeal, required this.portionController, this.wakeupController, this.retireController, this.mealTimeController, required this.commentController, - required this.productNameController, + required this.product_nameController, required this.productQuantityController, required this.caloriesController, required this.fatsController, @@ -820,27 +820,18 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { required this.moodExpanded, required this.isLoading, required this.isAdded}) - : _autocompleteList = autocompleteList, - _recommendedChartValues = recommendedChartValues, + : _recommendedChartValues = recommendedChartValues, _consumedChartValues = consumedChartValues, _portions = portions, _photos = photos, _mealList = mealList, - _portionList = portionList; + _portionList = portionList, + _autocompleteList = autocompleteList; @override final DiaryModel diary; @override final String? diaryDate; - final List _autocompleteList; - @override - List get autocompleteList { - if (_autocompleteList is EqualUnmodifiableListView) - return _autocompleteList; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_autocompleteList); - } - final List _recommendedChartValues; @override List get recommendedChartValues { @@ -891,6 +882,15 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { return EqualUnmodifiableListView(_portionList); } + final List _autocompleteList; + @override + List get autocompleteList { + if (_autocompleteList is EqualUnmodifiableListView) + return _autocompleteList; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_autocompleteList); + } + @override final Meal currentMeal; @override @@ -904,7 +904,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { @override final TextEditingController commentController; @override - final TextEditingController productNameController; + final TextEditingController product_nameController; @override final TextEditingController productQuantityController; @override @@ -932,7 +932,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { @override String toString() { - return 'DiaryState.loaded(diary: $diary, diaryDate: $diaryDate, autocompleteList: $autocompleteList, recommendedChartValues: $recommendedChartValues, consumedChartValues: $consumedChartValues, portions: $portions, photos: $photos, mealList: $mealList, portionList: $portionList, currentMeal: $currentMeal, portionController: $portionController, wakeupController: $wakeupController, retireController: $retireController, mealTimeController: $mealTimeController, commentController: $commentController, productNameController: $productNameController, productQuantityController: $productQuantityController, caloriesController: $caloriesController, fatsController: $fatsController, proteinsController: $proteinsController, carbsController: $carbsController, selectedMood: $selectedMood, selectedSatiety: $selectedSatiety, wakeupExpanded: $wakeupExpanded, moderationExpanded: $moderationExpanded, moodExpanded: $moodExpanded, isLoading: $isLoading, isAdded: $isAdded)'; + return 'DiaryState.loaded(diary: $diary, diaryDate: $diaryDate, recommendedChartValues: $recommendedChartValues, consumedChartValues: $consumedChartValues, portions: $portions, photos: $photos, mealList: $mealList, portionList: $portionList, autocompleteList: $autocompleteList, currentMeal: $currentMeal, portionController: $portionController, wakeupController: $wakeupController, retireController: $retireController, mealTimeController: $mealTimeController, commentController: $commentController, product_nameController: $product_nameController, productQuantityController: $productQuantityController, caloriesController: $caloriesController, fatsController: $fatsController, proteinsController: $proteinsController, carbsController: $carbsController, selectedMood: $selectedMood, selectedSatiety: $selectedSatiety, wakeupExpanded: $wakeupExpanded, moderationExpanded: $moderationExpanded, moodExpanded: $moodExpanded, isLoading: $isLoading, isAdded: $isAdded)'; } @override @@ -943,8 +943,6 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { (identical(other.diary, diary) || other.diary == diary) && (identical(other.diaryDate, diaryDate) || other.diaryDate == diaryDate) && - const DeepCollectionEquality() - .equals(other._autocompleteList, _autocompleteList) && const DeepCollectionEquality().equals( other._recommendedChartValues, _recommendedChartValues) && const DeepCollectionEquality() @@ -954,6 +952,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { const DeepCollectionEquality().equals(other._mealList, _mealList) && const DeepCollectionEquality() .equals(other._portionList, _portionList) && + const DeepCollectionEquality() + .equals(other._autocompleteList, _autocompleteList) && (identical(other.currentMeal, currentMeal) || other.currentMeal == currentMeal) && (identical(other.portionController, portionController) || @@ -966,8 +966,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { other.mealTimeController == mealTimeController) && (identical(other.commentController, commentController) || other.commentController == commentController) && - (identical(other.productNameController, productNameController) || - other.productNameController == productNameController) && + (identical(other.product_nameController, product_nameController) || + other.product_nameController == product_nameController) && (identical(other.productQuantityController, productQuantityController) || other.productQuantityController == productQuantityController) && @@ -999,20 +999,20 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { runtimeType, diary, diaryDate, - const DeepCollectionEquality().hash(_autocompleteList), const DeepCollectionEquality().hash(_recommendedChartValues), const DeepCollectionEquality().hash(_consumedChartValues), const DeepCollectionEquality().hash(_portions), const DeepCollectionEquality().hash(_photos), const DeepCollectionEquality().hash(_mealList), const DeepCollectionEquality().hash(_portionList), + const DeepCollectionEquality().hash(_autocompleteList), currentMeal, portionController, wakeupController, retireController, mealTimeController, commentController, - productNameController, + product_nameController, productQuantityController, caloriesController, fatsController, @@ -1042,20 +1042,20 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { required TResult Function( DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, @@ -1074,20 +1074,20 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { return loaded( diary, diaryDate, - autocompleteList, recommendedChartValues, consumedChartValues, portions, photos, mealList, portionList, + autocompleteList, currentMeal, portionController, wakeupController, retireController, mealTimeController, commentController, - productNameController, + product_nameController, productQuantityController, caloriesController, fatsController, @@ -1110,20 +1110,20 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { TResult? Function( DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, @@ -1142,20 +1142,20 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { return loaded?.call( diary, diaryDate, - autocompleteList, recommendedChartValues, consumedChartValues, portions, photos, mealList, portionList, + autocompleteList, currentMeal, portionController, wakeupController, retireController, mealTimeController, commentController, - productNameController, + product_nameController, productQuantityController, caloriesController, fatsController, @@ -1178,20 +1178,20 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { TResult Function( DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, @@ -1212,20 +1212,20 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { return loaded( diary, diaryDate, - autocompleteList, recommendedChartValues, consumedChartValues, portions, photos, mealList, portionList, + autocompleteList, currentMeal, portionController, wakeupController, retireController, mealTimeController, commentController, - productNameController, + product_nameController, productQuantityController, caloriesController, fatsController, @@ -1284,20 +1284,20 @@ abstract class DiaryStateLoaded implements DiaryState { const factory DiaryStateLoaded( {required final DiaryModel diary, final String? diaryDate, - required final List autocompleteList, required final List recommendedChartValues, required final List consumedChartValues, required final List portions, required final List photos, required final List mealList, required final List portionList, + required final List autocompleteList, required final Meal currentMeal, required final SelectionPopupModel portionController, final TimeOfDay? wakeupController, final TimeOfDay? retireController, final TimeOfDay? mealTimeController, required final TextEditingController commentController, - required final TextEditingController productNameController, + required final TextEditingController product_nameController, required final TextEditingController productQuantityController, required final TextEditingController caloriesController, required final TextEditingController fatsController, @@ -1313,20 +1313,20 @@ abstract class DiaryStateLoaded implements DiaryState { DiaryModel get diary; String? get diaryDate; - List get autocompleteList; List get recommendedChartValues; List get consumedChartValues; List get portions; List get photos; List get mealList; List get portionList; + List get autocompleteList; Meal get currentMeal; SelectionPopupModel get portionController; TimeOfDay? get wakeupController; TimeOfDay? get retireController; TimeOfDay? get mealTimeController; TextEditingController get commentController; - TextEditingController get productNameController; + TextEditingController get product_nameController; TextEditingController get productQuantityController; TextEditingController get caloriesController; TextEditingController get fatsController; @@ -1415,20 +1415,20 @@ class _$DiaryStateErrorImpl implements DiaryStateError { required TResult Function( DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, @@ -1455,20 +1455,20 @@ class _$DiaryStateErrorImpl implements DiaryStateError { TResult? Function( DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, @@ -1495,20 +1495,20 @@ class _$DiaryStateErrorImpl implements DiaryStateError { TResult Function( DiaryModel diary, String? diaryDate, - List autocompleteList, List recommendedChartValues, List consumedChartValues, List portions, List photos, List mealList, List portionList, + List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay? wakeupController, TimeOfDay? retireController, TimeOfDay? mealTimeController, TextEditingController commentController, - TextEditingController productNameController, + TextEditingController product_nameController, TextEditingController productQuantityController, TextEditingController caloriesController, TextEditingController fatsController, diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index 422d8bc..5603abb 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -4,6 +4,7 @@ import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:eatvio_app/features/diary/models/meal.dart'; import 'package:eatvio_app/features/diary/models/photo.dart'; import 'package:eatvio_app/features/diary/models/portion.dart'; +import 'package:eatvio_app/features/diary/models/product.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:flutter/cupertino.dart'; @@ -247,7 +248,9 @@ class DiaryScreen extends StatelessWidget { borderRadius: BorderRadiusStyle.roundedBorder5, ), child: Center( - child: CircularProgressIndicator(color: appTheme.blueGray300), // Замените на свой прелоадер при необходимости + child: CircularProgressIndicator( + color: appTheme + .blueGray300), // Замените на свой прелоадер при необходимости ), ), ], @@ -271,7 +274,8 @@ class DiaryScreen extends StatelessWidget { _buildMeal(BuildContext context, DiaryStateLoaded state) { final digitsOnly = FilteringTextInputFormatter.digitsOnly; - List _options = state.autocompleteList.map((dynamic item) => item as String).toList(); + List _options = + state.autocompleteList.map((Product item) => item.name).toList(); FocusNode focusNodeName = FocusNode(); return Container( margin: EdgeInsets.symmetric(horizontal: 16.h), @@ -315,7 +319,9 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectMealTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: state.mealTimeController?.format(context).toString(), + hintText: state.mealTimeController + ?.format(context) + .toString(), autofocus: false, ), ), @@ -451,7 +457,9 @@ class DiaryScreen extends StatelessWidget { SizedBox(height: 30.v), _buildAddProduct(context, state), SizedBox(height: 30.v), - ...state.portions.map((portion) => _buildProduct(context, portion)).toList(), + ...state.portions + .map((portion) => _buildProduct(context, portion)) + .toList(), SizedBox(height: 30.v), /*...state.photos != null ? state.photos!.isEmpty @@ -531,7 +539,7 @@ class DiaryScreen extends StatelessWidget { children: [ CustomTextFormField( hintText: "Название", - controller: state.productNameController, + controller: state.product_nameController, ), SizedBox(height: 10.v), CustomTextFormField( @@ -567,7 +575,7 @@ class DiaryScreen extends StatelessWidget { TextButton( onPressed: triggerModeration( context, - state.productNameController.text, + state.product_nameController.text, state.caloriesController.text, state.proteinsController.text, state.fatsController.text, @@ -608,7 +616,8 @@ class DiaryScreen extends StatelessWidget { popDialog(BuildContext dialogContext) { return () { - Navigator.of(dialogContext).pop(); // Dismiss the dialog on Cancel button press + Navigator.of(dialogContext) + .pop(); // Dismiss the dialog on Cancel button press }; } @@ -618,8 +627,9 @@ class DiaryScreen extends StatelessWidget { }; } - selectProduct(AutocompleteOnSelected onSelected, String option, DiaryStateLoaded state) { - state.productNameController.text = option; + selectProduct(AutocompleteOnSelected onSelected, String option, + DiaryStateLoaded state) { + state.product_nameController.text = option; return () { onSelected(option); }; @@ -660,7 +670,8 @@ class DiaryScreen extends StatelessWidget { return CarouselSlider( options: CarouselOptions(height: 340.0), items: state.currentMeal.photos.map((photo) { - return _buildPhoto(context, photo); // Assuming photos are stored as strings + return _buildPhoto( + context, photo); // Assuming photos are stored as strings }).toList(), ); } @@ -686,7 +697,9 @@ class DiaryScreen extends StatelessWidget { top: 5.v, ), child: Text( - portion.productName.length > 8 ? portion.productName.substring(0, 8) : portion.productName, + portion.product_name.length > 8 + ? portion.product_name.substring(0, 8) + : portion.product_name, style: CustomTextStyles.titleMedium16, ), ), @@ -758,12 +771,15 @@ class DiaryScreen extends StatelessWidget { removePhoto(BuildContext context, Photo photo) { return () { - context.read().add(RemoveImageEvent(photo.id.toString(), photo.path)); + context + .read() + .add(RemoveImageEvent(photo.id.toString(), photo.path)); }; } _buildNutritionChart(BuildContext context, DiaryStateLoaded state) { - final List recommendedValues = state.recommendedChartValues; // Рекомендуемые значения: калории, жиры, белки, углеводы + final List recommendedValues = state + .recommendedChartValues; // Рекомендуемые значения: калории, жиры, белки, углеводы final List consumedValues = state.consumedChartValues; // return Container( margin: EdgeInsets.symmetric(horizontal: 16.h), @@ -827,7 +843,10 @@ class DiaryScreen extends StatelessWidget { barRods: [ BarChartRodData( toY: consumedValues[0] / recommendedValues[0] * 100, - color: checkConsumedValues([recommendedValues[0]], [consumedValues[1]]) ? Colors.red : Colors.blue, + color: checkConsumedValues( + [recommendedValues[0]], [consumedValues[1]]) + ? Colors.red + : Colors.blue, ), ], ), @@ -836,7 +855,10 @@ class DiaryScreen extends StatelessWidget { barRods: [ BarChartRodData( toY: consumedValues[1] / recommendedValues[1] * 100, - color: checkConsumedValues([recommendedValues[1]], [consumedValues[1]]) ? Colors.red : Colors.blue, + color: checkConsumedValues( + [recommendedValues[1]], [consumedValues[1]]) + ? Colors.red + : Colors.blue, ), ], ), @@ -845,7 +867,10 @@ class DiaryScreen extends StatelessWidget { barRods: [ BarChartRodData( toY: consumedValues[2] / recommendedValues[2] * 100, - color: checkConsumedValues([recommendedValues[2]], [consumedValues[2]]) ? Colors.red : Colors.blue, + color: checkConsumedValues( + [recommendedValues[2]], [consumedValues[2]]) + ? Colors.red + : Colors.blue, ), ], ), @@ -854,7 +879,10 @@ class DiaryScreen extends StatelessWidget { barRods: [ BarChartRodData( toY: consumedValues[3] / recommendedValues[3] * 100, - color: checkConsumedValues([recommendedValues[3]], [consumedValues[3]]) ? Colors.red : Colors.blue, + color: checkConsumedValues( + [recommendedValues[3]], [consumedValues[3]]) + ? Colors.red + : Colors.blue, ), ], ), @@ -1045,7 +1073,9 @@ class DiaryScreen extends StatelessWidget { r"Подъем \ отход ко сну", style: CustomTextStyles.bodyMediumBlack900, ), - Icon(state.wakeupExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), + Icon(state.wakeupExpanded + ? Icons.arrow_drop_up + : Icons.arrow_drop_down), ], ), ), @@ -1059,7 +1089,8 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectWakeupTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: state.wakeupController?.format(context).toString(), + hintText: + state.wakeupController?.format(context).toString(), prefix: Icon(Icons.sunny), autofocus: false, ), @@ -1070,7 +1101,8 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectRetireTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: state.retireController?.format(context).toString(), + hintText: + state.retireController?.format(context).toString(), prefix: Icon(Icons.bed), autofocus: false, ), @@ -1117,7 +1149,8 @@ class DiaryScreen extends StatelessWidget { }; } - Function() sendFinishDayData(BuildContext dialogContext, BuildContext context) { + Function() sendFinishDayData( + BuildContext dialogContext, BuildContext context) { return () { closeDialog(dialogContext); context.read().add(FinishDay()); @@ -1160,7 +1193,9 @@ class DiaryScreen extends StatelessWidget { "Ваше настроение после приема пищи", style: CustomTextStyles.bodyMediumBlack900, ), - Icon(state.moodExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), + Icon(state.moodExpanded + ? Icons.arrow_drop_up + : Icons.arrow_drop_down), ], ), ), @@ -1220,7 +1255,8 @@ class DiaryScreen extends StatelessWidget { }; } - Future _selectWakeupTime(BuildContext context, DiaryStateLoaded state) async { + Future _selectWakeupTime( + BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.wakeupController ?? TimeOfDay.now(), @@ -1230,7 +1266,8 @@ class DiaryScreen extends StatelessWidget { } } - Future _selectRetireTime(BuildContext context, DiaryStateLoaded state) async { + Future _selectRetireTime( + BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.retireController ?? TimeOfDay.now(), @@ -1240,7 +1277,8 @@ class DiaryScreen extends StatelessWidget { } } - Future _selectMealTime(BuildContext context, DiaryStateLoaded state) async { + Future _selectMealTime( + BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.mealTimeController ?? TimeOfDay.now(), @@ -1251,7 +1289,8 @@ class DiaryScreen extends StatelessWidget { } } -bool checkConsumedValues(List recommendedValues, List consumedValues) { +bool checkConsumedValues( + List recommendedValues, List consumedValues) { for (int i = 0; i < recommendedValues.length; i++) { if (consumedValues[i] > recommendedValues[i]) { // Если хотя бы одно потребленное значение превышает рекомендованное diff --git a/lib/features/diary/repositories/diary_repository.dart b/lib/features/diary/repositories/diary_repository.dart index 12268fb..4bc13ae 100644 --- a/lib/features/diary/repositories/diary_repository.dart +++ b/lib/features/diary/repositories/diary_repository.dart @@ -1,4 +1,5 @@ import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:eatvio_app/features/diary/models/portion.dart'; import 'package:eatvio_app/features/diary/models/product.dart'; import 'package:eatvio_app/features/diary/services/diary_service.dart'; @@ -83,7 +84,7 @@ class DiaryRepository { } } - Future addPortion( + Future> addPortion( int diaryID, int mealID, String name, @@ -91,7 +92,8 @@ class DiaryRepository { int quantity, ) async { try { - await diaryService.sendPortionData( + print(name); + return await diaryService.sendPortionData( diaryID, mealID, name, @@ -109,6 +111,9 @@ class DiaryRepository { int portionID, ) async { try { + print(diaryID); + print(mealID); + print(portionID); await diaryService.sendRemovePortionData( diaryID, mealID, diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart index 3ec5a5b..f358d7c 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -1,5 +1,6 @@ import 'package:dio/dio.dart'; import 'package:eatvio_app/features/diary/models/diary_model.dart'; +import 'package:eatvio_app/features/diary/models/portion.dart'; import 'package:eatvio_app/features/diary/models/product.dart'; import 'package:retrofit/retrofit.dart'; @@ -49,7 +50,7 @@ abstract class DiaryService { ); @POST('/diary/{diary_id}/meal/{meal_id}/portions/create') - Future> sendPortionData( + Future> sendPortionData( @Path() int diary_id, @Path() int meal_id, @Query('product_name') String product_name, @@ -57,8 +58,8 @@ abstract class DiaryService { @Query('quantity') int quantity, ); - @POST('/diary/{diary_id}/meal/{meal_id}/portions/{portion_id}/delete') - Future> sendRemovePortionData( + @DELETE('/diary/{diary_id}/meal/{meal_id}/portions/{portion_id}/delete') + Future sendRemovePortionData( @Path() int diary_id, @Path() int meal_id, @Path() int portion_id, diff --git a/lib/features/diary/services/diary_service.g.dart b/lib/features/diary/services/diary_service.g.dart index 80461b5..50d9732 100644 --- a/lib/features/diary/services/diary_service.g.dart +++ b/lib/features/diary/services/diary_service.g.dart @@ -254,7 +254,7 @@ class _DiaryService implements DiaryService { } @override - Future> sendPortionData( + Future> sendPortionData( int diary_id, int meal_id, String product_name, @@ -269,8 +269,8 @@ class _DiaryService implements DiaryService { }; final _headers = {}; const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType>(Options( + final _result = await _dio.fetch>( + _setStreamType>(Options( method: 'POST', headers: _headers, extra: _extra, @@ -286,12 +286,13 @@ class _DiaryService implements DiaryService { _dio.options.baseUrl, baseUrl, )))); - final _value = _result.data!.cast(); + var _value = _result.data!.map((k, dynamic v) => + MapEntry(k, Portion.fromJson(v as Map))); return _value; } @override - Future> sendRemovePortionData( + Future sendRemovePortionData( int diary_id, int meal_id, int portion_id, @@ -300,25 +301,22 @@ class _DiaryService implements DiaryService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType>(Options( - method: 'POST', + await _dio.fetch(_setStreamType(Options( + method: 'DELETE', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/diary/${diary_id}/meal/${meal_id}/portions/${portion_id}/delete', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - final _value = _result.data!.cast(); - return _value; + .compose( + _dio.options, + '/diary/${diary_id}/meal/${meal_id}/portions/${portion_id}/delete', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); } RequestOptions _setStreamType(RequestOptions requestOptions) { -- 2.49.1 From 0671c5d07216e419993bc7fc1081b4272d83b910 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 24 Jul 2024 17:12:28 +0300 Subject: [PATCH 074/110] refactor(diary): API methods all refactored and new nutrition charty finished --- lib/features/diary/models/photo.dart | 3 +- lib/features/diary/models/photo.freezed.dart | 62 +-- lib/features/diary/models/photo.g.dart | 6 +- .../diary/presentation/bloc/diary_bloc.dart | 431 ++++++------------ .../diary/presentation/bloc/diary_state.dart | 11 +- .../bloc/diary_state.freezed.dart | 128 +++--- .../presentation/pages/diary_screen.dart | 71 ++- .../diary/repositories/diary_repository.dart | 94 +++- .../diary/services/diary_service.dart | 36 +- .../diary/services/diary_service.g.dart | 168 ++++++- pubspec.yaml | 1 + 11 files changed, 568 insertions(+), 443 deletions(-) diff --git a/lib/features/diary/models/photo.dart b/lib/features/diary/models/photo.dart index f057ec5..eef9e8f 100644 --- a/lib/features/diary/models/photo.dart +++ b/lib/features/diary/models/photo.dart @@ -7,9 +7,8 @@ part 'photo.g.dart'; class Photo with _$Photo { const factory Photo({ required int id, - required String originalName, + required String original_name, required String path, - required int size, }) = _Photo; factory Photo.fromJson(Map json) => _$PhotoFromJson(json); diff --git a/lib/features/diary/models/photo.freezed.dart b/lib/features/diary/models/photo.freezed.dart index 6b4520b..d922286 100644 --- a/lib/features/diary/models/photo.freezed.dart +++ b/lib/features/diary/models/photo.freezed.dart @@ -21,9 +21,8 @@ Photo _$PhotoFromJson(Map json) { /// @nodoc mixin _$Photo { int get id => throw _privateConstructorUsedError; - String get originalName => throw _privateConstructorUsedError; + String get original_name => throw _privateConstructorUsedError; String get path => throw _privateConstructorUsedError; - int get size => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -35,7 +34,7 @@ abstract class $PhotoCopyWith<$Res> { factory $PhotoCopyWith(Photo value, $Res Function(Photo) then) = _$PhotoCopyWithImpl<$Res, Photo>; @useResult - $Res call({int id, String originalName, String path, int size}); + $Res call({int id, String original_name, String path}); } /// @nodoc @@ -52,27 +51,22 @@ class _$PhotoCopyWithImpl<$Res, $Val extends Photo> @override $Res call({ Object? id = null, - Object? originalName = null, + Object? original_name = null, Object? path = null, - Object? size = null, }) { return _then(_value.copyWith( id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable as int, - originalName: null == originalName - ? _value.originalName - : originalName // ignore: cast_nullable_to_non_nullable + original_name: null == original_name + ? _value.original_name + : original_name // ignore: cast_nullable_to_non_nullable as String, path: null == path ? _value.path : path // ignore: cast_nullable_to_non_nullable as String, - size: null == size - ? _value.size - : size // ignore: cast_nullable_to_non_nullable - as int, ) as $Val); } } @@ -84,7 +78,7 @@ abstract class _$$PhotoImplCopyWith<$Res> implements $PhotoCopyWith<$Res> { __$$PhotoImplCopyWithImpl<$Res>; @override @useResult - $Res call({int id, String originalName, String path, int size}); + $Res call({int id, String original_name, String path}); } /// @nodoc @@ -99,27 +93,22 @@ class __$$PhotoImplCopyWithImpl<$Res> @override $Res call({ Object? id = null, - Object? originalName = null, + Object? original_name = null, Object? path = null, - Object? size = null, }) { return _then(_$PhotoImpl( id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable as int, - originalName: null == originalName - ? _value.originalName - : originalName // ignore: cast_nullable_to_non_nullable + original_name: null == original_name + ? _value.original_name + : original_name // ignore: cast_nullable_to_non_nullable as String, path: null == path ? _value.path : path // ignore: cast_nullable_to_non_nullable as String, - size: null == size - ? _value.size - : size // ignore: cast_nullable_to_non_nullable - as int, )); } } @@ -128,10 +117,7 @@ class __$$PhotoImplCopyWithImpl<$Res> @JsonSerializable() class _$PhotoImpl implements _Photo { const _$PhotoImpl( - {required this.id, - required this.originalName, - required this.path, - required this.size}); + {required this.id, required this.original_name, required this.path}); factory _$PhotoImpl.fromJson(Map json) => _$$PhotoImplFromJson(json); @@ -139,15 +125,13 @@ class _$PhotoImpl implements _Photo { @override final int id; @override - final String originalName; + final String original_name; @override final String path; - @override - final int size; @override String toString() { - return 'Photo(id: $id, originalName: $originalName, path: $path, size: $size)'; + return 'Photo(id: $id, original_name: $original_name, path: $path)'; } @override @@ -156,15 +140,14 @@ class _$PhotoImpl implements _Photo { (other.runtimeType == runtimeType && other is _$PhotoImpl && (identical(other.id, id) || other.id == id) && - (identical(other.originalName, originalName) || - other.originalName == originalName) && - (identical(other.path, path) || other.path == path) && - (identical(other.size, size) || other.size == size)); + (identical(other.original_name, original_name) || + other.original_name == original_name) && + (identical(other.path, path) || other.path == path)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, originalName, path, size); + int get hashCode => Object.hash(runtimeType, id, original_name, path); @JsonKey(ignore: true) @override @@ -183,21 +166,18 @@ class _$PhotoImpl implements _Photo { abstract class _Photo implements Photo { const factory _Photo( {required final int id, - required final String originalName, - required final String path, - required final int size}) = _$PhotoImpl; + required final String original_name, + required final String path}) = _$PhotoImpl; factory _Photo.fromJson(Map json) = _$PhotoImpl.fromJson; @override int get id; @override - String get originalName; + String get original_name; @override String get path; @override - int get size; - @override @JsonKey(ignore: true) _$$PhotoImplCopyWith<_$PhotoImpl> get copyWith => throw _privateConstructorUsedError; diff --git a/lib/features/diary/models/photo.g.dart b/lib/features/diary/models/photo.g.dart index 9b212a8..8cd7bcc 100644 --- a/lib/features/diary/models/photo.g.dart +++ b/lib/features/diary/models/photo.g.dart @@ -8,15 +8,13 @@ part of 'photo.dart'; _$PhotoImpl _$$PhotoImplFromJson(Map json) => _$PhotoImpl( id: (json['id'] as num).toInt(), - originalName: json['originalName'] as String, + original_name: json['original_name'] as String, path: json['path'] as String, - size: (json['size'] as num).toInt(), ); Map _$$PhotoImplToJson(_$PhotoImpl instance) => { 'id': instance.id, - 'originalName': instance.originalName, + 'original_name': instance.original_name, 'path': instance.path, - 'size': instance.size, }; diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index 37abfdc..a54ed15 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -38,7 +38,6 @@ class DiaryBloc extends Bloc { _removeImage, ); // пользователь нажимает на крестик около продукта on(_uploadImages); //пользователь нажимает "Добавить фото" - on(_addComment); //пользователь нажимает "Добавить комментарий" on( _inputProduct, ); @@ -57,13 +56,50 @@ class DiaryBloc extends Bloc { emit(const DiaryState.loading()); try { Map data = await diaryRepository.getDiaryID(); + final int? diaryID = data['id']; final DiaryModel diary = await diaryRepository.getDiary(diaryID ?? 45); final Meal currentMeal = diary.meals[0]; + List portionList = [ SelectionPopupModel(title: "gr"), SelectionPopupModel(title: "pcs") ]; + + final Map chartData = + await diaryRepository.getChartData(diaryID ?? 45); + final Map dailyNutritionIntake = + chartData['dailyNutritionIntake']!; + final Map dailyNutritionRecommendations = + chartData['dailyNutritionRecommendation']!; + final double ccal = dailyNutritionIntake['energy']! / + dailyNutritionRecommendations['energy']! * + 100; + final double proteins = dailyNutritionIntake['proteins']! / + dailyNutritionRecommendations['proteins']! * + 100; + final double fats = dailyNutritionIntake['fats']! / + dailyNutritionRecommendations['fats']! * + 100; + final double carbs = dailyNutritionIntake['carbohydrates']! / + dailyNutritionRecommendations['carbohydrates']! * + 100; + + Color getColor(double value) { + if (value >= 99.1) { + return Colors.red; + } else { + return Colors.blue; + } + } + + final List chartDataCounted = [ + NutritionData('Калории', ccal, getColor(ccal)), + NutritionData('Белки', proteins, getColor(proteins)), + NutritionData('Жиры', fats, getColor(fats)), + NutritionData('Углеводы', carbs, getColor(carbs)), + ]; + List mealList = [ SelectionPopupModel(title: "Прием пищи 1", id: 1), SelectionPopupModel(title: "Прием пищи 2", id: 2), @@ -72,14 +108,17 @@ class DiaryBloc extends Bloc { SelectionPopupModel(title: "Прием пищи 5", id: 5), SelectionPopupModel(title: "Прием пищи 6", id: 6), ]; + + print(dailyNutritionRecommendations); + print(dailyNutritionIntake); emit(DiaryState.loaded( diary: diary, currentMeal: currentMeal, portions: currentMeal.portions, - photos: currentMeal.photos, portionList: portionList, portionController: portionList[0], mealList: mealList, + chartData: chartDataCounted, selectedMood: currentMeal.mood, selectedSatiety: currentMeal.satiety, commentController: TextEditingController(), @@ -119,7 +158,7 @@ class DiaryBloc extends Bloc { if (responseChart.statusCode == 200) { final responseBody = jsonDecode(responseChart.body); - + print(responseBody); final recommendedChartValues = responseBody['dailyNutritionRecommendation'] .values @@ -131,13 +170,22 @@ class DiaryBloc extends Bloc { .map((value) => convertToInt(value)) .toList(); - print([recommendedChartValues, consumedChartValues]); - return [recommendedChartValues, consumedChartValues]; + print([ + recommendedChartValues, + consumedChartValues, + ]); + return [ + recommendedChartValues, + consumedChartValues, + ]; } else { emit(DiaryStateError( errorMessage: 'Ошибка при декодировании данных КБЖУ')); print('fail'); - return [[], []]; // Return empty lists instead of -1 + return [ + [], + [], + ]; } } @@ -162,10 +210,14 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = - currentState.copyWith(selectedSatiety: event.selectedElement); - diaryRepository.changeSatiety(event.selectedElement, - currentState.currentMeal.id, currentState.diary.id); + var updatedState = currentState.copyWith( + selectedSatiety: event.selectedElement, + ); + diaryRepository.changeSatiety( + event.selectedElement, + currentState.currentMeal.id, + currentState.diary.id, + ); emit(updatedState); } } @@ -176,11 +228,15 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = - currentState.copyWith(selectedMood: event.selectedElement); + var updatedState = currentState.copyWith( + selectedMood: event.selectedElement, + ); - diaryRepository.changeMood(event.selectedElement, - currentState.currentMeal.id, currentState.diary.id); + diaryRepository.changeMood( + event.selectedElement, + currentState.currentMeal.id, + currentState.diary.id, + ); emit(updatedState); // Передаем обновленное состояние в emit } @@ -246,7 +302,6 @@ class DiaryBloc extends Bloc { DiaryStateLoaded updatedState = currentState.copyWith( currentMeal: meal, portions: meal.portions, - photos: meal.photos, mealTimeController: toTime(meal.time), selectedMood: meal.mood, selectedSatiety: meal.satiety, @@ -279,6 +334,76 @@ class DiaryBloc extends Bloc { } } + FutureOr _addPortion( + AddPortionEvent event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + + Map data = await diaryRepository.addPortion( + currentState.diary.id, + currentState.currentMeal.id, + currentState.product_nameController.text, + currentState.portionController.title, + int.parse(currentState.productQuantityController.text), + ); + List newPortions = currentState.portions; + + final Portion newPortion = data['portion'] ?? + new Portion(id: 1, portion: 'gr', product_name: '1', quantity: 1); + newPortions.add(newPortion); + emit(currentState.copyWith(isAdded: true, portions: newPortions)); + //TODO update screen after addPortion() call + } + } + + Future _removePortion( + RemovePortionEvent event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + await diaryRepository.removePortion( + currentState.diary.id, + currentState.currentMeal.id, + event.portionId, + ); + } + //TODO update screen after _removePortion() call + } + + Future _uploadImages( + UploadImages event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + var currentState = state as DiaryStateLoaded; + + emit(currentState.copyWith(isLoading: true)); + await diaryRepository.uploadImage( + event.image.path, + currentState.diary.id, + currentState.currentMeal.id, + ); + } + } + + FutureOr _sendModeration( + SendModeration event, + Emitter emit, + ) async { + if (state is DiaryStateLoaded) { + await diaryRepository.sendModeration( + event.name, + event.energyOn100gr, + event.proteinsOn100gr, + event.fatsOn100gr, + event.carbohydratesOn100gr, + ); + } + } + FutureOr _clearInput( ClearInput event, Emitter emit, @@ -325,48 +450,6 @@ class DiaryBloc extends Bloc { } } - FutureOr _addPortion( - AddPortionEvent event, - Emitter emit, - ) async { - if (state is DiaryStateLoaded) { - var currentState = state as DiaryStateLoaded; - print(currentState.diary.id); - print(currentState.currentMeal.id); - print(currentState.product_nameController.text); - print(currentState.portionController.title); - print(currentState.productQuantityController.text); - - Map data = await diaryRepository.addPortion( - currentState.diary.id, - currentState.currentMeal.id, - currentState.product_nameController.text, - currentState.portionController.title, - int.parse(currentState.productQuantityController.text), - ); - List newPortions = currentState.portions; - - final Portion newPortion = data['portion'] ?? - new Portion(id: 1, portion: 'gr', product_name: '1', quantity: 1); - newPortions.add(newPortion); - emit(currentState.copyWith(isAdded: true, portions: newPortions)); - } - } - - Future _removePortion( - RemovePortionEvent event, - Emitter emit, - ) async { - if (state is DiaryStateLoaded) { - var currentState = state as DiaryStateLoaded; - await diaryRepository.removePortion( - currentState.diary.id, - currentState.currentMeal.id, - event.portionId, - ); - } - } - FutureOr _removeImage( RemoveImageEvent event, Emitter emit, @@ -374,244 +457,28 @@ class DiaryBloc extends Bloc { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var response = await sendRemovePhoto( - event.path, - event.photoID, - currentState.currentMeal.id, + await diaryRepository.removeImage( currentState.diary.id, + currentState.currentMeal.id, + int.parse(event.photoID), + event.path, ); - print(response.statusCode); - if (response.statusCode == 204) { - await reloadScreen(event, emit); - } else { - print( - 'Failed to remove photo. Status Code: ${response.statusCode} ${response.body}', - ); - } } } - Future sendRemovePhoto( - String? path, - String? photoID, - int? mealID, - int diaryID, - ) async { - String url = - '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete'; - final Map credentials = { - 'id': photoID, - 'path': path, - }; - var response = await http.delete( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - Future _finishDay(FinishDay event, Emitter emit) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var response = await sendFinishDay( + await diaryRepository.finishDay( currentState.diary.id, currentState.wakeupController, currentState.retireController, currentState.commentController.text, ); - - if (response.statusCode == 200) { - await reloadScreen(event, emit); - } } } - Future sendFinishDay( - int diaryID, - TimeOfDay? wakeup, - TimeOfDay? retire, - String? comment, - ) async { - final formatter = DateFormat('HH:mm'); - final wakeupString = - formatter.format(DateTime(2022, 1, 1, wakeup!.hour, wakeup.minute)); - final retireString = - formatter.format(DateTime(2022, 1, 1, retire!.hour, retire.minute)); - - final Map credentials = { - 'wakeup': wakeupString, - 'retire': retireString, - 'comment': comment ?? " ", - }; - - String url = '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/finishDay'; - - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - - Future _uploadImages( - UploadImages event, - Emitter emit, - ) async { - if (state is DiaryStateLoaded) { - var currentState = state as DiaryStateLoaded; - - emit(currentState.copyWith(isLoading: true)); - await uploadImageToServer( - event.image.path, - currentState.diary.id, - currentState.currentMeal.id, - ); - await reloadScreen(event, emit); - } - } - - Future uploadImageToServer( - String imagePath, - int diaryID, - int mealId, - ) async { - String url = - '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload'; - - var request = http.MultipartRequest('POST', Uri.parse(url)); - - request.files.add(await http.MultipartFile.fromPath('photo', imagePath)); - - var client = http.Client(); - var streamedResponse = await client.send(request); - - if (streamedResponse.statusCode == 200) { - var response = await http.Response.fromStream(streamedResponse); - var imageUrl = response.body; - print('Image successfully uploaded'); - return imageUrl; - } else { - throw Exception( - 'Failed to upload image. Status code: ${streamedResponse.statusCode}}', - ); - } - } - - FutureOr _sendModeration( - SendModeration event, - Emitter emit, - ) async { - if (state is DiaryStateLoaded) { - final response = await _sendModerationData( - event.name, - event.energyOn100gr, - event.proteinsOn100gr, - event.fatsOn100gr, - event.carbohydratesOn100gr, - ); - - if (response.statusCode == 200) - print("Moderation success"); - else - print("Moderation error"); - } - } - - Future _sendModerationData( - String name, - String energy_on_100gr, - String proteins_on_100gr, - String fats_on_100gr, - String carbohydrates_on_100gr, - ) async { - final Uri url = Uri.parse( - '${dotenv.env['SERVER_ROOT']!}/diary/product_nutritional_values/sendToModeration', - ); - final Uri serverURL = Uri.parse('${dotenv.env['SERVER_ROOT']!}'); - String host = serverURL.host; - final Map credentials = { - 'name': name, - 'energy_on_100gr': energy_on_100gr, - 'proteins_on_100gr': proteins_on_100gr, - 'fats_on_100gr': fats_on_100gr, - 'carbohydrates_on_100gr': carbohydrates_on_100gr, - }; - - var headers = { - //'Content-Length': bodyBytes, - 'Host': host, - }; - - var response = await http.post( - url, - headers: headers, - body: credentials, - encoding: utf8, - ); - - if (response.statusCode == 200) { - return response; - } else { - throw Exception( - 'Failed to send a product for moderation ${response.statusCode}', - ); - } - } - - FutureOr _addComment( - AddComment event, - Emitter emit, - ) async { - if (state is DiaryStateLoaded) { - var currentState = state as DiaryStateLoaded; - var updatedState = currentState.copyWith( - commentController: TextEditingController(text: event.comment), - ); - - // Отправляем данные по HTTP маршруту и ждем ответ - var response = await sendCommentData( - event.comment, - currentState.diary.id, - ); - - if (response.statusCode == 200) { - emit(updatedState); // Передаем обновленное состояние в emit - } - } - } - - Future sendCommentData( - String comment, - int diaryID, - ) async { - String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill'; - final Map credentials = { - 'comment': comment, - }; - - var response = await http.post( - Uri.parse(url), - headers: { - 'Content-Type': 'application/json', - }, - body: json.encode(credentials), - encoding: utf8, - ); - - return response; - } - TimeOfDay toTime(String timeStr) { List timeParts = timeStr.split(":"); int hour = int.parse(timeParts[0]); @@ -621,14 +488,6 @@ class DiaryBloc extends Bloc { return timeOfDay; } - List fillMealList(List meals) { - meals.sort(compareTypes); - return meals.map((meal) { - String title = "Прием пищи ${meal['type']}"; - return SelectionPopupModel(id: meal['id'], title: title); - }).toList(); - } - int compareTypes(a, b) { return a['type'].compareTo(b['type']); } diff --git a/lib/features/diary/presentation/bloc/diary_state.dart b/lib/features/diary/presentation/bloc/diary_state.dart index 57b3768..6feb5f1 100644 --- a/lib/features/diary/presentation/bloc/diary_state.dart +++ b/lib/features/diary/presentation/bloc/diary_state.dart @@ -1,6 +1,5 @@ import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:eatvio_app/features/diary/models/meal.dart'; -import 'package:eatvio_app/features/diary/models/photo.dart'; import 'package:eatvio_app/features/diary/models/portion.dart'; import 'package:eatvio_app/features/diary/models/product.dart'; import 'package:flutter/material.dart'; @@ -22,7 +21,6 @@ abstract class DiaryState with _$DiaryState { required List recommendedChartValues, required List consumedChartValues, required List portions, - required List photos, required List mealList, required List portionList, required List autocompleteList, @@ -45,9 +43,18 @@ abstract class DiaryState with _$DiaryState { required bool moodExpanded, required bool isLoading, required bool isAdded, + List? chartData, }) = DiaryStateLoaded; const factory DiaryState.error({ required String errorMessage, }) = DiaryStateError; } + +class NutritionData { + NutritionData(this.category, this.nutrition, this.color); + + final String category; + final double nutrition; + final Color color; +} diff --git a/lib/features/diary/presentation/bloc/diary_state.freezed.dart b/lib/features/diary/presentation/bloc/diary_state.freezed.dart index 981a027..deda872 100644 --- a/lib/features/diary/presentation/bloc/diary_state.freezed.dart +++ b/lib/features/diary/presentation/bloc/diary_state.freezed.dart @@ -26,7 +26,6 @@ mixin _$DiaryState { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -48,7 +47,8 @@ mixin _$DiaryState { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded) + bool isAdded, + List? chartData) loaded, required TResult Function(String errorMessage) error, }) => @@ -63,7 +63,6 @@ mixin _$DiaryState { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -85,7 +84,8 @@ mixin _$DiaryState { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded)? + bool isAdded, + List? chartData)? loaded, TResult? Function(String errorMessage)? error, }) => @@ -100,7 +100,6 @@ mixin _$DiaryState { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -122,7 +121,8 @@ mixin _$DiaryState { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded)? + bool isAdded, + List? chartData)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), @@ -219,7 +219,6 @@ class _$DiaryStateImpl implements _DiaryState { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -241,7 +240,8 @@ class _$DiaryStateImpl implements _DiaryState { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded) + bool isAdded, + List? chartData) loaded, required TResult Function(String errorMessage) error, }) { @@ -259,7 +259,6 @@ class _$DiaryStateImpl implements _DiaryState { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -281,7 +280,8 @@ class _$DiaryStateImpl implements _DiaryState { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded)? + bool isAdded, + List? chartData)? loaded, TResult? Function(String errorMessage)? error, }) { @@ -299,7 +299,6 @@ class _$DiaryStateImpl implements _DiaryState { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -321,7 +320,8 @@ class _$DiaryStateImpl implements _DiaryState { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded)? + bool isAdded, + List? chartData)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), @@ -420,7 +420,6 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -442,7 +441,8 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded) + bool isAdded, + List? chartData) loaded, required TResult Function(String errorMessage) error, }) { @@ -460,7 +460,6 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -482,7 +481,8 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded)? + bool isAdded, + List? chartData)? loaded, TResult? Function(String errorMessage)? error, }) { @@ -500,7 +500,6 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -522,7 +521,8 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded)? + bool isAdded, + List? chartData)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), @@ -587,7 +587,6 @@ abstract class _$$DiaryStateLoadedImplCopyWith<$Res> { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -609,7 +608,8 @@ abstract class _$$DiaryStateLoadedImplCopyWith<$Res> { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded}); + bool isAdded, + List? chartData}); $DiaryModelCopyWith<$Res> get diary; $MealCopyWith<$Res> get currentMeal; @@ -631,7 +631,6 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> Object? recommendedChartValues = null, Object? consumedChartValues = null, Object? portions = null, - Object? photos = null, Object? mealList = null, Object? portionList = null, Object? autocompleteList = null, @@ -654,6 +653,7 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> Object? moodExpanded = null, Object? isLoading = null, Object? isAdded = null, + Object? chartData = freezed, }) { return _then(_$DiaryStateLoadedImpl( diary: null == diary @@ -676,10 +676,6 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> ? _value._portions : portions // ignore: cast_nullable_to_non_nullable as List, - photos: null == photos - ? _value._photos - : photos // ignore: cast_nullable_to_non_nullable - as List, mealList: null == mealList ? _value._mealList : mealList // ignore: cast_nullable_to_non_nullable @@ -768,6 +764,10 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> ? _value.isAdded : isAdded // ignore: cast_nullable_to_non_nullable as bool, + chartData: freezed == chartData + ? _value._chartData + : chartData // ignore: cast_nullable_to_non_nullable + as List?, )); } @@ -797,7 +797,6 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { required final List recommendedChartValues, required final List consumedChartValues, required final List portions, - required final List photos, required final List mealList, required final List portionList, required final List autocompleteList, @@ -819,14 +818,15 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { required this.moderationExpanded, required this.moodExpanded, required this.isLoading, - required this.isAdded}) + required this.isAdded, + final List? chartData}) : _recommendedChartValues = recommendedChartValues, _consumedChartValues = consumedChartValues, _portions = portions, - _photos = photos, _mealList = mealList, _portionList = portionList, - _autocompleteList = autocompleteList; + _autocompleteList = autocompleteList, + _chartData = chartData; @override final DiaryModel diary; @@ -858,14 +858,6 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { return EqualUnmodifiableListView(_portions); } - final List _photos; - @override - List get photos { - if (_photos is EqualUnmodifiableListView) return _photos; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_photos); - } - final List _mealList; @override List get mealList { @@ -929,10 +921,19 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { final bool isLoading; @override final bool isAdded; + final List? _chartData; + @override + List? get chartData { + final value = _chartData; + if (value == null) return null; + if (_chartData is EqualUnmodifiableListView) return _chartData; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } @override String toString() { - return 'DiaryState.loaded(diary: $diary, diaryDate: $diaryDate, recommendedChartValues: $recommendedChartValues, consumedChartValues: $consumedChartValues, portions: $portions, photos: $photos, mealList: $mealList, portionList: $portionList, autocompleteList: $autocompleteList, currentMeal: $currentMeal, portionController: $portionController, wakeupController: $wakeupController, retireController: $retireController, mealTimeController: $mealTimeController, commentController: $commentController, product_nameController: $product_nameController, productQuantityController: $productQuantityController, caloriesController: $caloriesController, fatsController: $fatsController, proteinsController: $proteinsController, carbsController: $carbsController, selectedMood: $selectedMood, selectedSatiety: $selectedSatiety, wakeupExpanded: $wakeupExpanded, moderationExpanded: $moderationExpanded, moodExpanded: $moodExpanded, isLoading: $isLoading, isAdded: $isAdded)'; + return 'DiaryState.loaded(diary: $diary, diaryDate: $diaryDate, recommendedChartValues: $recommendedChartValues, consumedChartValues: $consumedChartValues, portions: $portions, mealList: $mealList, portionList: $portionList, autocompleteList: $autocompleteList, currentMeal: $currentMeal, portionController: $portionController, wakeupController: $wakeupController, retireController: $retireController, mealTimeController: $mealTimeController, commentController: $commentController, product_nameController: $product_nameController, productQuantityController: $productQuantityController, caloriesController: $caloriesController, fatsController: $fatsController, proteinsController: $proteinsController, carbsController: $carbsController, selectedMood: $selectedMood, selectedSatiety: $selectedSatiety, wakeupExpanded: $wakeupExpanded, moderationExpanded: $moderationExpanded, moodExpanded: $moodExpanded, isLoading: $isLoading, isAdded: $isAdded, chartData: $chartData)'; } @override @@ -948,7 +949,6 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { const DeepCollectionEquality() .equals(other._consumedChartValues, _consumedChartValues) && const DeepCollectionEquality().equals(other._portions, _portions) && - const DeepCollectionEquality().equals(other._photos, _photos) && const DeepCollectionEquality().equals(other._mealList, _mealList) && const DeepCollectionEquality() .equals(other._portionList, _portionList) && @@ -991,7 +991,9 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { other.moodExpanded == moodExpanded) && (identical(other.isLoading, isLoading) || other.isLoading == isLoading) && - (identical(other.isAdded, isAdded) || other.isAdded == isAdded)); + (identical(other.isAdded, isAdded) || other.isAdded == isAdded) && + const DeepCollectionEquality() + .equals(other._chartData, _chartData)); } @override @@ -1002,7 +1004,6 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { const DeepCollectionEquality().hash(_recommendedChartValues), const DeepCollectionEquality().hash(_consumedChartValues), const DeepCollectionEquality().hash(_portions), - const DeepCollectionEquality().hash(_photos), const DeepCollectionEquality().hash(_mealList), const DeepCollectionEquality().hash(_portionList), const DeepCollectionEquality().hash(_autocompleteList), @@ -1024,7 +1025,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { moderationExpanded, moodExpanded, isLoading, - isAdded + isAdded, + const DeepCollectionEquality().hash(_chartData) ]); @JsonKey(ignore: true) @@ -1045,7 +1047,6 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -1067,7 +1068,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded) + bool isAdded, + List? chartData) loaded, required TResult Function(String errorMessage) error, }) { @@ -1077,7 +1079,6 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { recommendedChartValues, consumedChartValues, portions, - photos, mealList, portionList, autocompleteList, @@ -1099,7 +1100,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { moderationExpanded, moodExpanded, isLoading, - isAdded); + isAdded, + chartData); } @override @@ -1113,7 +1115,6 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -1135,7 +1136,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded)? + bool isAdded, + List? chartData)? loaded, TResult? Function(String errorMessage)? error, }) { @@ -1145,7 +1147,6 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { recommendedChartValues, consumedChartValues, portions, - photos, mealList, portionList, autocompleteList, @@ -1167,7 +1168,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { moderationExpanded, moodExpanded, isLoading, - isAdded); + isAdded, + chartData); } @override @@ -1181,7 +1183,6 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -1203,7 +1204,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded)? + bool isAdded, + List? chartData)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), @@ -1215,7 +1217,6 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { recommendedChartValues, consumedChartValues, portions, - photos, mealList, portionList, autocompleteList, @@ -1237,7 +1238,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { moderationExpanded, moodExpanded, isLoading, - isAdded); + isAdded, + chartData); } return orElse(); } @@ -1287,7 +1289,6 @@ abstract class DiaryStateLoaded implements DiaryState { required final List recommendedChartValues, required final List consumedChartValues, required final List portions, - required final List photos, required final List mealList, required final List portionList, required final List autocompleteList, @@ -1309,14 +1310,14 @@ abstract class DiaryStateLoaded implements DiaryState { required final bool moderationExpanded, required final bool moodExpanded, required final bool isLoading, - required final bool isAdded}) = _$DiaryStateLoadedImpl; + required final bool isAdded, + final List? chartData}) = _$DiaryStateLoadedImpl; DiaryModel get diary; String? get diaryDate; List get recommendedChartValues; List get consumedChartValues; List get portions; - List get photos; List get mealList; List get portionList; List get autocompleteList; @@ -1339,6 +1340,7 @@ abstract class DiaryStateLoaded implements DiaryState { bool get moodExpanded; bool get isLoading; bool get isAdded; + List? get chartData; @JsonKey(ignore: true) _$$DiaryStateLoadedImplCopyWith<_$DiaryStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; @@ -1418,7 +1420,6 @@ class _$DiaryStateErrorImpl implements DiaryStateError { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -1440,7 +1441,8 @@ class _$DiaryStateErrorImpl implements DiaryStateError { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded) + bool isAdded, + List? chartData) loaded, required TResult Function(String errorMessage) error, }) { @@ -1458,7 +1460,6 @@ class _$DiaryStateErrorImpl implements DiaryStateError { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -1480,7 +1481,8 @@ class _$DiaryStateErrorImpl implements DiaryStateError { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded)? + bool isAdded, + List? chartData)? loaded, TResult? Function(String errorMessage)? error, }) { @@ -1498,7 +1500,6 @@ class _$DiaryStateErrorImpl implements DiaryStateError { List recommendedChartValues, List consumedChartValues, List portions, - List photos, List mealList, List portionList, List autocompleteList, @@ -1520,7 +1521,8 @@ class _$DiaryStateErrorImpl implements DiaryStateError { bool moderationExpanded, bool moodExpanded, bool isLoading, - bool isAdded)? + bool isAdded, + List? chartData)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index 5603abb..53937a9 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -7,20 +7,20 @@ import 'package:eatvio_app/features/diary/models/portion.dart'; import 'package:eatvio_app/features/diary/models/product.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; -import 'package:flutter/cupertino.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:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:image_picker/image_picker.dart'; import 'package:carousel_slider/carousel_slider.dart'; +import 'package:syncfusion_flutter_charts/charts.dart'; // ignore: must_be_immutable class DiaryScreen extends StatelessWidget { @@ -89,7 +89,7 @@ class DiaryScreen extends StatelessWidget { _buildMeal(context, state), SizedBox(height: 20.v), _buildMood(context, state), - SizedBox(height: 30.v), + SizedBox(height: 20.v), _buildNutritionChart(context, state), SizedBox(height: 30.v), _buildComment(context, state), @@ -109,6 +109,39 @@ class DiaryScreen extends StatelessWidget { ); } + _buildNutritionChart(BuildContext context, DiaryStateLoaded state) { + return Container( + margin: EdgeInsets.symmetric(horizontal: 16.h, vertical: 16.h), + padding: EdgeInsets.symmetric( + horizontal: 24.h, + vertical: 12.v, + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.all(Radius.circular(12)), + boxShadow: [ + BoxShadow( + color: Colors.grey.withOpacity(0.5), + spreadRadius: 2, + blurRadius: 5, + offset: Offset(0, 3), + ), + ], + ), + child: SfCircularChart( + title: ChartTitle(text: 'График КБЖУ'), + legend: Legend(isVisible: true), + series: [ + RadialBarSeries( + dataSource: state.chartData, + xValueMapper: (NutritionData data, _) => data.category, + yValueMapper: (NutritionData data, _) => data.nutrition, + pointColorMapper: (NutritionData data, _) => data.color, + ) + ], + )); + } + _buildEndDay(BuildContext context) { return CustomOutlinedButton( text: "Закончить день", @@ -122,7 +155,6 @@ class DiaryScreen extends StatelessWidget { color: Colors.transparent, ), onPressed: onFinishDayPressed(context), - // Установите прозрачный фон ); } @@ -217,8 +249,6 @@ class DiaryScreen extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: [ - // Показывайте прелоадер, если загрузка активна - Padding( padding: EdgeInsets.only( left: 7.h, @@ -461,13 +491,6 @@ class DiaryScreen extends StatelessWidget { .map((portion) => _buildProduct(context, portion)) .toList(), SizedBox(height: 30.v), - /*...state.photos != null - ? state.photos!.isEmpty - ? [Text('Фото пока нет')] - : state.photos! - .map((photo) => _buildPhoto(context, photo)) - .toList() - : [Text('Фото нет')],*/ _buildCarousel(context, state), SizedBox(height: 20.v), _buildAddPhoto(context, state), @@ -600,7 +623,6 @@ class DiaryScreen extends StatelessWidget { BuildContext dialogContext, ) { return () { - // Call function to send moderation with the entered values context.read().add( SendModeration( name: name, @@ -610,7 +632,7 @@ class DiaryScreen extends StatelessWidget { carbohydratesOn100gr: carbohydratesOn100gr, ), ); - Navigator.of(dialogContext).pop(); // Dismiss the dialog + Navigator.of(dialogContext).pop(); }; } @@ -670,8 +692,7 @@ class DiaryScreen extends StatelessWidget { return CarouselSlider( options: CarouselOptions(height: 340.0), items: state.currentMeal.photos.map((photo) { - return _buildPhoto( - context, photo); // Assuming photos are stored as strings + return _buildPhoto(context, photo); }).toList(), ); } @@ -777,7 +798,7 @@ class DiaryScreen extends StatelessWidget { }; } - _buildNutritionChart(BuildContext context, DiaryStateLoaded state) { + /*_buildNutritionChart(BuildContext context, DiaryStateLoaded state) { final List recommendedValues = state .recommendedChartValues; // Рекомендуемые значения: калории, жиры, белки, углеводы final List consumedValues = state.consumedChartValues; // @@ -996,7 +1017,7 @@ class DiaryScreen extends StatelessWidget { ], ), ); - } + }*/ /// Section Widget _buildComment(BuildContext context, DiaryStateLoaded state) { diff --git a/lib/features/diary/repositories/diary_repository.dart b/lib/features/diary/repositories/diary_repository.dart index 4bc13ae..56c9fbd 100644 --- a/lib/features/diary/repositories/diary_repository.dart +++ b/lib/features/diary/repositories/diary_repository.dart @@ -1,3 +1,7 @@ +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:eatvio_app/features/diary/models/portion.dart'; import 'package:eatvio_app/features/diary/models/product.dart'; @@ -24,6 +28,14 @@ class DiaryRepository { } } + Future> getChartData(int diaryID) async { + try { + return (await diaryService.getChart(diaryID)); + } catch (e) { + rethrow; + } + } + Future>> inputProduct(String name) async { try { return await diaryService.getInputProduct(name); @@ -92,7 +104,6 @@ class DiaryRepository { int quantity, ) async { try { - print(name); return await diaryService.sendPortionData( diaryID, mealID, @@ -105,15 +116,32 @@ class DiaryRepository { } } + Future> sendModeration( + String name, + String energy_on_100gr, + String proteins_on_100gr, + String fats_on_100gr, + String carbohydrates_on_100gr, + ) async { + try { + return await diaryService.sendModerationData( + name, + double.parse(energy_on_100gr + ".0"), + double.parse(proteins_on_100gr + ".0"), + double.parse(fats_on_100gr + ".0"), + double.parse(carbohydrates_on_100gr + ".0"), + ); + } catch (e) { + rethrow; + } + } + Future removePortion( int diaryID, int mealID, int portionID, ) async { try { - print(diaryID); - print(mealID); - print(portionID); await diaryService.sendRemovePortionData( diaryID, mealID, @@ -123,4 +151,62 @@ class DiaryRepository { rethrow; } } + + Future uploadImage( + String path, + int diaryID, + int mealID, + ) async { + try { + File file = File(path); + await diaryService.uploadImage( + diaryID, + mealID, + file, + ); + } catch (e) { + rethrow; + } + } + + Future removeImage( + int diaryID, + int mealID, + int photoID, + String path, + ) async { + try { + await diaryService.sendRemovePhotoData( + diaryID, + mealID, + path, + photoID, + ); + } catch (e) { + rethrow; + } + } + + Future finishDay( + int diaryID, + TimeOfDay? wakeup, + TimeOfDay? retire, + String? comment, + ) async { + try { + final formatter = DateFormat('HH:mm'); + final wakeupString = + formatter.format(DateTime(2022, 1, 1, wakeup!.hour, wakeup.minute)); + final retireString = + formatter.format(DateTime(2022, 1, 1, retire!.hour, retire.minute)); + await diaryService.sendFinishDay( + diaryID, + wakeupString, + retireString, + comment ?? " ", + ); + } catch (e) { + rethrow; + } + } } diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart index f358d7c..125db49 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -1,3 +1,5 @@ +import 'dart:io'; + import 'package:dio/dio.dart'; import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:eatvio_app/features/diary/models/portion.dart'; @@ -17,7 +19,7 @@ abstract class DiaryService { Future> getDiary(@Path() int id); @GET('/diary/{id}/dailyNutritionData/') - Future getChart(@Path() String id); + Future getChart(@Path() int id); @GET('/diary/product_nutritional_values/filter') Future>> getInputProduct( @@ -58,10 +60,42 @@ abstract class DiaryService { @Query('quantity') int quantity, ); + @POST('/diary/{diary_id}/meal/{meal_id}/photo/upload') + Future uploadImage( + @Path() int diary_id, + @Path() int meal_id, + @Part() File photo, + ); + + @POST('/diary/product_nutritional_values/sendToModeration') + Future> sendModerationData( + @Query('name') String product_name, + @Query('energy_on_100gr') double energy_on_100gr, + @Query('proteins_on_100gr') double proteins_on_100gr, + @Query('fats_on_100gr') double fats_on_100gr, + @Query('carbohydrates_on_100gr') double carbohydrates_on_100gr, + ); + + @POST('/diary/{diary_id}/finishDay') + Future sendFinishDay( + @Path() int diary_id, + @Query('wakeUp') String wakeup, + @Query('retire') String retire, + @Query('comment') String comment, + ); + @DELETE('/diary/{diary_id}/meal/{meal_id}/portions/{portion_id}/delete') Future sendRemovePortionData( @Path() int diary_id, @Path() int meal_id, @Path() int portion_id, ); + + @DELETE('/diary/{diary_id}/meal/{meal_id}/photo/delete') + Future sendRemovePhotoData( + @Path() int diary_id, + @Path() int meal_id, + @Query('path') String path, + @Query('id') int photo_id, + ); } diff --git a/lib/features/diary/services/diary_service.g.dart b/lib/features/diary/services/diary_service.g.dart index 50d9732..01a3488 100644 --- a/lib/features/diary/services/diary_service.g.dart +++ b/lib/features/diary/services/diary_service.g.dart @@ -74,29 +74,28 @@ class _DiaryService implements DiaryService { } @override - Future getChart(String id) async { + Future getChart(int id) async { final _extra = {}; final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType(Options( + final _result = await _dio.fetch(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/diary/${id}/dailyNutritionData/', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - final _value = DiaryModel.fromJson(_result.data!); + .compose( + _dio.options, + '/diary/${id}/dailyNutritionData/', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = _result.data; return _value; } @@ -291,6 +290,113 @@ class _DiaryService implements DiaryService { return _value; } + @override + Future uploadImage( + int diary_id, + int meal_id, + File photo, + ) async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + final _data = FormData(); + _data.files.add(MapEntry( + 'photo', + MultipartFile.fromFileSync( + photo.path, + filename: photo.path.split(Platform.pathSeparator).last, + ), + )); + await _dio.fetch(_setStreamType(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${diary_id}/meal/${meal_id}/photo/upload', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + } + + @override + Future> sendModerationData( + String product_name, + double energy_on_100gr, + double proteins_on_100gr, + double fats_on_100gr, + double carbohydrates_on_100gr, + ) async { + final _extra = {}; + final queryParameters = { + r'name': product_name, + r'energy_on_100gr': energy_on_100gr, + r'proteins_on_100gr': proteins_on_100gr, + r'fats_on_100gr': fats_on_100gr, + r'carbohydrates_on_100gr': carbohydrates_on_100gr, + }; + final _headers = {}; + const Map? _data = null; + final _result = await _dio.fetch>( + _setStreamType>(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/product_nutritional_values/sendToModeration', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = _result.data!.cast(); + return _value; + } + + @override + Future sendFinishDay( + int diary_id, + String wakeup, + String retire, + String comment, + ) async { + final _extra = {}; + final queryParameters = { + r'wakeUp': wakeup, + r'retire': retire, + r'comment': comment, + }; + final _headers = {}; + const Map? _data = null; + await _dio.fetch(_setStreamType(Options( + method: 'POST', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${diary_id}/finishDay', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + } + @override Future sendRemovePortionData( int diary_id, @@ -319,6 +425,38 @@ class _DiaryService implements DiaryService { )))); } + @override + Future sendRemovePhotoData( + int diary_id, + int meal_id, + String path, + int photo_id, + ) async { + final _extra = {}; + final queryParameters = { + r'path': path, + r'id': photo_id, + }; + final _headers = {}; + const Map? _data = null; + await _dio.fetch(_setStreamType(Options( + method: 'DELETE', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/diary/${diary_id}/meal/${meal_id}/photo/delete', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + } + RequestOptions _setStreamType(RequestOptions requestOptions) { if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || diff --git a/pubspec.yaml b/pubspec.yaml index 256f892..8a60729 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -68,6 +68,7 @@ dependencies: url_launcher: ^6.3.0 # debounce easy_debounce: ^2.0.3 + syncfusion_flutter_charts: ^26.1.42 dev_dependencies: build_runner: ^2.4.11 -- 2.49.1 From 2d15e9ea4ecb8b90ee1327764c9cb71b9485f5a0 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 25 Jul 2024 10:36:14 +0300 Subject: [PATCH 075/110] refactor(diary): Diary updated on method call success --- .../diary/presentation/bloc/diary_bloc.dart | 33 ++++--------------- .../diary/presentation/bloc/diary_event.dart | 3 +- 2 files changed, 8 insertions(+), 28 deletions(-) diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index a54ed15..cc0682a 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -43,9 +43,6 @@ class DiaryBloc extends Bloc { ); on(_finishDay); on(_sendModeration); - on( - reloadScreen, - ); on(_clearInput); } @@ -189,21 +186,6 @@ class DiaryBloc extends Bloc { } } - refreshScreen( - int mealID, - DiaryEvent event, - Emitter emit, - ) async { - await reloadScreen(event, emit); - } - - reloadScreen( - DiaryEvent event, - Emitter emit, - ) async { - print("Reloading..."); - } - Future _changeSatiety( ChangeSatiety event, Emitter emit, @@ -341,20 +323,14 @@ class DiaryBloc extends Bloc { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - Map data = await diaryRepository.addPortion( + await diaryRepository.addPortion( currentState.diary.id, currentState.currentMeal.id, currentState.product_nameController.text, currentState.portionController.title, int.parse(currentState.productQuantityController.text), ); - List newPortions = currentState.portions; - - final Portion newPortion = data['portion'] ?? - new Portion(id: 1, portion: 'gr', product_name: '1', quantity: 1); - newPortions.add(newPortion); - emit(currentState.copyWith(isAdded: true, portions: newPortions)); - //TODO update screen after addPortion() call + add(LoadDiary()); } } @@ -370,7 +346,7 @@ class DiaryBloc extends Bloc { event.portionId, ); } - //TODO update screen after _removePortion() call + add(LoadDiary()); } Future _uploadImages( @@ -386,6 +362,7 @@ class DiaryBloc extends Bloc { currentState.diary.id, currentState.currentMeal.id, ); + add(LoadDiary()); } } @@ -463,6 +440,7 @@ class DiaryBloc extends Bloc { int.parse(event.photoID), event.path, ); + add(LoadDiary()); } } @@ -476,6 +454,7 @@ class DiaryBloc extends Bloc { currentState.retireController, currentState.commentController.text, ); + add(LoadDiary()); } } diff --git a/lib/features/diary/presentation/bloc/diary_event.dart b/lib/features/diary/presentation/bloc/diary_event.dart index d663752..490fa0c 100644 --- a/lib/features/diary/presentation/bloc/diary_event.dart +++ b/lib/features/diary/presentation/bloc/diary_event.dart @@ -157,5 +157,6 @@ class SendModeration extends DiaryEvent { String fatsOn100gr; String carbohydratesOn100gr; @override - List get props => [name, energyOn100gr, proteinsOn100gr, fatsOn100gr, carbohydratesOn100gr]; + List get props => + [name, energyOn100gr, proteinsOn100gr, fatsOn100gr, carbohydratesOn100gr]; } -- 2.49.1 From 6886997fdeb295d308f63a5ad1bb7f74e617a4f8 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 25 Jul 2024 10:42:39 +0300 Subject: [PATCH 076/110] fix(diary):fix --- lib/features/diary/presentation/bloc/diary_bloc.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index cc0682a..e690335 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -1,7 +1,6 @@ import 'dart:async'; import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:eatvio_app/features/diary/models/meal.dart'; -import 'package:eatvio_app/features/diary/models/portion.dart'; import 'package:eatvio_app/features/diary/models/product.dart'; import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; import 'package:intl/intl.dart'; -- 2.49.1 From 6312de5aa86543e5449317f546f01a3bfae3013a Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 25 Jul 2024 14:16:13 +0300 Subject: [PATCH 077/110] feat(calendar): Initial layouts models and API for calendar --- lib/app_router.dart | 6 + .../calendar/models/calendar_model.dart | 10 +- .../models/calendar_model.freezed.dart | 200 +++--------------- .../calendar/models/calendar_model.g.dart | 20 +- .../presentation/pages/calendar_screen.dart | 109 ++++++++++ .../repositories/calendar_repository.dart | 5 +- .../calendar/services/calendar_service.dart | 2 +- .../calendar/services/calendar_service.g.dart | 11 +- lib/locator_service.dart | 8 + lib/main.dart | 25 ++- lib/widgets/custom_navigation_menu.dart | 13 +- pubspec.yaml | 1 + 12 files changed, 190 insertions(+), 220 deletions(-) create mode 100644 lib/features/calendar/presentation/pages/calendar_screen.dart diff --git a/lib/app_router.dart b/lib/app_router.dart index 50f7968..9d51f9c 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -1,4 +1,5 @@ import 'package:eatvio_app/core/token_storage.dart'; +import 'package:eatvio_app/features/calendar/presentation/pages/calendar_screen.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/diary/presentation/pages/diary_screen.dart'; @@ -245,6 +246,11 @@ class AppRouter { name: 'diaryScreen', builder: (context, state) => DiaryScreen(), ), + GoRoute( + path: '/calendar-screen', + name: 'calendarScreen', + builder: (context, state) => CalendarScreen(), + ), GoRoute( path: '/chat-select-screen', name: 'chatSelectScreen', diff --git a/lib/features/calendar/models/calendar_model.dart b/lib/features/calendar/models/calendar_model.dart index c206175..c13d5c5 100644 --- a/lib/features/calendar/models/calendar_model.dart +++ b/lib/features/calendar/models/calendar_model.dart @@ -6,14 +6,8 @@ part 'calendar_model.g.dart'; @freezed class CalendarModel with _$CalendarModel { const factory CalendarModel({ - required int id, - required String state, - required String image, - required String description, - @JsonKey(name: "youtube_url") required String youtubeUrl, - @JsonKey(name: "created_at") required DateTime createdAt, - @JsonKey(name: "updated_at") required DateTime updatedAt, - required String title, + required String date, + Object? diary, }) = _CalendarModel; factory CalendarModel.fromJson(Map json) => diff --git a/lib/features/calendar/models/calendar_model.freezed.dart b/lib/features/calendar/models/calendar_model.freezed.dart index 7f0d320..fd8f7ea 100644 --- a/lib/features/calendar/models/calendar_model.freezed.dart +++ b/lib/features/calendar/models/calendar_model.freezed.dart @@ -20,17 +20,8 @@ CalendarModel _$CalendarModelFromJson(Map json) { /// @nodoc mixin _$CalendarModel { - int get id => throw _privateConstructorUsedError; - String get state => throw _privateConstructorUsedError; - String get image => throw _privateConstructorUsedError; - String get description => throw _privateConstructorUsedError; - @JsonKey(name: "youtube_url") - String get youtubeUrl => throw _privateConstructorUsedError; - @JsonKey(name: "created_at") - DateTime get createdAt => throw _privateConstructorUsedError; - @JsonKey(name: "updated_at") - DateTime get updatedAt => throw _privateConstructorUsedError; - String get title => throw _privateConstructorUsedError; + String get date => throw _privateConstructorUsedError; + Object? get diary => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -44,15 +35,7 @@ abstract class $CalendarModelCopyWith<$Res> { CalendarModel value, $Res Function(CalendarModel) then) = _$CalendarModelCopyWithImpl<$Res, CalendarModel>; @useResult - $Res call( - {int id, - String state, - String image, - String description, - @JsonKey(name: "youtube_url") String youtubeUrl, - @JsonKey(name: "created_at") DateTime createdAt, - @JsonKey(name: "updated_at") DateTime updatedAt, - String title}); + $Res call({String date, Object? diary}); } /// @nodoc @@ -68,48 +51,15 @@ class _$CalendarModelCopyWithImpl<$Res, $Val extends CalendarModel> @pragma('vm:prefer-inline') @override $Res call({ - Object? id = null, - Object? state = null, - Object? image = null, - Object? description = null, - Object? youtubeUrl = null, - Object? createdAt = null, - Object? updatedAt = null, - Object? title = null, + Object? date = null, + Object? diary = freezed, }) { return _then(_value.copyWith( - id: null == id - ? _value.id - : id // ignore: cast_nullable_to_non_nullable - as int, - state: null == state - ? _value.state - : state // ignore: cast_nullable_to_non_nullable - as String, - image: null == image - ? _value.image - : image // ignore: cast_nullable_to_non_nullable - as String, - description: null == description - ? _value.description - : description // ignore: cast_nullable_to_non_nullable - as String, - youtubeUrl: null == youtubeUrl - ? _value.youtubeUrl - : youtubeUrl // ignore: cast_nullable_to_non_nullable - as String, - createdAt: null == createdAt - ? _value.createdAt - : createdAt // ignore: cast_nullable_to_non_nullable - as DateTime, - updatedAt: null == updatedAt - ? _value.updatedAt - : updatedAt // ignore: cast_nullable_to_non_nullable - as DateTime, - title: null == title - ? _value.title - : title // ignore: cast_nullable_to_non_nullable + date: null == date + ? _value.date + : date // ignore: cast_nullable_to_non_nullable as String, + diary: freezed == diary ? _value.diary : diary, ) as $Val); } } @@ -122,15 +72,7 @@ abstract class _$$CalendarModelImplCopyWith<$Res> __$$CalendarModelImplCopyWithImpl<$Res>; @override @useResult - $Res call( - {int id, - String state, - String image, - String description, - @JsonKey(name: "youtube_url") String youtubeUrl, - @JsonKey(name: "created_at") DateTime createdAt, - @JsonKey(name: "updated_at") DateTime updatedAt, - String title}); + $Res call({String date, Object? diary}); } /// @nodoc @@ -144,48 +86,15 @@ class __$$CalendarModelImplCopyWithImpl<$Res> @pragma('vm:prefer-inline') @override $Res call({ - Object? id = null, - Object? state = null, - Object? image = null, - Object? description = null, - Object? youtubeUrl = null, - Object? createdAt = null, - Object? updatedAt = null, - Object? title = null, + Object? date = null, + Object? diary = freezed, }) { return _then(_$CalendarModelImpl( - id: null == id - ? _value.id - : id // ignore: cast_nullable_to_non_nullable - as int, - state: null == state - ? _value.state - : state // ignore: cast_nullable_to_non_nullable - as String, - image: null == image - ? _value.image - : image // ignore: cast_nullable_to_non_nullable - as String, - description: null == description - ? _value.description - : description // ignore: cast_nullable_to_non_nullable - as String, - youtubeUrl: null == youtubeUrl - ? _value.youtubeUrl - : youtubeUrl // ignore: cast_nullable_to_non_nullable - as String, - createdAt: null == createdAt - ? _value.createdAt - : createdAt // ignore: cast_nullable_to_non_nullable - as DateTime, - updatedAt: null == updatedAt - ? _value.updatedAt - : updatedAt // ignore: cast_nullable_to_non_nullable - as DateTime, - title: null == title - ? _value.title - : title // ignore: cast_nullable_to_non_nullable + date: null == date + ? _value.date + : date // ignore: cast_nullable_to_non_nullable as String, + diary: freezed == diary ? _value.diary : diary, )); } } @@ -193,42 +102,19 @@ class __$$CalendarModelImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() class _$CalendarModelImpl implements _CalendarModel { - const _$CalendarModelImpl( - {required this.id, - required this.state, - required this.image, - required this.description, - @JsonKey(name: "youtube_url") required this.youtubeUrl, - @JsonKey(name: "created_at") required this.createdAt, - @JsonKey(name: "updated_at") required this.updatedAt, - required this.title}); + const _$CalendarModelImpl({required this.date, this.diary}); factory _$CalendarModelImpl.fromJson(Map json) => _$$CalendarModelImplFromJson(json); @override - final int id; + final String date; @override - final String state; - @override - final String image; - @override - final String description; - @override - @JsonKey(name: "youtube_url") - final String youtubeUrl; - @override - @JsonKey(name: "created_at") - final DateTime createdAt; - @override - @JsonKey(name: "updated_at") - final DateTime updatedAt; - @override - final String title; + final Object? diary; @override String toString() { - return 'CalendarModel(id: $id, state: $state, image: $image, description: $description, youtubeUrl: $youtubeUrl, createdAt: $createdAt, updatedAt: $updatedAt, title: $title)'; + return 'CalendarModel(date: $date, diary: $diary)'; } @override @@ -236,24 +122,14 @@ class _$CalendarModelImpl implements _CalendarModel { return identical(this, other) || (other.runtimeType == runtimeType && other is _$CalendarModelImpl && - (identical(other.id, id) || other.id == id) && - (identical(other.state, state) || other.state == state) && - (identical(other.image, image) || other.image == image) && - (identical(other.description, description) || - other.description == description) && - (identical(other.youtubeUrl, youtubeUrl) || - other.youtubeUrl == youtubeUrl) && - (identical(other.createdAt, createdAt) || - other.createdAt == createdAt) && - (identical(other.updatedAt, updatedAt) || - other.updatedAt == updatedAt) && - (identical(other.title, title) || other.title == title)); + (identical(other.date, date) || other.date == date) && + const DeepCollectionEquality().equals(other.diary, diary)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, state, image, description, - youtubeUrl, createdAt, updatedAt, title); + int get hashCode => Object.hash( + runtimeType, date, const DeepCollectionEquality().hash(diary)); @JsonKey(ignore: true) @override @@ -271,37 +147,15 @@ class _$CalendarModelImpl implements _CalendarModel { abstract class _CalendarModel implements CalendarModel { const factory _CalendarModel( - {required final int id, - required final String state, - required final String image, - required final String description, - @JsonKey(name: "youtube_url") required final String youtubeUrl, - @JsonKey(name: "created_at") required final DateTime createdAt, - @JsonKey(name: "updated_at") required final DateTime updatedAt, - required final String title}) = _$CalendarModelImpl; + {required final String date, final Object? diary}) = _$CalendarModelImpl; factory _CalendarModel.fromJson(Map json) = _$CalendarModelImpl.fromJson; @override - int get id; + String get date; @override - String get state; - @override - String get image; - @override - String get description; - @override - @JsonKey(name: "youtube_url") - String get youtubeUrl; - @override - @JsonKey(name: "created_at") - DateTime get createdAt; - @override - @JsonKey(name: "updated_at") - DateTime get updatedAt; - @override - String get title; + Object? get diary; @override @JsonKey(ignore: true) _$$CalendarModelImplCopyWith<_$CalendarModelImpl> get copyWith => diff --git a/lib/features/calendar/models/calendar_model.g.dart b/lib/features/calendar/models/calendar_model.g.dart index d675f9b..c12dd96 100644 --- a/lib/features/calendar/models/calendar_model.g.dart +++ b/lib/features/calendar/models/calendar_model.g.dart @@ -8,24 +8,12 @@ part of 'calendar_model.dart'; _$CalendarModelImpl _$$CalendarModelImplFromJson(Map json) => _$CalendarModelImpl( - id: (json['id'] as num).toInt(), - state: json['state'] as String, - image: json['image'] as String, - description: json['description'] as String, - youtubeUrl: json['youtube_url'] as String, - createdAt: DateTime.parse(json['created_at'] as String), - updatedAt: DateTime.parse(json['updated_at'] as String), - title: json['title'] as String, + date: json['date'] as String, + diary: json['diary'], ); Map _$$CalendarModelImplToJson(_$CalendarModelImpl instance) => { - 'id': instance.id, - 'state': instance.state, - 'image': instance.image, - 'description': instance.description, - 'youtube_url': instance.youtubeUrl, - 'created_at': instance.createdAt.toIso8601String(), - 'updated_at': instance.updatedAt.toIso8601String(), - 'title': instance.title, + 'date': instance.date, + 'diary': instance.diary, }; diff --git a/lib/features/calendar/presentation/pages/calendar_screen.dart b/lib/features/calendar/presentation/pages/calendar_screen.dart new file mode 100644 index 0000000..7ef68dd --- /dev/null +++ b/lib/features/calendar/presentation/pages/calendar_screen.dart @@ -0,0 +1,109 @@ +// ignore_for_file: unused_local_variable + +import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_cubit.dart'; +import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_state.dart'; +import 'package:eatvio_app/core/app_export.dart'; +import 'package:table_calendar/table_calendar.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; + +// ignore: must_be_immutable +class CalendarScreen extends StatelessWidget { + CalendarScreen({Key? key}) : super(key: key); + Widget build(BuildContext context) { + return BlocBuilder( + builder: (context, state) { + if (state is CalendarStateLoaded) { + return _buildCalendar(context, state); + } else if (state is CalendarStateLoading) { + return Scaffold( + body: Center( + child: CupertinoActivityIndicator(), + ), + ); + } else if (state is CalendarStateError) { + return Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: Center( + child: Text(state.errorMessage), + ), + ), + ); + } else + return Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: Center( + child: Text("Неопределенная ошибка"), + ), + ), + ); + }, + ); + } + + Widget _buildCalendar(BuildContext context, CalendarStateLoaded state) { + return Stack(alignment: Alignment.bottomCenter, children: [ + FormBuilder( + child: Scaffold( + appBar: AppBar( + toolbarHeight: 0, + automaticallyImplyLeading: false, + ), + backgroundColor: Color.fromARGB(255, 240, 242, 245), + resizeToAvoidBottomInset: true, + body: SizedBox( + width: double.maxFinite, + child: Column( + children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.only(bottom: 5.v), + child: Column( + children: [ + SizedBox(height: 20.v), + _buildCalendarBody(context, state), + SizedBox(height: 20.v), + ], + ), + ), + ), + ), + ], + ), + ), + ), + ), + ]); + } + + _buildCalendarBody(BuildContext context, CalendarStateLoaded state) { + return Container( + margin: EdgeInsets.symmetric(horizontal: 16.h, vertical: 16.h), + padding: EdgeInsets.symmetric( + horizontal: 24.h, + vertical: 12.v, + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.all(Radius.circular(12)), + boxShadow: [ + BoxShadow( + color: Colors.grey.withOpacity(0.5), + spreadRadius: 2, + blurRadius: 5, + offset: Offset(0, 3), + ), + ], + ), + child: TableCalendar( + firstDay: DateTime.utc(2010, 10, 16), + lastDay: DateTime.utc(2030, 3, 14), + focusedDay: DateTime.now(), + ), + ); + } +} diff --git a/lib/features/calendar/repositories/calendar_repository.dart b/lib/features/calendar/repositories/calendar_repository.dart index 97a23dc..fd9f734 100644 --- a/lib/features/calendar/repositories/calendar_repository.dart +++ b/lib/features/calendar/repositories/calendar_repository.dart @@ -8,10 +8,7 @@ class CalendarRepository { Future> getCalendar() async { try { - return (await calendarService.getCalendar()) - .entries - .map((entry) => entry.value) - .toList(); + return await calendarService.getCalendar(); } catch (e) { rethrow; } diff --git a/lib/features/calendar/services/calendar_service.dart b/lib/features/calendar/services/calendar_service.dart index 80b98e6..d3e3c97 100644 --- a/lib/features/calendar/services/calendar_service.dart +++ b/lib/features/calendar/services/calendar_service.dart @@ -9,5 +9,5 @@ abstract class CalendarService { factory CalendarService(Dio dio, {String baseUrl}) = _CalendarService; @GET('/calendar/index') - Future> getCalendar(); + Future> getCalendar(); } diff --git a/lib/features/calendar/services/calendar_service.g.dart b/lib/features/calendar/services/calendar_service.g.dart index 5703378..f89b79e 100644 --- a/lib/features/calendar/services/calendar_service.g.dart +++ b/lib/features/calendar/services/calendar_service.g.dart @@ -19,13 +19,13 @@ class _CalendarService implements CalendarService { String? baseUrl; @override - Future> getCalendar() async { + Future> getCalendar() async { final _extra = {}; final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>( - _setStreamType>(Options( + final _result = await _dio + .fetch>(_setStreamType>(Options( method: 'GET', headers: _headers, extra: _extra, @@ -41,8 +41,9 @@ class _CalendarService implements CalendarService { _dio.options.baseUrl, baseUrl, )))); - var _value = _result.data!.map((k, dynamic v) => - MapEntry(k, CalendarModel.fromJson(v as Map))); + var _value = _result.data! + .map((dynamic i) => CalendarModel.fromJson(i as Map)) + .toList(); return _value; } diff --git a/lib/locator_service.dart b/lib/locator_service.dart index 7f2caf5..fa54c50 100644 --- a/lib/locator_service.dart +++ b/lib/locator_service.dart @@ -3,6 +3,9 @@ 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'; import 'package:eatvio_app/features/blog_post/services/blog_post_service.dart'; +import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_cubit.dart'; +import 'package:eatvio_app/features/calendar/repositories/calendar_repository.dart'; +import 'package:eatvio_app/features/calendar/services/calendar_service.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; import 'package:eatvio_app/features/chat/services/chat_service.dart'; @@ -27,6 +30,8 @@ Future init() async { sl.registerFactory( () => BlogPostCubit(blogPostRepository: sl())); sl.registerFactory(() => DiaryBloc(diaryRepository: sl())); + sl.registerFactory( + () => CalendarCubit(calendarRepository: sl())); // Repository sl.registerLazySingleton( @@ -37,12 +42,15 @@ Future init() async { () => BlogPostRepository(blogPostService: sl())); sl.registerLazySingleton( () => DiaryRepository(diaryService: sl())); + sl.registerLazySingleton( + () => CalendarRepository(calendarService: sl())); // Services sl.registerLazySingleton(() => ChatService(sl())); sl.registerLazySingleton(() => FeedService(sl())); sl.registerLazySingleton(() => BlogPostService(sl())); sl.registerLazySingleton(() => DiaryService(sl())); + sl.registerLazySingleton(() => CalendarService(sl())); // External sl.registerLazySingleton( diff --git a/lib/main.dart b/lib/main.dart index f71b4a5..9ce1b92 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,6 +1,7 @@ import 'package:eatvio_app/app_router.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_state.dart'; +import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_cubit.dart'; 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'; @@ -41,13 +42,25 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MultiBlocProvider( providers: [ - BlocProvider(create: (context) => InitializationCubit(chatRepository: sl())), - BlocProvider(create: (context) => ThemeBloc(ThemeState(themeType: PrefUtils().getThemeData()))), - BlocProvider(create: (context) => sl()..loadFeedBlogPostList()), - BlocProvider(create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent())), - BlocProvider(create: (context) => sl()..add(LoadDiary())), + BlocProvider( + create: (context) => InitializationCubit(chatRepository: sl())), + BlocProvider( + create: (context) => + ThemeBloc(ThemeState(themeType: PrefUtils().getThemeData()))), + BlocProvider( + create: (context) => sl()..loadFeedBlogPostList()), + BlocProvider( + create: (context) => sl()..loadCalendarList()), + BlocProvider( + create: (context) => MyProfileBloc( + MyProfileState(myProfileModelObj: MyProfileModel())) + ..add(MyProfileInitialEvent())), + BlocProvider( + create: (context) => sl()..add(LoadDiary())), BlocProvider( - create: (context) => ChatSelectBloc(ChatSelectState(chatSelectModelObj: ChatSelectModel()))..add(ChatSelectInitialEvent()), + create: (context) => ChatSelectBloc( + ChatSelectState(chatSelectModelObj: ChatSelectModel())) + ..add(ChatSelectInitialEvent()), ), ], child: BlocListener( diff --git a/lib/widgets/custom_navigation_menu.dart b/lib/widgets/custom_navigation_menu.dart index 03d11a9..0a5d354 100644 --- a/lib/widgets/custom_navigation_menu.dart +++ b/lib/widgets/custom_navigation_menu.dart @@ -23,19 +23,21 @@ class CustomNavigationMenu extends StatelessWidget { icon: ImageConstant.imgRecipes, text: 'Мои рецепты', onTap: () => GoRouter.of(context).push('/recipe-select-screen'), - // Действие при нажатии на "Мои рецепты" ), MenuItem( icon: ImageConstant.imgDiets, text: 'Мои диеты', onTap: () => GoRouter.of(context).push('/diet-select-screen'), - // Действие при нажатии на "Мои рецепты" ), MenuItem( icon: ImageConstant.imgPlans, text: 'Мои планы', onTap: () => GoRouter.of(context).push('/plan-select-screen'), - // Действие при нажатии на "Мои рецепты" + ), + MenuItem( + icon: ImageConstant.imgRecipes, + text: 'Календарь', + onTap: () => GoRouter.of(context).push('/calendar-screen'), ), MenuItem( icon: ImageConstant.imgFinance, @@ -45,15 +47,12 @@ class CustomNavigationMenu extends StatelessWidget { MenuItem( icon: ImageConstant.imgSupport, text: 'Поддержка', - onTap: () { - // Действие при нажатии на "Поддержка" - }, + onTap: () {}, ), MenuItem( icon: ImageConstant.imgExit, text: 'Выход', onTap: _onTapLogout(context), - // Действие при нажатии на "Выход" ), ], ), diff --git a/pubspec.yaml b/pubspec.yaml index 8a60729..a797498 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -69,6 +69,7 @@ dependencies: # debounce easy_debounce: ^2.0.3 syncfusion_flutter_charts: ^26.1.42 + table_calendar: ^3.1.2 dev_dependencies: build_runner: ^2.4.11 -- 2.49.1 From 102154ddb264ab7910555748e3996f1aecbb3800 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 25 Jul 2024 15:29:30 +0300 Subject: [PATCH 078/110] feat(calendar): Calendar Event class --- .../presentation/pages/calendar_screen.dart | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/lib/features/calendar/presentation/pages/calendar_screen.dart b/lib/features/calendar/presentation/pages/calendar_screen.dart index 7ef68dd..93179cb 100644 --- a/lib/features/calendar/presentation/pages/calendar_screen.dart +++ b/lib/features/calendar/presentation/pages/calendar_screen.dart @@ -7,6 +7,7 @@ import 'package:table_calendar/table_calendar.dart'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'dart:collection'; // ignore: must_be_immutable class CalendarScreen extends StatelessWidget { @@ -103,7 +104,60 @@ class CalendarScreen extends StatelessWidget { firstDay: DateTime.utc(2010, 10, 16), lastDay: DateTime.utc(2030, 3, 14), focusedDay: DateTime.now(), + eventLoader: (day) { + if (day.weekday == DateTime.monday) { + return [Event('Cyclic event')]; + } + + return []; + }, ), ); } } + +/// Example event class. +class Event { + final String title; + + const Event(this.title); + + @override + String toString() => title; +} + +/// Example events. +/// +/// Using a [LinkedHashMap] is highly recommended if you decide to use a map. +final kEvents = LinkedHashMap>( + equals: isSameDay, + hashCode: getHashCode, +)..addAll(_kEventSource); + +final _kEventSource = Map.fromIterable(List.generate(50, (index) => index), + key: (item) => DateTime.utc(kFirstDay.year, kFirstDay.month, item * 5), + value: (item) => List.generate( + item % 4 + 1, (index) => Event('Event $item | ${index + 1}'))) + ..addAll({ + kToday: [ + Event('Today\'s Event 1'), + Event('Today\'s Event 2'), + ], + }); + +int getHashCode(DateTime key) { + return key.day * 1000000 + key.month * 10000 + key.year; +} + +/// Returns a list of [DateTime] objects from [first] to [last], inclusive. +List daysInRange(DateTime first, DateTime last) { + final dayCount = last.difference(first).inDays + 1; + return List.generate( + dayCount, + (index) => DateTime.utc(first.year, first.month, first.day + index), + ); +} + +final kToday = DateTime.now(); +final kFirstDay = DateTime(kToday.year, kToday.month - 3, kToday.day); +final kLastDay = DateTime(kToday.year, kToday.month + 3, kToday.day); -- 2.49.1 From 56e5cdbe168ff5ab0254337c4ed51bcdc4a13728 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 25 Jul 2024 16:53:49 +0300 Subject: [PATCH 079/110] fix(calendar): Finished days fix --- .../presentation/pages/calendar_screen.dart | 80 +++-- .../diary/presentation/bloc/diary_bloc.dart | 115 ++----- .../diary/presentation/bloc/diary_state.dart | 4 +- .../bloc/diary_state.freezed.dart | 92 +++--- .../presentation/pages/diary_screen.dart | 284 ++---------------- .../diary/repositories/diary_repository.dart | 18 +- .../diary/services/diary_service.dart | 9 +- .../diary/services/diary_service.g.dart | 13 +- 8 files changed, 132 insertions(+), 483 deletions(-) diff --git a/lib/features/calendar/presentation/pages/calendar_screen.dart b/lib/features/calendar/presentation/pages/calendar_screen.dart index 93179cb..9dab6be 100644 --- a/lib/features/calendar/presentation/pages/calendar_screen.dart +++ b/lib/features/calendar/presentation/pages/calendar_screen.dart @@ -1,5 +1,6 @@ // ignore_for_file: unused_local_variable +import 'package:eatvio_app/features/calendar/models/calendar_model.dart'; import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_cubit.dart'; import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_state.dart'; import 'package:eatvio_app/core/app_export.dart'; @@ -7,7 +8,6 @@ import 'package:table_calendar/table_calendar.dart'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'dart:collection'; // ignore: must_be_immutable class CalendarScreen extends StatelessWidget { @@ -104,60 +104,48 @@ class CalendarScreen extends StatelessWidget { firstDay: DateTime.utc(2010, 10, 16), lastDay: DateTime.utc(2030, 3, 14), focusedDay: DateTime.now(), - eventLoader: (day) { - if (day.weekday == DateTime.monday) { - return [Event('Cyclic event')]; - } - - return []; - }, + startingDayOfWeek: StartingDayOfWeek.monday, + calendarBuilders: CalendarBuilders( + selectedBuilder: (context, day, focusedDay) => _buildCellDate(day, focusedDay: focusedDay, state), + defaultBuilder: (context, day, focusedDay) => _buildCellDate(day, state), + todayBuilder: (context, day, focusedDay) => _buildCellDate(day, state), + ), ), ); } } -/// Example event class. -class Event { - final String title; +Widget _buildCellDate(DateTime day, CalendarStateLoaded state, {DateTime? focusedDay}) { + final String dayString = day.toIso8601String().split('T').first; + final List calendarModels = state.calendarList; - const Event(this.title); + // Находим первую модель, соответствующую дате + final CalendarModel model = calendarModels.firstWhere((model) => model.date == dayString, orElse: () => CalendarModel(date: dayString, diary: {})); - @override - String toString() => title; -} + Color? bgclr; // Объявляем переменную bgclr здесь -/// Example events. -/// -/// Using a [LinkedHashMap] is highly recommended if you decide to use a map. -final kEvents = LinkedHashMap>( - equals: isSameDay, - hashCode: getHashCode, -)..addAll(_kEventSource); + if (model.diary is Map) { + final Map diary = model.diary as Map; -final _kEventSource = Map.fromIterable(List.generate(50, (index) => index), - key: (item) => DateTime.utc(kFirstDay.year, kFirstDay.month, item * 5), - value: (item) => List.generate( - item % 4 + 1, (index) => Event('Event $item | ${index + 1}'))) - ..addAll({ - kToday: [ - Event('Today\'s Event 1'), - Event('Today\'s Event 2'), - ], - }); + if (diary['state'] == "started") { + bgclr = Colors.grey; + } else if (diary['state'] == "finished") { + bgclr = Colors.green; + } else { + bgclr = Colors.white; + } + } else { + bgclr = Colors.white; // Значение по умолчанию, если diary не является Map + } -int getHashCode(DateTime key) { - return key.day * 1000000 + key.month * 10000 + key.year; -} - -/// Returns a list of [DateTime] objects from [first] to [last], inclusive. -List daysInRange(DateTime first, DateTime last) { - final dayCount = last.difference(first).inDays + 1; - return List.generate( - dayCount, - (index) => DateTime.utc(first.year, first.month, first.day + index), + return Container( + margin: const EdgeInsets.all(5), + alignment: Alignment.center, + decoration: BoxDecoration( + shape: (day == focusedDay) ? BoxShape.circle : BoxShape.rectangle, + color: bgclr, + borderRadius: (day == focusedDay) ? null : BorderRadius.circular(4), + ), + child: Text(day.day.toString(), style: TextStyle(color: Colors.black)), ); } - -final kToday = DateTime.now(); -final kFirstDay = DateTime(kToday.year, kToday.month - 3, kToday.day); -final kLastDay = DateTime(kToday.year, kToday.month + 3, kToday.day); diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index e690335..8ac0e8a 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -9,9 +9,6 @@ import 'package:flutter/material.dart'; import '/core/app_export.dart'; import 'package:image_picker/image_picker.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; -import 'package:http/http.dart' as http; -import 'dart:convert'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; part 'diary_event.dart'; @@ -19,8 +16,7 @@ part 'diary_event.dart'; class DiaryBloc extends Bloc { final DiaryRepository diaryRepository; - DiaryBloc({required this.diaryRepository}) - : super(const DiaryState.loading()) { + DiaryBloc({required this.diaryRepository}) : super(const DiaryState.loading()) { on(loadDiary); on(_changeSatiety); // пользователь нажимает на шкалу сытости on(_changeMood); // пользователь нажимает на шкалу настроения @@ -57,29 +53,15 @@ class DiaryBloc extends Bloc { final DiaryModel diary = await diaryRepository.getDiary(diaryID ?? 45); final Meal currentMeal = diary.meals[0]; - List portionList = [ - SelectionPopupModel(title: "gr"), - SelectionPopupModel(title: "pcs") - ]; + List portionList = [SelectionPopupModel(title: "gr"), SelectionPopupModel(title: "pcs")]; - final Map chartData = - await diaryRepository.getChartData(diaryID ?? 45); - final Map dailyNutritionIntake = - chartData['dailyNutritionIntake']!; - final Map dailyNutritionRecommendations = - chartData['dailyNutritionRecommendation']!; - final double ccal = dailyNutritionIntake['energy']! / - dailyNutritionRecommendations['energy']! * - 100; - final double proteins = dailyNutritionIntake['proteins']! / - dailyNutritionRecommendations['proteins']! * - 100; - final double fats = dailyNutritionIntake['fats']! / - dailyNutritionRecommendations['fats']! * - 100; - final double carbs = dailyNutritionIntake['carbohydrates']! / - dailyNutritionRecommendations['carbohydrates']! * - 100; + final Map chartData = await diaryRepository.getChartData(diaryID ?? 45); + final Map dailyNutritionIntake = chartData['dailyNutritionIntake']!; + final Map dailyNutritionRecommendations = chartData['dailyNutritionRecommendation']!; + final double ccal = dailyNutritionIntake['energy']! / dailyNutritionRecommendations['energy']! * 100; + final double proteins = dailyNutritionIntake['proteins']! / dailyNutritionRecommendations['proteins']! * 100; + final double fats = dailyNutritionIntake['fats']! / dailyNutritionRecommendations['fats']! * 100; + final double carbs = dailyNutritionIntake['carbohydrates']! / dailyNutritionRecommendations['carbohydrates']! * 100; Color getColor(double value) { if (value >= 99.1) { @@ -105,8 +87,6 @@ class DiaryBloc extends Bloc { SelectionPopupModel(title: "Прием пищи 6", id: 6), ]; - print(dailyNutritionRecommendations); - print(dailyNutritionIntake); emit(DiaryState.loaded( diary: diary, currentMeal: currentMeal, @@ -117,6 +97,8 @@ class DiaryBloc extends Bloc { chartData: chartDataCounted, selectedMood: currentMeal.mood, selectedSatiety: currentMeal.satiety, + wakeupController: TimeOfDay.now(), + retireController: TimeOfDay.now(), commentController: TextEditingController(), product_nameController: TextEditingController(), productQuantityController: TextEditingController(), @@ -137,54 +119,6 @@ class DiaryBloc extends Bloc { } } - fetchChartValues( - String token, - int diaryID, - Emitter emit, - ) async { - final responseChart = await http.get( - Uri.parse( - dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/dailyNutritionData/', - ), - headers: { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer $token', - }, - ); - - if (responseChart.statusCode == 200) { - final responseBody = jsonDecode(responseChart.body); - print(responseBody); - final recommendedChartValues = - responseBody['dailyNutritionRecommendation'] - .values - .map((value) => convertToInt(value)) - .toList(); - - final consumedChartValues = responseBody['dailyNutritionIntake'] - .values - .map((value) => convertToInt(value)) - .toList(); - - print([ - recommendedChartValues, - consumedChartValues, - ]); - return [ - recommendedChartValues, - consumedChartValues, - ]; - } else { - emit(DiaryStateError( - errorMessage: 'Ошибка при декодировании данных КБЖУ')); - print('fail'); - return [ - [], - [], - ]; - } - } - Future _changeSatiety( ChangeSatiety event, Emitter emit, @@ -229,11 +163,9 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = - currentState.copyWith(wakeupController: event.selectedTime); + var updatedState = currentState.copyWith(wakeupController: event.selectedTime); final DateFormat formatter = DateFormat('HH:mm'); - final String wakeupString = formatter.format(DateTime( - 2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); + final String wakeupString = formatter.format(DateTime(2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); await diaryRepository.changeWakeup( currentState.diary.id, wakeupString, @@ -248,11 +180,9 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = - currentState.copyWith(retireController: event.selectedTime); + var updatedState = currentState.copyWith(retireController: event.selectedTime); final DateFormat formatter = DateFormat('HH:mm'); - final String retireString = formatter.format(DateTime( - 2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); + final String retireString = formatter.format(DateTime(2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); await diaryRepository.changeRetire( currentState.diary.id, retireString, @@ -278,8 +208,7 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { final currentState = state as DiaryStateLoaded; - final Meal meal = currentState.diary.meals - .firstWhere((meal) => meal.type == event.value.id); + final Meal meal = currentState.diary.meals.firstWhere((meal) => meal.type == event.value.id); DiaryStateLoaded updatedState = currentState.copyWith( currentMeal: meal, portions: meal.portions, @@ -298,12 +227,10 @@ class DiaryBloc extends Bloc { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - final Map> productNutritionalValues = - await diaryRepository.inputProduct(event.input); + final Map> productNutritionalValues = await diaryRepository.inputProduct(event.input); var updatedState = currentState.copyWith( product_nameController: TextEditingController(text: event.input), - autocompleteList: - productNutritionalValues['product_nutritional_value'] ?? [], + autocompleteList: productNutritionalValues['product_nutritional_value'] ?? [], ); if (event.input.length > 3) { updatedState = updatedState.copyWith(moderationExpanded: true); @@ -449,9 +376,9 @@ class DiaryBloc extends Bloc { await diaryRepository.finishDay( currentState.diary.id, - currentState.wakeupController, - currentState.retireController, - currentState.commentController.text, + // currentState.wakeupController, + // currentState.retireController, + // currentState.commentController.text, ); add(LoadDiary()); } diff --git a/lib/features/diary/presentation/bloc/diary_state.dart b/lib/features/diary/presentation/bloc/diary_state.dart index 6feb5f1..9156576 100644 --- a/lib/features/diary/presentation/bloc/diary_state.dart +++ b/lib/features/diary/presentation/bloc/diary_state.dart @@ -26,8 +26,8 @@ abstract class DiaryState with _$DiaryState { required List autocompleteList, required Meal currentMeal, required SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + required TimeOfDay wakeupController, + required TimeOfDay retireController, TimeOfDay? mealTimeController, required TextEditingController commentController, required TextEditingController product_nameController, diff --git a/lib/features/diary/presentation/bloc/diary_state.freezed.dart b/lib/features/diary/presentation/bloc/diary_state.freezed.dart index deda872..a8cf8f1 100644 --- a/lib/features/diary/presentation/bloc/diary_state.freezed.dart +++ b/lib/features/diary/presentation/bloc/diary_state.freezed.dart @@ -31,8 +31,8 @@ mixin _$DiaryState { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, @@ -68,8 +68,8 @@ mixin _$DiaryState { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, @@ -105,8 +105,8 @@ mixin _$DiaryState { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, @@ -224,8 +224,8 @@ class _$DiaryStateImpl implements _DiaryState { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, @@ -264,8 +264,8 @@ class _$DiaryStateImpl implements _DiaryState { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, @@ -304,8 +304,8 @@ class _$DiaryStateImpl implements _DiaryState { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, @@ -425,8 +425,8 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, @@ -465,8 +465,8 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, @@ -505,8 +505,8 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, @@ -592,8 +592,8 @@ abstract class _$$DiaryStateLoadedImplCopyWith<$Res> { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, @@ -636,8 +636,8 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> Object? autocompleteList = null, Object? currentMeal = null, Object? portionController = null, - Object? wakeupController = freezed, - Object? retireController = freezed, + Object? wakeupController = null, + Object? retireController = null, Object? mealTimeController = freezed, Object? commentController = null, Object? product_nameController = null, @@ -696,14 +696,14 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> ? _value.portionController : portionController // ignore: cast_nullable_to_non_nullable as SelectionPopupModel, - wakeupController: freezed == wakeupController + wakeupController: null == wakeupController ? _value.wakeupController : wakeupController // ignore: cast_nullable_to_non_nullable - as TimeOfDay?, - retireController: freezed == retireController + as TimeOfDay, + retireController: null == retireController ? _value.retireController : retireController // ignore: cast_nullable_to_non_nullable - as TimeOfDay?, + as TimeOfDay, mealTimeController: freezed == mealTimeController ? _value.mealTimeController : mealTimeController // ignore: cast_nullable_to_non_nullable @@ -802,8 +802,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { required final List autocompleteList, required this.currentMeal, required this.portionController, - this.wakeupController, - this.retireController, + required this.wakeupController, + required this.retireController, this.mealTimeController, required this.commentController, required this.product_nameController, @@ -888,9 +888,9 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { @override final SelectionPopupModel portionController; @override - final TimeOfDay? wakeupController; + final TimeOfDay wakeupController; @override - final TimeOfDay? retireController; + final TimeOfDay retireController; @override final TimeOfDay? mealTimeController; @override @@ -1052,8 +1052,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, @@ -1120,8 +1120,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, @@ -1188,8 +1188,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, @@ -1294,8 +1294,8 @@ abstract class DiaryStateLoaded implements DiaryState { required final List autocompleteList, required final Meal currentMeal, required final SelectionPopupModel portionController, - final TimeOfDay? wakeupController, - final TimeOfDay? retireController, + required final TimeOfDay wakeupController, + required final TimeOfDay retireController, final TimeOfDay? mealTimeController, required final TextEditingController commentController, required final TextEditingController product_nameController, @@ -1323,8 +1323,8 @@ abstract class DiaryStateLoaded implements DiaryState { List get autocompleteList; Meal get currentMeal; SelectionPopupModel get portionController; - TimeOfDay? get wakeupController; - TimeOfDay? get retireController; + TimeOfDay get wakeupController; + TimeOfDay get retireController; TimeOfDay? get mealTimeController; TextEditingController get commentController; TextEditingController get product_nameController; @@ -1425,8 +1425,8 @@ class _$DiaryStateErrorImpl implements DiaryStateError { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, @@ -1465,8 +1465,8 @@ class _$DiaryStateErrorImpl implements DiaryStateError { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, @@ -1505,8 +1505,8 @@ class _$DiaryStateErrorImpl implements DiaryStateError { List autocompleteList, Meal currentMeal, SelectionPopupModel portionController, - TimeOfDay? wakeupController, - TimeOfDay? retireController, + TimeOfDay wakeupController, + TimeOfDay retireController, TimeOfDay? mealTimeController, TextEditingController commentController, TextEditingController product_nameController, diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index 53937a9..8be9be4 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -278,9 +278,7 @@ class DiaryScreen extends StatelessWidget { borderRadius: BorderRadiusStyle.roundedBorder5, ), child: Center( - child: CircularProgressIndicator( - color: appTheme - .blueGray300), // Замените на свой прелоадер при необходимости + child: CircularProgressIndicator(color: appTheme.blueGray300), // Замените на свой прелоадер при необходимости ), ), ], @@ -304,8 +302,7 @@ class DiaryScreen extends StatelessWidget { _buildMeal(BuildContext context, DiaryStateLoaded state) { final digitsOnly = FilteringTextInputFormatter.digitsOnly; - List _options = - state.autocompleteList.map((Product item) => item.name).toList(); + List _options = state.autocompleteList.map((Product item) => item.name).toList(); FocusNode focusNodeName = FocusNode(); return Container( margin: EdgeInsets.symmetric(horizontal: 16.h), @@ -349,9 +346,7 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectMealTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: state.mealTimeController - ?.format(context) - .toString(), + hintText: state.mealTimeController?.format(context).toString(), autofocus: false, ), ), @@ -487,9 +482,7 @@ class DiaryScreen extends StatelessWidget { SizedBox(height: 30.v), _buildAddProduct(context, state), SizedBox(height: 30.v), - ...state.portions - .map((portion) => _buildProduct(context, portion)) - .toList(), + ...state.portions.map((portion) => _buildProduct(context, portion)).toList(), SizedBox(height: 30.v), _buildCarousel(context, state), SizedBox(height: 20.v), @@ -638,8 +631,7 @@ class DiaryScreen extends StatelessWidget { popDialog(BuildContext dialogContext) { return () { - Navigator.of(dialogContext) - .pop(); // Dismiss the dialog on Cancel button press + Navigator.of(dialogContext).pop(); // Dismiss the dialog on Cancel button press }; } @@ -649,8 +641,7 @@ class DiaryScreen extends StatelessWidget { }; } - selectProduct(AutocompleteOnSelected onSelected, String option, - DiaryStateLoaded state) { + selectProduct(AutocompleteOnSelected onSelected, String option, DiaryStateLoaded state) { state.product_nameController.text = option; return () { onSelected(option); @@ -718,9 +709,7 @@ class DiaryScreen extends StatelessWidget { top: 5.v, ), child: Text( - portion.product_name.length > 8 - ? portion.product_name.substring(0, 8) - : portion.product_name, + portion.product_name.length > 8 ? portion.product_name.substring(0, 8) : portion.product_name, style: CustomTextStyles.titleMedium16, ), ), @@ -792,234 +781,10 @@ class DiaryScreen extends StatelessWidget { removePhoto(BuildContext context, Photo photo) { return () { - context - .read() - .add(RemoveImageEvent(photo.id.toString(), photo.path)); + context.read().add(RemoveImageEvent(photo.id.toString(), photo.path)); }; } - /*_buildNutritionChart(BuildContext context, DiaryStateLoaded state) { - final List recommendedValues = state - .recommendedChartValues; // Рекомендуемые значения: калории, жиры, белки, углеводы - final List consumedValues = state.consumedChartValues; // - return Container( - margin: EdgeInsets.symmetric(horizontal: 16.h), - padding: EdgeInsets.symmetric( - horizontal: 10.h, - vertical: 16.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: Column( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - SizedBox(height: 3.v), - Text( - "Ваш КБЖУ", - style: theme.textTheme.titleMedium, - ), - SizedBox(height: 8.v), - Text( - "От дневной суточной нормы", - style: CustomTextStyles.bodyMediumBluegray800, - ), - SizedBox(height: 19.v), - Align( - alignment: Alignment.centerRight, - child: Padding( - padding: EdgeInsets.only( - left: 30.h, - right: 12.h, - ), - child: AspectRatio( - aspectRatio: 1.5, - child: BarChart( - BarChartData( - alignment: BarChartAlignment.spaceAround, - barTouchData: BarTouchData(enabled: false), - titlesData: FlTitlesData( - show: true, - bottomTitles: AxisTitles( - sideTitles: SideTitles( - showTitles: true, - //getTitlesWidget: (value, meta) => newMethod(value), - ), - ), - ), - borderData: FlBorderData(show: false), - barGroups: [ - BarChartGroupData( - x: 0, - barRods: [ - BarChartRodData( - toY: consumedValues[0] / recommendedValues[0] * 100, - color: checkConsumedValues( - [recommendedValues[0]], [consumedValues[1]]) - ? Colors.red - : Colors.blue, - ), - ], - ), - BarChartGroupData( - x: 1, - barRods: [ - BarChartRodData( - toY: consumedValues[1] / recommendedValues[1] * 100, - color: checkConsumedValues( - [recommendedValues[1]], [consumedValues[1]]) - ? Colors.red - : Colors.blue, - ), - ], - ), - BarChartGroupData( - x: 2, - barRods: [ - BarChartRodData( - toY: consumedValues[2] / recommendedValues[2] * 100, - color: checkConsumedValues( - [recommendedValues[2]], [consumedValues[2]]) - ? Colors.red - : Colors.blue, - ), - ], - ), - BarChartGroupData( - x: 3, - barRods: [ - BarChartRodData( - toY: consumedValues[3] / recommendedValues[3] * 100, - color: checkConsumedValues( - [recommendedValues[3]], [consumedValues[3]]) - ? Colors.red - : Colors.blue, - ), - ], - ), - ], - ), - ), - ), - ), - ), - SizedBox(height: 8.v), - SizedBox(height: 2.v), - Padding( - padding: EdgeInsets.only( - left: 10.h, - right: 2.h, - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - "Калорий", - style: theme.textTheme.bodySmall, - ), - Padding( - padding: EdgeInsets.only( - left: 25.h, - bottom: 11.v, - ), - child: Text( - "Белков", - style: theme.textTheme.bodySmall, - ), - ), - Padding( - padding: EdgeInsets.only( - left: 19.h, - bottom: 11.v, - ), - child: Text( - "Жиров", - style: theme.textTheme.bodySmall, - ), - ), - Padding( - padding: EdgeInsets.only( - left: 14.h, - bottom: 11.v, - ), - child: Text( - "Углеводов", - style: theme.textTheme.bodySmall, - ), - ), - ], - ), - ), - SizedBox(height: 2.v), - Padding( - padding: EdgeInsets.only( - left: 10.h, - right: 2.h, - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - "${consumedValues[0].toInt()} из ${recommendedValues[0].toInt()}", - style: theme.textTheme.bodySmall, - ), - Padding( - padding: EdgeInsets.only( - left: 25.h, - bottom: 11.v, - ), - child: Text( - "${consumedValues[1].toInt()} из ${recommendedValues[1].toInt()}", - style: theme.textTheme.bodySmall, - ), - ), - Padding( - padding: EdgeInsets.only( - left: 19.h, - bottom: 11.v, - ), - child: Text( - "${consumedValues[2].toInt()} из ${recommendedValues[2].toInt()}", - style: theme.textTheme.bodySmall, - ), - ), - Padding( - padding: EdgeInsets.only( - left: 14.h, - bottom: 11.v, - ), - child: Text( - "${consumedValues[3].toInt()} из ${recommendedValues[3].toInt()}", - style: theme.textTheme.bodySmall, - ), - ), - ], - ), - ), - SizedBox(height: 19.v), - if (checkConsumedValues(recommendedValues, consumedValues)) - Text( - "*Превышенная суточная норма", - style: theme.textTheme.labelLarge, - ), - ], - ), - ); - }*/ - - /// Section Widget _buildComment(BuildContext context, DiaryStateLoaded state) { return Container( margin: EdgeInsets.symmetric(horizontal: 16.h), @@ -1094,9 +859,7 @@ class DiaryScreen extends StatelessWidget { r"Подъем \ отход ко сну", style: CustomTextStyles.bodyMediumBlack900, ), - Icon(state.wakeupExpanded - ? Icons.arrow_drop_up - : Icons.arrow_drop_down), + Icon(state.wakeupExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), ], ), ), @@ -1110,8 +873,7 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectWakeupTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: - state.wakeupController?.format(context).toString(), + hintText: state.wakeupController.format(context).toString(), prefix: Icon(Icons.sunny), autofocus: false, ), @@ -1122,8 +884,7 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectRetireTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: - state.retireController?.format(context).toString(), + hintText: state.retireController.format(context).toString(), prefix: Icon(Icons.bed), autofocus: false, ), @@ -1170,8 +931,7 @@ class DiaryScreen extends StatelessWidget { }; } - Function() sendFinishDayData( - BuildContext dialogContext, BuildContext context) { + Function() sendFinishDayData(BuildContext dialogContext, BuildContext context) { return () { closeDialog(dialogContext); context.read().add(FinishDay()); @@ -1214,9 +974,7 @@ class DiaryScreen extends StatelessWidget { "Ваше настроение после приема пищи", style: CustomTextStyles.bodyMediumBlack900, ), - Icon(state.moodExpanded - ? Icons.arrow_drop_up - : Icons.arrow_drop_down), + Icon(state.moodExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), ], ), ), @@ -1276,30 +1034,27 @@ class DiaryScreen extends StatelessWidget { }; } - Future _selectWakeupTime( - BuildContext context, DiaryStateLoaded state) async { + Future _selectWakeupTime(BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, - initialTime: state.wakeupController ?? TimeOfDay.now(), + initialTime: state.wakeupController, ); if (pickedTime != null && pickedTime != state.wakeupController) { context.read().add(WakeupEvent(pickedTime)); } } - Future _selectRetireTime( - BuildContext context, DiaryStateLoaded state) async { + Future _selectRetireTime(BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, - initialTime: state.retireController ?? TimeOfDay.now(), + initialTime: state.retireController, ); if (pickedTime != null && pickedTime != state.retireController) { context.read().add(RetireEvent(pickedTime)); } } - Future _selectMealTime( - BuildContext context, DiaryStateLoaded state) async { + Future _selectMealTime(BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.mealTimeController ?? TimeOfDay.now(), @@ -1310,8 +1065,7 @@ class DiaryScreen extends StatelessWidget { } } -bool checkConsumedValues( - List recommendedValues, List consumedValues) { +bool checkConsumedValues(List recommendedValues, List consumedValues) { for (int i = 0; i < recommendedValues.length; i++) { if (consumedValues[i] > recommendedValues[i]) { // Если хотя бы одно потребленное значение превышает рекомендованное diff --git a/lib/features/diary/repositories/diary_repository.dart b/lib/features/diary/repositories/diary_repository.dart index 56c9fbd..599c081 100644 --- a/lib/features/diary/repositories/diary_repository.dart +++ b/lib/features/diary/repositories/diary_repository.dart @@ -189,22 +189,12 @@ class DiaryRepository { Future finishDay( int diaryID, - TimeOfDay? wakeup, - TimeOfDay? retire, - String? comment, ) async { try { - final formatter = DateFormat('HH:mm'); - final wakeupString = - formatter.format(DateTime(2022, 1, 1, wakeup!.hour, wakeup.minute)); - final retireString = - formatter.format(DateTime(2022, 1, 1, retire!.hour, retire.minute)); - await diaryService.sendFinishDay( - diaryID, - wakeupString, - retireString, - comment ?? " ", - ); + /*final formatter = DateFormat('HH:mm'); + final wakeupString = formatter.format(DateTime(2022, 1, 1, wakeup.hour, wakeup.minute)); + final retireString = formatter.format(DateTime(2022, 1, 1, retire.hour, retire.minute));*/ + await diaryService.sendFinishDay(diaryID); } catch (e) { rethrow; } diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart index 125db49..bf9a890 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -22,8 +22,7 @@ abstract class DiaryService { Future getChart(@Path() int id); @GET('/diary/product_nutritional_values/filter') - Future>> getInputProduct( - @Query('name') String name); + Future>> getInputProduct(@Query('name') String name); @POST('/diary/{diary_id}/meal/{meal_id}/satiety/fill') Future> sendSatietyData( @@ -79,9 +78,9 @@ abstract class DiaryService { @POST('/diary/{diary_id}/finishDay') Future sendFinishDay( @Path() int diary_id, - @Query('wakeUp') String wakeup, - @Query('retire') String retire, - @Query('comment') String comment, + //@Query('wakeUp') String wakeup, + //@Query('retire') String retire, + //@Query('comment') String comment, ); @DELETE('/diary/{diary_id}/meal/{meal_id}/portions/{portion_id}/delete') diff --git a/lib/features/diary/services/diary_service.g.dart b/lib/features/diary/services/diary_service.g.dart index 01a3488..91e048e 100644 --- a/lib/features/diary/services/diary_service.g.dart +++ b/lib/features/diary/services/diary_service.g.dart @@ -365,18 +365,9 @@ class _DiaryService implements DiaryService { } @override - Future sendFinishDay( - int diary_id, - String wakeup, - String retire, - String comment, - ) async { + Future sendFinishDay(int diary_id) async { final _extra = {}; - final queryParameters = { - r'wakeUp': wakeup, - r'retire': retire, - r'comment': comment, - }; + final queryParameters = {}; final _headers = {}; const Map? _data = null; await _dio.fetch(_setStreamType(Options( -- 2.49.1 From 818721a993fc36491e38ba3831fa4b990a32b073 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Sun, 28 Jul 2024 18:39:36 +0300 Subject: [PATCH 080/110] feature(registration): add location endpoint with debounce --- .../user_registration_model.dart | 5 +- .../user_registration_model.freezed.dart | 75 +++---- .../user_registration_model.g.dart | 8 +- .../registration/models/location_model.dart | 15 ++ .../models/location_model.freezed.dart | 189 ++++++++++++++++++ .../registration/models/location_model.g.dart | 19 ++ .../registration_cubit.dart | 14 +- .../pages/city_of_living_screen.dart | 61 ++---- .../pages/registration_screen.dart | 2 +- .../repositories/registration_repository.dart | 9 + .../services/registration_service.dart | 6 + .../services/registration_service.g.dart | 27 +++ .../bloc/blog_post_create_bloc.dart | 6 +- 13 files changed, 345 insertions(+), 91 deletions(-) create mode 100644 lib/features/registration/models/location_model.dart create mode 100644 lib/features/registration/models/location_model.freezed.dart create mode 100644 lib/features/registration/models/location_model.g.dart diff --git a/lib/data/models/userRegistrationModel/user_registration_model.dart b/lib/data/models/userRegistrationModel/user_registration_model.dart index 5e30818..a86d064 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.dart @@ -15,8 +15,9 @@ class UserRegistrationSheet with _$UserRegistrationSheet { @Default('accepted') @JsonKey(name: 'terms') String termsAccepted, required String birthdate, required String gender, - required String country, - required String city, + required String location, + @JsonKey(name: 'response_body') + required String responseBody, required String lang, required int weight, required int height, diff --git a/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart b/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart index 4aa91df..70f656f 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart @@ -34,8 +34,9 @@ mixin _$UserRegistrationSheet { 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 location => throw _privateConstructorUsedError; + @JsonKey(name: 'response_body') + String get responseBody => throw _privateConstructorUsedError; String get lang => throw _privateConstructorUsedError; int get weight => throw _privateConstructorUsedError; int get height => throw _privateConstructorUsedError; @@ -90,8 +91,8 @@ abstract class $UserRegistrationSheetCopyWith<$Res> { @JsonKey(name: 'terms') String termsAccepted, String birthdate, String gender, - String country, - String city, + String location, + @JsonKey(name: 'response_body') String responseBody, String lang, int weight, int height, @@ -134,8 +135,8 @@ class _$UserRegistrationSheetCopyWithImpl<$Res, Object? termsAccepted = null, Object? birthdate = null, Object? gender = null, - Object? country = null, - Object? city = null, + Object? location = null, + Object? responseBody = null, Object? lang = null, Object? weight = null, Object? height = null, @@ -191,13 +192,13 @@ class _$UserRegistrationSheetCopyWithImpl<$Res, ? _value.gender : gender // ignore: cast_nullable_to_non_nullable as String, - country: null == country - ? _value.country - : country // ignore: cast_nullable_to_non_nullable + location: null == location + ? _value.location + : location // ignore: cast_nullable_to_non_nullable as String, - city: null == city - ? _value.city - : city // ignore: cast_nullable_to_non_nullable + responseBody: null == responseBody + ? _value.responseBody + : responseBody // ignore: cast_nullable_to_non_nullable as String, lang: null == lang ? _value.lang @@ -290,8 +291,8 @@ abstract class _$$UserRegistrationSheetImplCopyWith<$Res> @JsonKey(name: 'terms') String termsAccepted, String birthdate, String gender, - String country, - String city, + String location, + @JsonKey(name: 'response_body') String responseBody, String lang, int weight, int height, @@ -332,8 +333,8 @@ class __$$UserRegistrationSheetImplCopyWithImpl<$Res> Object? termsAccepted = null, Object? birthdate = null, Object? gender = null, - Object? country = null, - Object? city = null, + Object? location = null, + Object? responseBody = null, Object? lang = null, Object? weight = null, Object? height = null, @@ -389,13 +390,13 @@ class __$$UserRegistrationSheetImplCopyWithImpl<$Res> ? _value.gender : gender // ignore: cast_nullable_to_non_nullable as String, - country: null == country - ? _value.country - : country // ignore: cast_nullable_to_non_nullable + location: null == location + ? _value.location + : location // ignore: cast_nullable_to_non_nullable as String, - city: null == city - ? _value.city - : city // ignore: cast_nullable_to_non_nullable + responseBody: null == responseBody + ? _value.responseBody + : responseBody // ignore: cast_nullable_to_non_nullable as String, lang: null == lang ? _value.lang @@ -483,8 +484,8 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @JsonKey(name: 'terms') this.termsAccepted = 'accepted', required this.birthdate, required this.gender, - required this.country, - required this.city, + required this.location, + @JsonKey(name: 'response_body') required this.responseBody, required this.lang, required this.weight, required this.height, @@ -529,9 +530,10 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @override final String gender; @override - final String country; + final String location; @override - final String city; + @JsonKey(name: 'response_body') + final String responseBody; @override final String lang; @override @@ -583,7 +585,7 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @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)'; + return 'UserRegistrationSheet(name: $name, firstName: $firstName, lastName: $lastName, email: $email, password: $password, passwordConfirmation: $passwordConfirmation, termsAccepted: $termsAccepted, birthdate: $birthdate, gender: $gender, location: $location, responseBody: $responseBody, 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 @@ -606,8 +608,10 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { (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.location, location) || + other.location == location) && + (identical(other.responseBody, responseBody) || + other.responseBody == responseBody) && (identical(other.lang, lang) || other.lang == lang) && (identical(other.weight, weight) || other.weight == weight) && (identical(other.height, height) || other.height == height) && @@ -653,8 +657,8 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { termsAccepted, birthdate, gender, - country, - city, + location, + responseBody, lang, weight, height, @@ -701,8 +705,8 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { @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 location, + @JsonKey(name: 'response_body') required final String responseBody, required final String lang, required final int weight, required final int height, @@ -752,9 +756,10 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { @override String get gender; @override - String get country; + String get location; @override - String get city; + @JsonKey(name: 'response_body') + String get responseBody; @override String get lang; @override diff --git a/lib/data/models/userRegistrationModel/user_registration_model.g.dart b/lib/data/models/userRegistrationModel/user_registration_model.g.dart index 132240b..6ca8a1c 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.g.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.g.dart @@ -18,8 +18,8 @@ _$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson( 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, + location: json['location'] as String, + responseBody: json['response_body'] as String, lang: json['lang'] as String, weight: (json['weight'] as num).toInt(), height: (json['height'] as num).toInt(), @@ -52,8 +52,8 @@ Map _$$UserRegistrationSheetImplToJson( 'terms': instance.termsAccepted, 'birthdate': instance.birthdate, 'gender': instance.gender, - 'country': instance.country, - 'city': instance.city, + 'location': instance.location, + 'response_body': instance.responseBody, 'lang': instance.lang, 'weight': instance.weight, 'height': instance.height, diff --git a/lib/features/registration/models/location_model.dart b/lib/features/registration/models/location_model.dart new file mode 100644 index 0000000..3632a3e --- /dev/null +++ b/lib/features/registration/models/location_model.dart @@ -0,0 +1,15 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'location_model.g.dart'; +part 'location_model.freezed.dart'; + +@freezed +class LocationModel with _$LocationModel { + const factory LocationModel({ + required Map locations, + @JsonKey(name: 'response_body') + required String responseBody, +}) = _LocationModel; + + factory LocationModel.fromJson(Map json) => _$LocationModelFromJson(json); +} \ No newline at end of file diff --git a/lib/features/registration/models/location_model.freezed.dart b/lib/features/registration/models/location_model.freezed.dart new file mode 100644 index 0000000..71cbcb4 --- /dev/null +++ b/lib/features/registration/models/location_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 'location_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'); + +LocationModel _$LocationModelFromJson(Map json) { + return _LocationModel.fromJson(json); +} + +/// @nodoc +mixin _$LocationModel { + Map get locations => throw _privateConstructorUsedError; + @JsonKey(name: 'response_body') + String get responseBody => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $LocationModelCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $LocationModelCopyWith<$Res> { + factory $LocationModelCopyWith( + LocationModel value, $Res Function(LocationModel) then) = + _$LocationModelCopyWithImpl<$Res, LocationModel>; + @useResult + $Res call( + {Map locations, + @JsonKey(name: 'response_body') String responseBody}); +} + +/// @nodoc +class _$LocationModelCopyWithImpl<$Res, $Val extends LocationModel> + implements $LocationModelCopyWith<$Res> { + _$LocationModelCopyWithImpl(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? locations = null, + Object? responseBody = null, + }) { + return _then(_value.copyWith( + locations: null == locations + ? _value.locations + : locations // ignore: cast_nullable_to_non_nullable + as Map, + responseBody: null == responseBody + ? _value.responseBody + : responseBody // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$LocationModelImplCopyWith<$Res> + implements $LocationModelCopyWith<$Res> { + factory _$$LocationModelImplCopyWith( + _$LocationModelImpl value, $Res Function(_$LocationModelImpl) then) = + __$$LocationModelImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {Map locations, + @JsonKey(name: 'response_body') String responseBody}); +} + +/// @nodoc +class __$$LocationModelImplCopyWithImpl<$Res> + extends _$LocationModelCopyWithImpl<$Res, _$LocationModelImpl> + implements _$$LocationModelImplCopyWith<$Res> { + __$$LocationModelImplCopyWithImpl( + _$LocationModelImpl _value, $Res Function(_$LocationModelImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? locations = null, + Object? responseBody = null, + }) { + return _then(_$LocationModelImpl( + locations: null == locations + ? _value._locations + : locations // ignore: cast_nullable_to_non_nullable + as Map, + responseBody: null == responseBody + ? _value.responseBody + : responseBody // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$LocationModelImpl implements _LocationModel { + const _$LocationModelImpl( + {required final Map locations, + @JsonKey(name: 'response_body') required this.responseBody}) + : _locations = locations; + + factory _$LocationModelImpl.fromJson(Map json) => + _$$LocationModelImplFromJson(json); + + final Map _locations; + @override + Map get locations { + if (_locations is EqualUnmodifiableMapView) return _locations; + // ignore: implicit_dynamic_type + return EqualUnmodifiableMapView(_locations); + } + + @override + @JsonKey(name: 'response_body') + final String responseBody; + + @override + String toString() { + return 'LocationModel(locations: $locations, responseBody: $responseBody)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LocationModelImpl && + const DeepCollectionEquality() + .equals(other._locations, _locations) && + (identical(other.responseBody, responseBody) || + other.responseBody == responseBody)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, + const DeepCollectionEquality().hash(_locations), responseBody); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$LocationModelImplCopyWith<_$LocationModelImpl> get copyWith => + __$$LocationModelImplCopyWithImpl<_$LocationModelImpl>(this, _$identity); + + @override + Map toJson() { + return _$$LocationModelImplToJson( + this, + ); + } +} + +abstract class _LocationModel implements LocationModel { + const factory _LocationModel( + {required final Map locations, + @JsonKey(name: 'response_body') required final String responseBody}) = + _$LocationModelImpl; + + factory _LocationModel.fromJson(Map json) = + _$LocationModelImpl.fromJson; + + @override + Map get locations; + @override + @JsonKey(name: 'response_body') + String get responseBody; + @override + @JsonKey(ignore: true) + _$$LocationModelImplCopyWith<_$LocationModelImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/registration/models/location_model.g.dart b/lib/features/registration/models/location_model.g.dart new file mode 100644 index 0000000..04a199f --- /dev/null +++ b/lib/features/registration/models/location_model.g.dart @@ -0,0 +1,19 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'location_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$LocationModelImpl _$$LocationModelImplFromJson(Map json) => + _$LocationModelImpl( + locations: json['locations'] as Map, + responseBody: json['response_body'] as String, + ); + +Map _$$LocationModelImplToJson(_$LocationModelImpl instance) => + { + 'locations': instance.locations, + 'response_body': instance.responseBody, + }; diff --git a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart index f9e767f..af81fda 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart @@ -21,8 +21,8 @@ class RegistrationCubit extends Cubit { passwordConfirmation: '', birthdate: '', gender: '', - country: '', - city: '', + location: '', + responseBody: '', lang: '', weight: 0, height: 0, @@ -54,4 +54,14 @@ class RegistrationCubit extends Cubit { rethrow; } } + + Future> getLocationsByQuery(String query) async { + try { + final location = (await registrationRepository.getLocationsListByQuery(query)); + emit(RegistrationState(sheet: state.sheet.copyWith(responseBody: location.responseBody))); + return location.locations.values.toList().map((e) => e.toString()).toList(); + } catch (e) { + rethrow; + } + } } diff --git a/lib/features/registration/presentation/pages/city_of_living_screen.dart b/lib/features/registration/presentation/pages/city_of_living_screen.dart index 02e5c65..0a3dd29 100644 --- a/lib/features/registration/presentation/pages/city_of_living_screen.dart +++ b/lib/features/registration/presentation/pages/city_of_living_screen.dart @@ -1,8 +1,6 @@ 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:eatvio_app/widgets/custom_edit_text_form_field.dart'; import 'package:flutter/material.dart'; import 'package:flutter_typeahead/flutter_typeahead.dart'; @@ -27,15 +25,8 @@ class _CityOfLivingScreenState extends State { @override void initState() { super.initState(); - if (widget.sheet.country.isNotEmpty) { - selectedItem = dropdownItemList.firstWhere((item) => item.title == widget.sheet.country); - } else { - selectedItem = dropdownItemList.first; - final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(country: selectedItem.title)); - } - if (widget.sheet.city.isNotEmpty) { - cityController.text = widget.sheet.city; + if (widget.sheet.location.isNotEmpty) { + cityController.text = widget.sheet.location; } } @@ -46,39 +37,19 @@ class _CityOfLivingScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text("country".tr), - SizedBox(height: 4), - 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: 16), - Text("Населенный пункт"), + Text("Местоположение"), SizedBox(height: 4), TypeAheadField( - debounceDuration: Duration.zero, + debounceDuration: Duration(milliseconds: 300), controller: cityController, builder: (context, controller, focus) => CustomTextFormField( - controller: cityController, - focusNode: focus, - textStyle: TextStyle( - fontSize: 16, - color: Colors.black, - ) - ), + controller: cityController, + focusNode: focus, + autofocus: true, + textStyle: TextStyle( + fontSize: 16, + color: Colors.black, + )), itemBuilder: (BuildContext context, String item) { return Padding( padding: const EdgeInsets.all(8.0), @@ -96,10 +67,14 @@ class _CityOfLivingScreenState extends State { cityController.text = item; }); final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(city: item)); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(location: item)); }, - suggestionsCallback: (query) { - return citiesList.where((country) => country.toLowerCase().contains(query.toLowerCase())).toList(); + suggestionsCallback: (query) async { + if (query.length >= 3) { + final registrationCubit = context.read(); + return (await registrationCubit.getLocationsByQuery(query)); + } + return null; }, ), ], diff --git a/lib/features/registration/presentation/pages/registration_screen.dart b/lib/features/registration/presentation/pages/registration_screen.dart index 1688ef2..0856290 100644 --- a/lib/features/registration/presentation/pages/registration_screen.dart +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -244,7 +244,7 @@ class _RegistrationScreenState extends State { return false; } case 6: - if (state.sheet.country.isNotEmpty && state.sheet.city.isNotEmpty) + if (state.sheet.location.isNotEmpty) return true; else { showDialog( diff --git a/lib/features/registration/repositories/registration_repository.dart b/lib/features/registration/repositories/registration_repository.dart index aa38880..31a1ff1 100644 --- a/lib/features/registration/repositories/registration_repository.dart +++ b/lib/features/registration/repositories/registration_repository.dart @@ -1,4 +1,5 @@ import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_model.dart'; +import 'package:eatvio_app/features/registration/models/location_model.dart'; import 'package:eatvio_app/features/registration/services/registration_service.dart'; class RegistrationRepository { @@ -13,4 +14,12 @@ class RegistrationRepository { rethrow; } } + + Future getLocationsListByQuery(String query) async { + try { + return (await registrationService.getLocations(query: query)); + } catch (e) { + rethrow; + } + } } diff --git a/lib/features/registration/services/registration_service.dart b/lib/features/registration/services/registration_service.dart index fefca6a..af4bd83 100644 --- a/lib/features/registration/services/registration_service.dart +++ b/lib/features/registration/services/registration_service.dart @@ -1,4 +1,5 @@ import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/registration/models/location_model.dart'; import 'package:retrofit/retrofit.dart'; part 'registration_service.g.dart'; @@ -11,4 +12,9 @@ abstract class RegistrationService { Future> register({ @Body() required Map sheet, }); + + @GET('/api/locations') + Future getLocations({ + @Query('user_address') required String query, + }); } diff --git a/lib/features/registration/services/registration_service.g.dart b/lib/features/registration/services/registration_service.g.dart index 269d16c..6c9ce5b 100644 --- a/lib/features/registration/services/registration_service.g.dart +++ b/lib/features/registration/services/registration_service.g.dart @@ -47,6 +47,33 @@ class _RegistrationService implements RegistrationService { return _value; } + @override + Future getLocations({required String query}) async { + final _extra = {}; + final queryParameters = {r'user_address': query}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio + .fetch>(_setStreamType(Options( + method: 'GET', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/api/locations', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = LocationModel.fromJson(_result.data!); + return _value; + } + RequestOptions _setStreamType(RequestOptions requestOptions) { if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || 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 654e963..184938a 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 @@ -72,9 +72,7 @@ class BlogPostCreateBloc extends Bloc if (response.statusCode == 200 || response.statusCode == 201) { AppRouter.navigatorKey.currentContext?.goNamed('feedScreen'); } else { - print( - 'Failed to create blog post. Status Code: ${response.statusCode} ${response.data}', - ); + print('Failed to create blog post. Status Code: ${response.statusCode} ${response.data}'); } } } @@ -85,7 +83,7 @@ class BlogPostCreateBloc extends Bloc FormData formData = FormData.fromMap({ 'title': title, 'description': description, - 'videoUrl': youtubeURL, + 'youtube_url': youtubeURL, 'state': 'active', 'image': await MultipartFile.fromFile(image!.path, filename: image.name), }); -- 2.49.1 From f96c6b53d6e02fab2d1da56539a53751f7300e1d Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Mon, 29 Jul 2024 11:20:01 +0300 Subject: [PATCH 081/110] feature(registration): fix location model --- .../registration/models/location_model.dart | 10 ++++---- .../models/location_model.freezed.dart | 24 +++++++++---------- .../registration/models/location_model.g.dart | 3 ++- .../registration_cubit.dart | 2 +- 4 files changed, 20 insertions(+), 19 deletions(-) diff --git a/lib/features/registration/models/location_model.dart b/lib/features/registration/models/location_model.dart index 3632a3e..cc6b107 100644 --- a/lib/features/registration/models/location_model.dart +++ b/lib/features/registration/models/location_model.dart @@ -1,15 +1,15 @@ import 'package:freezed_annotation/freezed_annotation.dart'; part 'location_model.g.dart'; + part 'location_model.freezed.dart'; @freezed class LocationModel with _$LocationModel { const factory LocationModel({ - required Map locations, - @JsonKey(name: 'response_body') - required String responseBody, -}) = _LocationModel; + required List locations, + @JsonKey(name: 'response_body') required String responseBody, + }) = _LocationModel; factory LocationModel.fromJson(Map json) => _$LocationModelFromJson(json); -} \ No newline at end of file +} diff --git a/lib/features/registration/models/location_model.freezed.dart b/lib/features/registration/models/location_model.freezed.dart index 71cbcb4..f640ca2 100644 --- a/lib/features/registration/models/location_model.freezed.dart +++ b/lib/features/registration/models/location_model.freezed.dart @@ -20,7 +20,7 @@ LocationModel _$LocationModelFromJson(Map json) { /// @nodoc mixin _$LocationModel { - Map get locations => throw _privateConstructorUsedError; + List get locations => throw _privateConstructorUsedError; @JsonKey(name: 'response_body') String get responseBody => throw _privateConstructorUsedError; @@ -37,7 +37,7 @@ abstract class $LocationModelCopyWith<$Res> { _$LocationModelCopyWithImpl<$Res, LocationModel>; @useResult $Res call( - {Map locations, + {List locations, @JsonKey(name: 'response_body') String responseBody}); } @@ -61,7 +61,7 @@ class _$LocationModelCopyWithImpl<$Res, $Val extends LocationModel> locations: null == locations ? _value.locations : locations // ignore: cast_nullable_to_non_nullable - as Map, + as List, responseBody: null == responseBody ? _value.responseBody : responseBody // ignore: cast_nullable_to_non_nullable @@ -79,7 +79,7 @@ abstract class _$$LocationModelImplCopyWith<$Res> @override @useResult $Res call( - {Map locations, + {List locations, @JsonKey(name: 'response_body') String responseBody}); } @@ -101,7 +101,7 @@ class __$$LocationModelImplCopyWithImpl<$Res> locations: null == locations ? _value._locations : locations // ignore: cast_nullable_to_non_nullable - as Map, + as List, responseBody: null == responseBody ? _value.responseBody : responseBody // ignore: cast_nullable_to_non_nullable @@ -114,19 +114,19 @@ class __$$LocationModelImplCopyWithImpl<$Res> @JsonSerializable() class _$LocationModelImpl implements _LocationModel { const _$LocationModelImpl( - {required final Map locations, + {required final List locations, @JsonKey(name: 'response_body') required this.responseBody}) : _locations = locations; factory _$LocationModelImpl.fromJson(Map json) => _$$LocationModelImplFromJson(json); - final Map _locations; + final List _locations; @override - Map get locations { - if (_locations is EqualUnmodifiableMapView) return _locations; + List get locations { + if (_locations is EqualUnmodifiableListView) return _locations; // ignore: implicit_dynamic_type - return EqualUnmodifiableMapView(_locations); + return EqualUnmodifiableListView(_locations); } @override @@ -170,7 +170,7 @@ class _$LocationModelImpl implements _LocationModel { abstract class _LocationModel implements LocationModel { const factory _LocationModel( - {required final Map locations, + {required final List locations, @JsonKey(name: 'response_body') required final String responseBody}) = _$LocationModelImpl; @@ -178,7 +178,7 @@ abstract class _LocationModel implements LocationModel { _$LocationModelImpl.fromJson; @override - Map get locations; + List get locations; @override @JsonKey(name: 'response_body') String get responseBody; diff --git a/lib/features/registration/models/location_model.g.dart b/lib/features/registration/models/location_model.g.dart index 04a199f..449630a 100644 --- a/lib/features/registration/models/location_model.g.dart +++ b/lib/features/registration/models/location_model.g.dart @@ -8,7 +8,8 @@ part of 'location_model.dart'; _$LocationModelImpl _$$LocationModelImplFromJson(Map json) => _$LocationModelImpl( - locations: json['locations'] as Map, + locations: + (json['locations'] as List).map((e) => e as String).toList(), responseBody: json['response_body'] as String, ); diff --git a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart index af81fda..c8aef3f 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart @@ -59,7 +59,7 @@ class RegistrationCubit extends Cubit { try { final location = (await registrationRepository.getLocationsListByQuery(query)); emit(RegistrationState(sheet: state.sheet.copyWith(responseBody: location.responseBody))); - return location.locations.values.toList().map((e) => e.toString()).toList(); + return location.locations; } catch (e) { rethrow; } -- 2.49.1 From 2b3a3a0e93d684ef5a5ed21aa00159759d14b177 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Mon, 29 Jul 2024 15:55:48 +0300 Subject: [PATCH 082/110] feature(blogPosts): refactor main screen --- lib/app_router.dart | 4 +- .../chat_select_screen.dart | 1 - .../presentation/pages/feed_screen_new.dart | 211 ++++++++++++++++++ .../widgets/blog_post_widget.dart | 129 +++++++++++ .../repositories/registration_repository.dart | 2 +- .../services/registration_service.dart | 10 +- .../services/registration_service.g.dart | 37 ++- 7 files changed, 386 insertions(+), 8 deletions(-) create mode 100644 lib/features/feed/presentation/pages/feed_screen_new.dart create mode 100644 lib/features/feed/presentation/widgets/blog_post_widget.dart diff --git a/lib/app_router.dart b/lib/app_router.dart index 9c23dd0..4cddc6e 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -6,7 +6,7 @@ import 'package:eatvio_app/features/bottom_navigation_bar/presentation/widgets/b 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/feed/presentation/pages/feed_screen_new.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'; @@ -64,7 +64,7 @@ class AppRouter { GoRoute( path: '/feed-screen', name: 'feedScreen', - builder: (context, state) => FeedScreen(), + builder: (context, state) => FeedScreenNew(), routes: [ GoRoute( path: 'blog-post-create-screen', 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 3df79df..32258da 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 @@ -37,7 +37,6 @@ class ChatSelectScreen extends StatelessWidget { return Scaffold( appBar: AppBar( backgroundColor: Colors.white, - forceMaterialTransparency: true, toolbarHeight: 0, ), body: NestedScrollView( diff --git a/lib/features/feed/presentation/pages/feed_screen_new.dart b/lib/features/feed/presentation/pages/feed_screen_new.dart new file mode 100644 index 0000000..e1f1b15 --- /dev/null +++ b/lib/features/feed/presentation/pages/feed_screen_new.dart @@ -0,0 +1,211 @@ +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:eatvio_app/features/feed/presentation/widgets/blog_post_widget.dart'; +import 'package:eatvio_app/theme/theme_helper.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +class FeedScreenNew extends StatefulWidget { + const FeedScreenNew({super.key}); + + @override + State createState() => _FeedScreenNewState(); +} + +class _FeedScreenNewState extends State { + final List chipsLabelList = ['Все', 'Рецепты', 'Диеты', 'Планы питания', 'Консультанты']; + + int _selectedChipIndex = 0; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: Colors.white, + toolbarHeight: 0, + systemOverlayStyle: SystemUiOverlayStyle( + statusBarColor: Colors.white, + ), + ), + backgroundColor: Colors.grey.shade200, + body: NestedScrollView( + headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { + return [ + SliverAppBar( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(bottom: Radius.circular(12)), + ), + backgroundColor: Colors.white, + foregroundColor: Colors.white, + automaticallyImplyLeading: false, + stretchTriggerOffset: 1, + floating: true, + snap: true, + bottom: _chipGroup(), + title: Row( + children: [ + _searchBar(), + SizedBox(width: 12), + _addBlogPostButton(), + ], + ), + ), + ]; + }, + body: _buildAllBlogPosts(), + ), + ); + } + + _buildAllBlogPosts() { + return Expanded( + child: BlocBuilder( + builder: (BuildContext context, FeedState state) { + if (state is FeedStateLoaded) { + return ListView.separated( + padding: EdgeInsets.symmetric(vertical: 8), + shrinkWrap: true, + physics: BouncingScrollPhysics(), + itemBuilder: (context, index) { + return BlogPostWidget(feedBlogPostModel: state.feedBlogPostList[index]); + }, + separatorBuilder: (context, index) { + return SizedBox(height: 8); + }, + itemCount: state.feedBlogPostList.length, + ); + } else if (state is FeedStateError) { + return Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: Center( + child: Text(state.errorMessage), + ), + ), + ); + } else { + return Scaffold( + body: Center( + child: CupertinoActivityIndicator(), + ), + ); + } + }, + ), + ); + } + + _chipGroup() { + return PreferredSize( + preferredSize: Size(MediaQuery.of(context).size.width, 32), + child: Align( + alignment: Alignment.centerLeft, + child: SingleChildScrollView( + padding: EdgeInsets.symmetric(horizontal: 16), + scrollDirection: Axis.horizontal, + child: Row( + children: [ + _choiceChipWidget(0), + SizedBox(width: 8), + _choiceChipWidget(1), + SizedBox(width: 8), + _choiceChipWidget(2), + SizedBox(width: 8), + _choiceChipWidget(3), + SizedBox(width: 8), + _choiceChipWidget(4), + ], + ), + ), + ), + ); + } + + _addBlogPostButton() { + return InkWell( + onTap: () {}, + borderRadius: BorderRadius.circular(64), + child: Ink( + decoration: BoxDecoration( + color: appTheme.blueA400, + shape: BoxShape.circle, + ), + child: Icon( + Icons.add_rounded, + color: appTheme.gray100, + ), + width: 40, + height: 40, + ), + ); + } + + _searchBar() { + return SizedBox( + height: 40, + width: MediaQuery.of(context).size.width - 84, + child: TextFormField( + style: TextStyle( + fontSize: 12, + ), + decoration: InputDecoration( + hintText: 'Поиск', + hintStyle: TextStyle( + fontSize: 12, + color: appTheme.gray600, + fontWeight: FontWeight.w400, + ), + prefixIcon: Icon( + Icons.search, + color: appTheme.gray600, + size: 16, + ), + isDense: false, + contentPadding: EdgeInsets.all(8), + fillColor: appTheme.gray100, + filled: true, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(16), + borderSide: BorderSide.none, + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(16), + borderSide: BorderSide.none, + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(16), + borderSide: BorderSide.none, + ), + ), + ), + ); + } + + _choiceChipWidget(int index) { + return ChoiceChip( + selectedColor: appTheme.blueA400, + pressElevation: 0, + showCheckmark: false, + side: BorderSide.none, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + label: Text(chipsLabelList[index]), + labelStyle: TextStyle( + color: index == _selectedChipIndex ? Colors.white : appTheme.gray600, + fontWeight: FontWeight.w500, + fontSize: 12, + ), + selected: _selectedChipIndex == index, + backgroundColor: appTheme.gray100, + onSelected: (bool selected) { + setState(() { + _selectedChipIndex = index; + }); + }, + ); + } +} diff --git a/lib/features/feed/presentation/widgets/blog_post_widget.dart b/lib/features/feed/presentation/widgets/blog_post_widget.dart new file mode 100644 index 0000000..b7d26df --- /dev/null +++ b/lib/features/feed/presentation/widgets/blog_post_widget.dart @@ -0,0 +1,129 @@ +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:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; +import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; +import 'package:flutter/material.dart'; + +class BlogPostWidget extends StatefulWidget { + final FeedBlogPostModel feedBlogPostModel; + + const BlogPostWidget({super.key, required this.feedBlogPostModel}); + + @override + State createState() => _BlogPostWidgetState(); +} + +class _BlogPostWidgetState extends State { + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: () {}, + child: Ink( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + color: Colors.white, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 12), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Row( + children: [ + CircleAvatar(radius: 20), + SizedBox(width: 8), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Имя автора'), + Text('Время поста'), + ], + ), + ], + ), + ), + SizedBox(height: 12), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Text(widget.feedBlogPostModel.title), + ), + SizedBox(height: 8), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Text(widget.feedBlogPostModel.description), + ), + SizedBox(height: 8), + GestureDetector( + onTap: () { + context.pushTransparentRoute( + rootNavigator: true, + PhotoViewScreen( + imageUrls: [baseUrl + '/storage/' + widget.feedBlogPostModel.image], + index: 0, + ), + ); + }, + child: Hero( + tag: baseUrl + '/storage/' + widget.feedBlogPostModel.image, + child: CachedNetworkImage( + imageUrl: baseUrl + '/storage/' + widget.feedBlogPostModel.image, + ), + ), + ), + SizedBox(height: 8), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Row( + children: [ + _iconButton(Icons.favorite_border_rounded), + SizedBox(width: 8), + _iconButton(Icons.mode_comment_outlined), + SizedBox(width: 8), + _iconButton(Icons.reply_rounded), + ], + ), + ), + SizedBox(height: 8), + ], + ), + ), + ); + } + + _iconButton(IconData icon, [String? text]) { + return InkWell( + onTap: () {}, + borderRadius: BorderRadius.circular(16), + child: Ink( + padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4), + decoration: BoxDecoration( + color: appTheme.gray100, + borderRadius: BorderRadius.circular(16), + ), + height: 32, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + icon, + size: 20, + color: appTheme.gray600, + ), + if (text != null) SizedBox(width: 8), + if (text != null) + Text( + text, + style: TextStyle( + color: appTheme.gray600, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/registration/repositories/registration_repository.dart b/lib/features/registration/repositories/registration_repository.dart index 31a1ff1..a96a32f 100644 --- a/lib/features/registration/repositories/registration_repository.dart +++ b/lib/features/registration/repositories/registration_repository.dart @@ -17,7 +17,7 @@ class RegistrationRepository { Future getLocationsListByQuery(String query) async { try { - return (await registrationService.getLocations(query: query)); + return (await registrationService.getLocationsByAddress(query: query)); } catch (e) { rethrow; } diff --git a/lib/features/registration/services/registration_service.dart b/lib/features/registration/services/registration_service.dart index af4bd83..08a23a0 100644 --- a/lib/features/registration/services/registration_service.dart +++ b/lib/features/registration/services/registration_service.dart @@ -13,8 +13,14 @@ abstract class RegistrationService { @Body() required Map sheet, }); - @GET('/api/locations') - Future getLocations({ + @GET('/api/location_by_address') + Future getLocationsByAddress({ @Query('user_address') required String query, }); + + @GET('/api/api/location_by_coordinate') + Future getLocationsByCoordinate({ + @Query('coordinate[position][latitude]') required String latitude, + @Query('coordinate[position][longitude]') required String longitude, + }); } diff --git a/lib/features/registration/services/registration_service.g.dart b/lib/features/registration/services/registration_service.g.dart index 6c9ce5b..9cd29f3 100644 --- a/lib/features/registration/services/registration_service.g.dart +++ b/lib/features/registration/services/registration_service.g.dart @@ -48,7 +48,7 @@ class _RegistrationService implements RegistrationService { } @override - Future getLocations({required String query}) async { + Future getLocationsByAddress({required String query}) async { final _extra = {}; final queryParameters = {r'user_address': query}; final _headers = {}; @@ -61,7 +61,40 @@ class _RegistrationService implements RegistrationService { ) .compose( _dio.options, - '/api/locations', + '/api/location_by_address', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = LocationModel.fromJson(_result.data!); + return _value; + } + + @override + Future getLocationsByCoordinate({ + required String latitude, + required String longitude, + }) async { + final _extra = {}; + final queryParameters = { + r'coordinate[position][latitude]': latitude, + r'coordinate[position][longitude]': longitude, + }; + final _headers = {}; + const Map? _data = null; + final _result = await _dio + .fetch>(_setStreamType(Options( + method: 'GET', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/api/api/location_by_coordinate', queryParameters: queryParameters, data: _data, ) -- 2.49.1 From 3af1318d1ce8a15dfd422b866f3abbc8d196bc9d Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Mon, 29 Jul 2024 16:14:48 +0300 Subject: [PATCH 083/110] feature(blogPosts): fix grey screen --- .../chat_select_screen.dart | 2 +- .../presentation/pages/feed_screen_new.dart | 65 +++++++++---------- 2 files changed, 33 insertions(+), 34 deletions(-) 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 32258da..5bbd1d7 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 @@ -47,7 +47,7 @@ class ChatSelectScreen extends StatelessWidget { sliver: SliverAppBar( automaticallyImplyLeading: false, stretchTriggerOffset: 1, - forceMaterialTransparency: true, + scrolledUnderElevation: 0, floating: true, snap: true, title: Padding( diff --git a/lib/features/feed/presentation/pages/feed_screen_new.dart b/lib/features/feed/presentation/pages/feed_screen_new.dart index e1f1b15..bdd2476 100644 --- a/lib/features/feed/presentation/pages/feed_screen_new.dart +++ b/lib/features/feed/presentation/pages/feed_screen_new.dart @@ -43,6 +43,7 @@ class _FeedScreenNewState extends State { stretchTriggerOffset: 1, floating: true, snap: true, + scrolledUnderElevation: 0, bottom: _chipGroup(), title: Row( children: [ @@ -60,40 +61,38 @@ class _FeedScreenNewState extends State { } _buildAllBlogPosts() { - return Expanded( - child: BlocBuilder( - builder: (BuildContext context, FeedState state) { - if (state is FeedStateLoaded) { - return ListView.separated( - padding: EdgeInsets.symmetric(vertical: 8), - shrinkWrap: true, - physics: BouncingScrollPhysics(), - itemBuilder: (context, index) { - return BlogPostWidget(feedBlogPostModel: state.feedBlogPostList[index]); - }, - separatorBuilder: (context, index) { - return SizedBox(height: 8); - }, - itemCount: state.feedBlogPostList.length, - ); - } else if (state is FeedStateError) { - return Scaffold( - body: Padding( - padding: const EdgeInsets.all(16), - child: Center( - child: Text(state.errorMessage), - ), + return BlocBuilder( + builder: (BuildContext context, FeedState state) { + if (state is FeedStateLoaded) { + return ListView.separated( + padding: EdgeInsets.symmetric(vertical: 8), + shrinkWrap: true, + physics: BouncingScrollPhysics(), + itemBuilder: (context, index) { + return BlogPostWidget(feedBlogPostModel: state.feedBlogPostList[index]); + }, + separatorBuilder: (context, index) { + return SizedBox(height: 8); + }, + itemCount: state.feedBlogPostList.length, + ); + } else if (state is FeedStateError) { + return Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: Center( + child: Text(state.errorMessage), ), - ); - } else { - return Scaffold( - body: Center( - child: CupertinoActivityIndicator(), - ), - ); - } - }, - ), + ), + ); + } else { + return Scaffold( + body: Center( + child: CupertinoActivityIndicator(), + ), + ); + } + }, ); } -- 2.49.1 From e6b1218199eaddd75ca8b5909ce3627834b51a79 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Wed, 31 Jul 2024 11:36:03 +0300 Subject: [PATCH 084/110] feat(registration): add location by coordinates --- android/app/src/main/AndroidManifest.xml | 8 +- android/build.gradle | 2 +- android/settings.gradle | 4 +- ios/Runner/Info.plist | 2 + .../registration_cubit.dart | 10 ++ .../pages/city_of_living_screen.dart | 152 +++++++++++++----- .../repositories/registration_repository.dart | 8 + .../services/registration_service.dart | 2 +- .../services/registration_service.g.dart | 2 +- pubspec.yaml | 1 + 10 files changed, 143 insertions(+), 48 deletions(-) diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 435e017..516dace 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,13 +1,9 @@ - - + + NSAllowsArbitraryLoads + NSLocationWhenInUseUsageDescription + diff --git a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart index c8aef3f..dcad030 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart @@ -64,4 +64,14 @@ class RegistrationCubit extends Cubit { rethrow; } } + + Future> getLocationsByCoordinates(String latitude, String longitude) async { + try { + final location = (await registrationRepository.getLocationsListByCoordinates(latitude, longitude)); + emit(RegistrationState(sheet: state.sheet.copyWith(responseBody: location.responseBody))); + return location.locations; + } catch (e) { + rethrow; + } + } } diff --git a/lib/features/registration/presentation/pages/city_of_living_screen.dart b/lib/features/registration/presentation/pages/city_of_living_screen.dart index 0a3dd29..808c0cc 100644 --- a/lib/features/registration/presentation/pages/city_of_living_screen.dart +++ b/lib/features/registration/presentation/pages/city_of_living_screen.dart @@ -2,8 +2,10 @@ 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_edit_text_form_field.dart'; +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_typeahead/flutter_typeahead.dart'; +import 'package:location/location.dart'; class CityOfLivingScreen extends StatefulWidget { final UserRegistrationSheet sheet; @@ -21,6 +23,8 @@ class _CityOfLivingScreenState extends State { late SelectionPopupModel selectedItem; final cityController = TextEditingController(); + final suggestionsController = SuggestionsController(); + bool isLoading = false; @override void initState() { @@ -30,6 +34,34 @@ class _CityOfLivingScreenState extends State { } } + Future getLocationData() async { + Location location = new Location(); + + bool _serviceEnabled; + PermissionStatus _permissionGranted; + LocationData _locationData; + + _serviceEnabled = await location.serviceEnabled(); + if (!_serviceEnabled) { + _serviceEnabled = await location.requestService(); + if (!_serviceEnabled) { + return null; + } + } + + _permissionGranted = await location.hasPermission(); + if (_permissionGranted == PermissionStatus.denied) { + _permissionGranted = await location.requestPermission(); + if (_permissionGranted != PermissionStatus.granted) { + return null; + } + } + + _locationData = await location.getLocation(); + + return _locationData; + } + @override Widget build(BuildContext context) { return SingleChildScrollView( @@ -39,43 +71,89 @@ class _CityOfLivingScreenState extends State { children: [ Text("Местоположение"), SizedBox(height: 4), - TypeAheadField( - debounceDuration: Duration(milliseconds: 300), - controller: cityController, - builder: (context, controller, focus) => CustomTextFormField( - controller: cityController, - focusNode: focus, - autofocus: true, - textStyle: TextStyle( - fontSize: 16, - color: Colors.black, - )), - itemBuilder: (BuildContext context, String item) { - return Padding( - padding: const EdgeInsets.all(8.0), - child: Text(item, style: theme.textTheme.bodyLarge?.copyWith(color: Colors.black)), - ); - }, - decorationBuilder: (context, child) => Material( - type: MaterialType.card, - elevation: 4, - borderRadius: BorderRadius.circular(8), - child: child, - ), - onSelected: (item) { - setState(() { - cityController.text = item; - }); - final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(location: item)); - }, - suggestionsCallback: (query) async { - if (query.length >= 3) { - final registrationCubit = context.read(); - return (await registrationCubit.getLocationsByQuery(query)); - } - return null; - }, + Row( + children: [ + SizedBox( + width: MediaQuery.of(context).size.width - 80, + child: TypeAheadField( + debounceDuration: Duration(milliseconds: 300), + controller: cityController, + suggestionsController: suggestionsController, + builder: (context, controller, focus) => CustomTextFormField( + controller: cityController, + focusNode: focus, + autofocus: true, + textStyle: TextStyle( + fontSize: 16, + color: Colors.black, + )), + itemBuilder: (BuildContext context, String item) { + return Padding( + padding: const EdgeInsets.all(8.0), + child: Text(item, style: theme.textTheme.bodyLarge?.copyWith(color: Colors.black)), + ); + }, + decorationBuilder: (context, child) => Material( + type: MaterialType.card, + elevation: 4, + borderRadius: BorderRadius.circular(8), + child: child, + ), + onSelected: (item) { + setState(() { + cityController.text = item; + }); + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(location: item)); + }, + suggestionsCallback: (query) async { + if (query.length >= 3) { + final registrationCubit = context.read(); + return (await registrationCubit.getLocationsByQuery(query)); + } + return null; + }, + ), + ), + SizedBox(width: 8), + InkWell( + borderRadius: BorderRadius.circular(8), + onTap: !isLoading + ? () async { + setState(() { + isLoading = true; + }); + final LocationData? locationData = await getLocationData(); + if (locationData != null) { + final List locations = await context + .read() + .getLocationsByCoordinates(locationData.latitude.toString(), locationData.longitude.toString()); + setState(() { + cityController.text = locations.first; + suggestionsController.suggestions = locations; + }); + } + setState(() { + isLoading = false; + }); + } + : null, + child: Ink( + height: 40, + width: 40, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(8), + color: Color(0xFFEAF2FD), + ), + child: !isLoading + ? Icon( + Icons.near_me_rounded, + color: appTheme.blueA400, + ) + : CupertinoActivityIndicator(), + ), + ), + ], ), ], ), diff --git a/lib/features/registration/repositories/registration_repository.dart b/lib/features/registration/repositories/registration_repository.dart index a96a32f..d609ee1 100644 --- a/lib/features/registration/repositories/registration_repository.dart +++ b/lib/features/registration/repositories/registration_repository.dart @@ -22,4 +22,12 @@ class RegistrationRepository { rethrow; } } + + Future getLocationsListByCoordinates(String latitude, String longitude) async { + try { + return (await registrationService.getLocationsByCoordinate(latitude: latitude, longitude: longitude)); + } catch (e) { + rethrow; + } + } } diff --git a/lib/features/registration/services/registration_service.dart b/lib/features/registration/services/registration_service.dart index 08a23a0..200c2f6 100644 --- a/lib/features/registration/services/registration_service.dart +++ b/lib/features/registration/services/registration_service.dart @@ -18,7 +18,7 @@ abstract class RegistrationService { @Query('user_address') required String query, }); - @GET('/api/api/location_by_coordinate') + @GET('/api/location_by_coordinate') Future getLocationsByCoordinate({ @Query('coordinate[position][latitude]') required String latitude, @Query('coordinate[position][longitude]') required String longitude, diff --git a/lib/features/registration/services/registration_service.g.dart b/lib/features/registration/services/registration_service.g.dart index 9cd29f3..9820fd3 100644 --- a/lib/features/registration/services/registration_service.g.dart +++ b/lib/features/registration/services/registration_service.g.dart @@ -94,7 +94,7 @@ class _RegistrationService implements RegistrationService { ) .compose( _dio.options, - '/api/api/location_by_coordinate', + '/api/location_by_coordinate', queryParameters: queryParameters, data: _data, ) diff --git a/pubspec.yaml b/pubspec.yaml index 2cdbe59..110e8fc 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -44,6 +44,7 @@ dependencies: lazy_load_scrollview: ^1.3.0 badges: ^3.1.2 google_fonts: ^6.2.1 + location: ^7.0.0 dev_dependencies: build_runner: ^2.4.11 -- 2.49.1 From a2360a1c1926a5d34c917822f1b4f65c47c057ff Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 31 Jul 2024 12:21:17 +0300 Subject: [PATCH 085/110] feat(diary): Nutrition chart looks like half-donut --- .../presentation/pages/calendar_screen.dart | 41 +++-- .../diary/presentation/bloc/diary_bloc.dart | 54 ++++-- .../presentation/pages/diary_screen.dart | 161 +++++++++++++----- .../diary/repositories/diary_repository.dart | 2 - lib/main.dart | 3 +- 5 files changed, 181 insertions(+), 80 deletions(-) diff --git a/lib/features/calendar/presentation/pages/calendar_screen.dart b/lib/features/calendar/presentation/pages/calendar_screen.dart index 9dab6be..646a3bb 100644 --- a/lib/features/calendar/presentation/pages/calendar_screen.dart +++ b/lib/features/calendar/presentation/pages/calendar_screen.dart @@ -4,6 +4,7 @@ import 'package:eatvio_app/features/calendar/models/calendar_model.dart'; import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_cubit.dart'; import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_state.dart'; import 'package:eatvio_app/core/app_export.dart'; +import 'package:go_router/go_router.dart'; import 'package:table_calendar/table_calendar.dart'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; @@ -101,26 +102,34 @@ class CalendarScreen extends StatelessWidget { ], ), child: TableCalendar( + locale: 'ru_RU', firstDay: DateTime.utc(2010, 10, 16), lastDay: DateTime.utc(2030, 3, 14), focusedDay: DateTime.now(), startingDayOfWeek: StartingDayOfWeek.monday, calendarBuilders: CalendarBuilders( - selectedBuilder: (context, day, focusedDay) => _buildCellDate(day, focusedDay: focusedDay, state), - defaultBuilder: (context, day, focusedDay) => _buildCellDate(day, state), - todayBuilder: (context, day, focusedDay) => _buildCellDate(day, state), + selectedBuilder: (context, day, focusedDay) => + _buildCellDate(context, day, focusedDay: focusedDay, state), + defaultBuilder: (context, day, focusedDay) => + _buildCellDate(context, day, state), + todayBuilder: (context, day, focusedDay) => + _buildCellDate(context, day, state), ), ), ); } } -Widget _buildCellDate(DateTime day, CalendarStateLoaded state, {DateTime? focusedDay}) { +Widget _buildCellDate( + BuildContext context, DateTime day, CalendarStateLoaded state, + {DateTime? focusedDay}) { final String dayString = day.toIso8601String().split('T').first; final List calendarModels = state.calendarList; // Находим первую модель, соответствующую дате - final CalendarModel model = calendarModels.firstWhere((model) => model.date == dayString, orElse: () => CalendarModel(date: dayString, diary: {})); + final CalendarModel model = calendarModels.firstWhere( + (model) => model.date == dayString, + orElse: () => CalendarModel(date: dayString, diary: {})); Color? bgclr; // Объявляем переменную bgclr здесь @@ -138,14 +147,16 @@ Widget _buildCellDate(DateTime day, CalendarStateLoaded state, {DateTime? focuse bgclr = Colors.white; // Значение по умолчанию, если diary не является Map } - return Container( - margin: const EdgeInsets.all(5), - alignment: Alignment.center, - decoration: BoxDecoration( - shape: (day == focusedDay) ? BoxShape.circle : BoxShape.rectangle, - color: bgclr, - borderRadius: (day == focusedDay) ? null : BorderRadius.circular(4), - ), - child: Text(day.day.toString(), style: TextStyle(color: Colors.black)), - ); + return GestureDetector( + onTap: () => GoRouter.of(context).replace('/diary-screen'), + child: Container( + margin: const EdgeInsets.all(5), + alignment: Alignment.center, + decoration: BoxDecoration( + shape: (day == focusedDay) ? BoxShape.circle : BoxShape.rectangle, + color: bgclr, + borderRadius: (day == focusedDay) ? null : BorderRadius.circular(4), + ), + child: Text(day.day.toString(), style: TextStyle(color: Colors.black)), + )); } diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index 8ac0e8a..e1b952b 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -16,7 +16,8 @@ part 'diary_event.dart'; class DiaryBloc extends Bloc { final DiaryRepository diaryRepository; - DiaryBloc({required this.diaryRepository}) : super(const DiaryState.loading()) { + DiaryBloc({required this.diaryRepository}) + : super(const DiaryState.loading()) { on(loadDiary); on(_changeSatiety); // пользователь нажимает на шкалу сытости on(_changeMood); // пользователь нажимает на шкалу настроения @@ -53,15 +54,29 @@ class DiaryBloc extends Bloc { final DiaryModel diary = await diaryRepository.getDiary(diaryID ?? 45); final Meal currentMeal = diary.meals[0]; - List portionList = [SelectionPopupModel(title: "gr"), SelectionPopupModel(title: "pcs")]; + List portionList = [ + SelectionPopupModel(title: "gr"), + SelectionPopupModel(title: "pcs") + ]; - final Map chartData = await diaryRepository.getChartData(diaryID ?? 45); - final Map dailyNutritionIntake = chartData['dailyNutritionIntake']!; - final Map dailyNutritionRecommendations = chartData['dailyNutritionRecommendation']!; - final double ccal = dailyNutritionIntake['energy']! / dailyNutritionRecommendations['energy']! * 100; - final double proteins = dailyNutritionIntake['proteins']! / dailyNutritionRecommendations['proteins']! * 100; - final double fats = dailyNutritionIntake['fats']! / dailyNutritionRecommendations['fats']! * 100; - final double carbs = dailyNutritionIntake['carbohydrates']! / dailyNutritionRecommendations['carbohydrates']! * 100; + final Map chartData = + await diaryRepository.getChartData(diaryID ?? 45); + final Map dailyNutritionIntake = + chartData['dailyNutritionIntake']!; + final Map dailyNutritionRecommendations = + chartData['dailyNutritionRecommendation']!; + final double ccal = dailyNutritionIntake['energy']! / + dailyNutritionRecommendations['energy']! * + 50; + final double proteins = dailyNutritionIntake['proteins']! / + dailyNutritionRecommendations['proteins']! * + 50; + final double fats = dailyNutritionIntake['fats']! / + dailyNutritionRecommendations['fats']! * + 50; + final double carbs = dailyNutritionIntake['carbohydrates']! / + dailyNutritionRecommendations['carbohydrates']! * + 50; Color getColor(double value) { if (value >= 99.1) { @@ -163,9 +178,11 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = currentState.copyWith(wakeupController: event.selectedTime); + var updatedState = + currentState.copyWith(wakeupController: event.selectedTime); final DateFormat formatter = DateFormat('HH:mm'); - final String wakeupString = formatter.format(DateTime(2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); + final String wakeupString = formatter.format(DateTime( + 2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); await diaryRepository.changeWakeup( currentState.diary.id, wakeupString, @@ -180,9 +197,11 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = currentState.copyWith(retireController: event.selectedTime); + var updatedState = + currentState.copyWith(retireController: event.selectedTime); final DateFormat formatter = DateFormat('HH:mm'); - final String retireString = formatter.format(DateTime(2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); + final String retireString = formatter.format(DateTime( + 2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); await diaryRepository.changeRetire( currentState.diary.id, retireString, @@ -208,7 +227,8 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { final currentState = state as DiaryStateLoaded; - final Meal meal = currentState.diary.meals.firstWhere((meal) => meal.type == event.value.id); + final Meal meal = currentState.diary.meals + .firstWhere((meal) => meal.type == event.value.id); DiaryStateLoaded updatedState = currentState.copyWith( currentMeal: meal, portions: meal.portions, @@ -227,10 +247,12 @@ class DiaryBloc extends Bloc { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - final Map> productNutritionalValues = await diaryRepository.inputProduct(event.input); + final Map> productNutritionalValues = + await diaryRepository.inputProduct(event.input); var updatedState = currentState.copyWith( product_nameController: TextEditingController(text: event.input), - autocompleteList: productNutritionalValues['product_nutritional_value'] ?? [], + autocompleteList: + productNutritionalValues['product_nutritional_value'] ?? [], ); if (event.input.length > 3) { updatedState = updatedState.copyWith(moderationExpanded: true); diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index 8be9be4..e360f35 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -111,35 +111,80 @@ class DiaryScreen extends StatelessWidget { _buildNutritionChart(BuildContext context, DiaryStateLoaded state) { return Container( - margin: EdgeInsets.symmetric(horizontal: 16.h, vertical: 16.h), - padding: EdgeInsets.symmetric( - horizontal: 24.h, - vertical: 12.v, - ), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: const BorderRadius.all(Radius.circular(12)), - boxShadow: [ - BoxShadow( - color: Colors.grey.withOpacity(0.5), - spreadRadius: 2, - blurRadius: 5, - offset: Offset(0, 3), - ), - ], - ), - child: SfCircularChart( - title: ChartTitle(text: 'График КБЖУ'), - legend: Legend(isVisible: true), - series: [ - RadialBarSeries( - dataSource: state.chartData, - xValueMapper: (NutritionData data, _) => data.category, - yValueMapper: (NutritionData data, _) => data.nutrition, - pointColorMapper: (NutritionData data, _) => data.color, - ) - ], - )); + margin: EdgeInsets.symmetric(horizontal: 16.h, vertical: 16.h), + padding: EdgeInsets.symmetric( + horizontal: 24.h, + vertical: 12.v, + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.all(Radius.circular(12)), + boxShadow: [ + BoxShadow( + color: Colors.grey.withOpacity(0.5), + spreadRadius: 2, + blurRadius: 5, + offset: Offset(0, 3), + ), + ], + ), + child: Column( + children: [ + Text( + "График КБЖУ", + style: theme.textTheme.titleMedium, + textAlign: TextAlign.center, + ), + Transform.rotate( + angle: -1.5708, + child: ClipRect( + child: Align( + alignment: Alignment.centerRight, + widthFactor: 0.5, + child: SfCircularChart( + legend: Legend(isVisible: false), + series: [ + RadialBarSeries( + dataSource: state.chartData, + xValueMapper: (NutritionData data, _) => data.category, + yValueMapper: (NutritionData data, _) => data.nutrition, + pointColorMapper: (NutritionData data, _) => data.color, + ) + ], + ), + ), + )), + SizedBox(height: 16.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Калории'), + Text('Белки'), + Text('Жиры'), + Text('Углеводы'), + ], + ), + Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + '${state.chartData![0].nutrition.toStringAsFixed(1)}'), // Калории + Text( + '${state.chartData![1].nutrition.toStringAsFixed(1)}'), // Белки + Text( + '${state.chartData![2].nutrition.toStringAsFixed(1)}'), // Жиры + Text( + '${state.chartData![3].nutrition.toStringAsFixed(1)}'), // Углеводы + ], + ), + ], + ), + ], + ), + ); } _buildEndDay(BuildContext context) { @@ -278,7 +323,9 @@ class DiaryScreen extends StatelessWidget { borderRadius: BorderRadiusStyle.roundedBorder5, ), child: Center( - child: CircularProgressIndicator(color: appTheme.blueGray300), // Замените на свой прелоадер при необходимости + child: CircularProgressIndicator( + color: appTheme + .blueGray300), // Замените на свой прелоадер при необходимости ), ), ], @@ -302,7 +349,8 @@ class DiaryScreen extends StatelessWidget { _buildMeal(BuildContext context, DiaryStateLoaded state) { final digitsOnly = FilteringTextInputFormatter.digitsOnly; - List _options = state.autocompleteList.map((Product item) => item.name).toList(); + List _options = + state.autocompleteList.map((Product item) => item.name).toList(); FocusNode focusNodeName = FocusNode(); return Container( margin: EdgeInsets.symmetric(horizontal: 16.h), @@ -346,7 +394,9 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectMealTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: state.mealTimeController?.format(context).toString(), + hintText: state.mealTimeController + ?.format(context) + .toString(), autofocus: false, ), ), @@ -482,7 +532,9 @@ class DiaryScreen extends StatelessWidget { SizedBox(height: 30.v), _buildAddProduct(context, state), SizedBox(height: 30.v), - ...state.portions.map((portion) => _buildProduct(context, portion)).toList(), + ...state.portions + .map((portion) => _buildProduct(context, portion)) + .toList(), SizedBox(height: 30.v), _buildCarousel(context, state), SizedBox(height: 20.v), @@ -631,7 +683,8 @@ class DiaryScreen extends StatelessWidget { popDialog(BuildContext dialogContext) { return () { - Navigator.of(dialogContext).pop(); // Dismiss the dialog on Cancel button press + Navigator.of(dialogContext) + .pop(); // Dismiss the dialog on Cancel button press }; } @@ -641,7 +694,8 @@ class DiaryScreen extends StatelessWidget { }; } - selectProduct(AutocompleteOnSelected onSelected, String option, DiaryStateLoaded state) { + selectProduct(AutocompleteOnSelected onSelected, String option, + DiaryStateLoaded state) { state.product_nameController.text = option; return () { onSelected(option); @@ -709,7 +763,9 @@ class DiaryScreen extends StatelessWidget { top: 5.v, ), child: Text( - portion.product_name.length > 8 ? portion.product_name.substring(0, 8) : portion.product_name, + portion.product_name.length > 8 + ? portion.product_name.substring(0, 8) + : portion.product_name, style: CustomTextStyles.titleMedium16, ), ), @@ -781,7 +837,9 @@ class DiaryScreen extends StatelessWidget { removePhoto(BuildContext context, Photo photo) { return () { - context.read().add(RemoveImageEvent(photo.id.toString(), photo.path)); + context + .read() + .add(RemoveImageEvent(photo.id.toString(), photo.path)); }; } @@ -859,7 +917,9 @@ class DiaryScreen extends StatelessWidget { r"Подъем \ отход ко сну", style: CustomTextStyles.bodyMediumBlack900, ), - Icon(state.wakeupExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), + Icon(state.wakeupExpanded + ? Icons.arrow_drop_up + : Icons.arrow_drop_down), ], ), ), @@ -873,7 +933,8 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectWakeupTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: state.wakeupController.format(context).toString(), + hintText: + state.wakeupController.format(context).toString(), prefix: Icon(Icons.sunny), autofocus: false, ), @@ -884,7 +945,8 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectRetireTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: state.retireController.format(context).toString(), + hintText: + state.retireController.format(context).toString(), prefix: Icon(Icons.bed), autofocus: false, ), @@ -931,7 +993,8 @@ class DiaryScreen extends StatelessWidget { }; } - Function() sendFinishDayData(BuildContext dialogContext, BuildContext context) { + Function() sendFinishDayData( + BuildContext dialogContext, BuildContext context) { return () { closeDialog(dialogContext); context.read().add(FinishDay()); @@ -974,7 +1037,9 @@ class DiaryScreen extends StatelessWidget { "Ваше настроение после приема пищи", style: CustomTextStyles.bodyMediumBlack900, ), - Icon(state.moodExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), + Icon(state.moodExpanded + ? Icons.arrow_drop_up + : Icons.arrow_drop_down), ], ), ), @@ -1034,7 +1099,8 @@ class DiaryScreen extends StatelessWidget { }; } - Future _selectWakeupTime(BuildContext context, DiaryStateLoaded state) async { + Future _selectWakeupTime( + BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.wakeupController, @@ -1044,7 +1110,8 @@ class DiaryScreen extends StatelessWidget { } } - Future _selectRetireTime(BuildContext context, DiaryStateLoaded state) async { + Future _selectRetireTime( + BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.retireController, @@ -1054,7 +1121,8 @@ class DiaryScreen extends StatelessWidget { } } - Future _selectMealTime(BuildContext context, DiaryStateLoaded state) async { + Future _selectMealTime( + BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.mealTimeController ?? TimeOfDay.now(), @@ -1065,7 +1133,8 @@ class DiaryScreen extends StatelessWidget { } } -bool checkConsumedValues(List recommendedValues, List consumedValues) { +bool checkConsumedValues( + List recommendedValues, List consumedValues) { for (int i = 0; i < recommendedValues.length; i++) { if (consumedValues[i] > recommendedValues[i]) { // Если хотя бы одно потребленное значение превышает рекомендованное diff --git a/lib/features/diary/repositories/diary_repository.dart b/lib/features/diary/repositories/diary_repository.dart index 599c081..04a8cad 100644 --- a/lib/features/diary/repositories/diary_repository.dart +++ b/lib/features/diary/repositories/diary_repository.dart @@ -1,6 +1,4 @@ import 'dart:io'; -import 'package:flutter/material.dart'; -import 'package:intl/intl.dart'; import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:eatvio_app/features/diary/models/portion.dart'; diff --git a/lib/main.dart b/lib/main.dart index 9ce1b92..d628b94 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -18,6 +18,7 @@ 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:intl/date_symbol_data_local.dart'; var globalMessengerKey = GlobalKey(); @@ -34,7 +35,7 @@ void main() async { DeviceOrientation.portraitUp, ]); await PrefUtils().init(); - runApp(MyApp()); + initializeDateFormatting().then((_) => runApp(MyApp())); } class MyApp extends StatelessWidget { -- 2.49.1 From 403e49d65799f23d7996566292e1814c55346fbf Mon Sep 17 00:00:00 2001 From: maxxkim Date: Wed, 31 Jul 2024 13:09:28 +0300 Subject: [PATCH 086/110] feat(calendar): Routes to diary --- .../calendar/presentation/pages/calendar_screen.dart | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/features/calendar/presentation/pages/calendar_screen.dart b/lib/features/calendar/presentation/pages/calendar_screen.dart index 646a3bb..ab90403 100644 --- a/lib/features/calendar/presentation/pages/calendar_screen.dart +++ b/lib/features/calendar/presentation/pages/calendar_screen.dart @@ -133,9 +133,8 @@ Widget _buildCellDate( Color? bgclr; // Объявляем переменную bgclr здесь + final Map diary = model.diary as Map; if (model.diary is Map) { - final Map diary = model.diary as Map; - if (diary['state'] == "started") { bgclr = Colors.grey; } else if (diary['state'] == "finished") { @@ -148,7 +147,10 @@ Widget _buildCellDate( } return GestureDetector( - onTap: () => GoRouter.of(context).replace('/diary-screen'), + onTap: () => GoRouter.of(context).pushNamed( + 'diaryScreen', + extra: diary['id'], + ), child: Container( margin: const EdgeInsets.all(5), alignment: Alignment.center, -- 2.49.1 From bdfa671c18374c35f8c25e6f15f39b4c6e5b874f Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Wed, 31 Jul 2024 13:10:07 +0300 Subject: [PATCH 087/110] feat(blogPost): add routing --- lib/app_router.dart | 40 +++++------ .../presentation/pages/blog_post_screen.dart | 2 +- .../pages/blog_post_create_screen.dart | 9 ++- .../feed/presentation/pages/feed_screen.dart | 2 +- .../presentation/pages/feed_screen_new.dart | 68 ++++++++++--------- .../widgets/blog_post_widget.dart | 16 +++-- .../subscribers_screen.dart | 2 +- 7 files changed, 74 insertions(+), 65 deletions(-) diff --git a/lib/app_router.dart b/lib/app_router.dart index 4cddc6e..605e247 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -65,28 +65,6 @@ class AppRouter { path: '/feed-screen', name: 'feedScreen', builder: (context, state) => FeedScreenNew(), - routes: [ - GoRoute( - path: 'blog-post-create-screen', - name: 'blogPostCreateScreen', - builder: (context, state) => BlogPostCreateScreen.builder(context), - ), - GoRoute( - path: 'blog-post-screen', - name: 'blogPostScreen', - builder: (context, state) => BlogPostScreen(blogPostID: state.extra as String), - routes: [ - GoRoute( - path: 'blog-post-edit-screen', - name: 'blogPostEditScreen', - builder: (context, state) => BlogPostEditScreen.builder( - context, - state.extra, - ), - ), - ], - ), - ], ), GoRoute( path: '/diary-screen', @@ -100,6 +78,24 @@ class AppRouter { ), ], ), + GoRoute( + path: '/blog-post-create-screen', + name: 'blogPostCreateScreen', + builder: (context, state) => BlogPostCreateScreen.builder(context), + ), + GoRoute( + path: '/blog-post-screen', + name: 'blogPostScreen', + builder: (context, state) => BlogPostScreen(blogPostID: state.extra as String), + ), + GoRoute( + path: '/blog-post-edit-screen', + name: 'blogPostEditScreen', + builder: (context, state) => BlogPostEditScreen.builder( + context, + state.extra, + ), + ), GoRoute( path: '/chat-screen', name: 'chatScreen', 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 c46c8b1..8bb6630 100644 --- a/lib/features/blog_post/presentation/pages/blog_post_screen.dart +++ b/lib/features/blog_post/presentation/pages/blog_post_screen.dart @@ -294,7 +294,7 @@ class BlogPostScreen extends StatelessWidget { void tapMenu(String value, BuildContext context, BlogPostStateLoaded state) { if (value == 'edit') { - GoRouter.of(context).goNamed( + GoRouter.of(context).pushNamed( 'blogPostEditScreen', extra: state.blogPost.id.toString(), ); 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 39c3f4e..d829514 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 @@ -9,7 +9,7 @@ import 'package:image_picker/image_picker.dart'; 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 { +class BlogPostCreateScreen extends StatefulWidget { const BlogPostCreateScreen({Key? key}) : super(key: key); static Widget builder(BuildContext context) { @@ -21,6 +21,11 @@ class BlogPostCreateScreen extends StatelessWidget { ); } + @override + State createState() => _BlogPostCreateScreenState(); +} + +class _BlogPostCreateScreenState extends State { Widget build(BuildContext context) { return BlocBuilder( builder: (context, state) { @@ -115,7 +120,7 @@ class BlogPostCreateScreen extends StatelessWidget { } } -_submitForm(BuildContext context, String title, String description, String youtubeURL) { +_submitForm(BuildContext context, String title, String description, String youtubeURL) async { String? titleError = _validateTitle(title); String? descriptionError = _validateDescription(description); String? youtubeURLError = _validateYouTubeLink(youtubeURL); diff --git a/lib/features/feed/presentation/pages/feed_screen.dart b/lib/features/feed/presentation/pages/feed_screen.dart index e97b39e..93697eb 100644 --- a/lib/features/feed/presentation/pages/feed_screen.dart +++ b/lib/features/feed/presentation/pages/feed_screen.dart @@ -108,7 +108,7 @@ class FeedScreen extends StatelessWidget { flex: 1, child: CustomOutlinedButton( text: "+", - onPressed: () => GoRouter.of(context).goNamed('blogPostCreateScreen'), + onPressed: () => GoRouter.of(context).pushNamed('blogPostCreateScreen'), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, ), ), diff --git a/lib/features/feed/presentation/pages/feed_screen_new.dart b/lib/features/feed/presentation/pages/feed_screen_new.dart index bdd2476..6b5e183 100644 --- a/lib/features/feed/presentation/pages/feed_screen_new.dart +++ b/lib/features/feed/presentation/pages/feed_screen_new.dart @@ -6,6 +6,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:go_router/go_router.dart'; class FeedScreenNew extends StatefulWidget { const FeedScreenNew({super.key}); @@ -61,38 +62,41 @@ class _FeedScreenNewState extends State { } _buildAllBlogPosts() { - return BlocBuilder( - builder: (BuildContext context, FeedState state) { - if (state is FeedStateLoaded) { - return ListView.separated( - padding: EdgeInsets.symmetric(vertical: 8), - shrinkWrap: true, - physics: BouncingScrollPhysics(), - itemBuilder: (context, index) { - return BlogPostWidget(feedBlogPostModel: state.feedBlogPostList[index]); - }, - separatorBuilder: (context, index) { - return SizedBox(height: 8); - }, - itemCount: state.feedBlogPostList.length, - ); - } else if (state is FeedStateError) { - return Scaffold( - body: Padding( - padding: const EdgeInsets.all(16), - child: Center( - child: Text(state.errorMessage), + return RefreshIndicator( + onRefresh: () => context.read().loadFeedBlogPostList(), + child: BlocBuilder( + builder: (BuildContext context, FeedState state) { + if (state is FeedStateLoaded) { + return ListView.separated( + padding: EdgeInsets.symmetric(vertical: 8), + shrinkWrap: true, + physics: BouncingScrollPhysics(), + itemBuilder: (context, index) { + return BlogPostWidget(feedBlogPostModel: state.feedBlogPostList[index]); + }, + separatorBuilder: (context, index) { + return SizedBox(height: 8); + }, + itemCount: state.feedBlogPostList.length, + ); + } else if (state is FeedStateError) { + return Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: Center( + child: Text(state.errorMessage), + ), ), - ), - ); - } else { - return Scaffold( - body: Center( - child: CupertinoActivityIndicator(), - ), - ); - } - }, + ); + } else { + return Scaffold( + body: Center( + child: CupertinoActivityIndicator(), + ), + ); + } + }, + ), ); } @@ -124,7 +128,7 @@ class _FeedScreenNewState extends State { _addBlogPostButton() { return InkWell( - onTap: () {}, + onTap: () => GoRouter.of(context).pushNamed('blogPostCreateScreen'), borderRadius: BorderRadius.circular(64), child: Ink( decoration: BoxDecoration( diff --git a/lib/features/feed/presentation/widgets/blog_post_widget.dart b/lib/features/feed/presentation/widgets/blog_post_widget.dart index b7d26df..6bf0f7e 100644 --- a/lib/features/feed/presentation/widgets/blog_post_widget.dart +++ b/lib/features/feed/presentation/widgets/blog_post_widget.dart @@ -4,6 +4,7 @@ import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; class BlogPostWidget extends StatefulWidget { final FeedBlogPostModel feedBlogPostModel; @@ -17,8 +18,11 @@ class BlogPostWidget extends StatefulWidget { class _BlogPostWidgetState extends State { @override Widget build(BuildContext context) { - return GestureDetector( - onTap: () {}, + return InkWell( + onTap: () => GoRouter.of(context).pushNamed( + 'blogPostScreen', + extra: widget.feedBlogPostModel.id.toString(), + ), child: Ink( decoration: BoxDecoration( borderRadius: BorderRadius.circular(12), @@ -45,17 +49,17 @@ class _BlogPostWidgetState extends State { ], ), ), - SizedBox(height: 12), + if (widget.feedBlogPostModel.title.isNotEmpty || widget.feedBlogPostModel.description.isNotEmpty) SizedBox(height: 12), Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Text(widget.feedBlogPostModel.title), ), - SizedBox(height: 8), + if (widget.feedBlogPostModel.title.isNotEmpty && widget.feedBlogPostModel.description.isNotEmpty) SizedBox(height: 8), Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Text(widget.feedBlogPostModel.description), ), - SizedBox(height: 8), + if (widget.feedBlogPostModel.title.isNotEmpty || widget.feedBlogPostModel.description.isNotEmpty) SizedBox(height: 8), GestureDetector( onTap: () { context.pushTransparentRoute( @@ -73,7 +77,7 @@ class _BlogPostWidgetState extends State { ), ), ), - SizedBox(height: 8), + SizedBox(height: 12), Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Row( diff --git a/lib/presentation/users/subscribers_screen/subscribers_screen.dart b/lib/presentation/users/subscribers_screen/subscribers_screen.dart index 01fb9a7..bb968f2 100644 --- a/lib/presentation/users/subscribers_screen/subscribers_screen.dart +++ b/lib/presentation/users/subscribers_screen/subscribers_screen.dart @@ -139,7 +139,7 @@ class SubscribersScreen extends StatelessWidget { flex: 1, child: CustomOutlinedButton( text: "+", - onPressed: () => GoRouter.of(context).goNamed('blogPostCreateScreen'), + onPressed: () => GoRouter.of(context).pushNamed('blogPostCreateScreen'), buttonStyle: CustomButtonStyles.outlinePrimaryTL15, ), ), -- 2.49.1 From b7ca00b9480179919b0005216d3f4d7dc9919d09 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Wed, 31 Jul 2024 13:29:05 +0300 Subject: [PATCH 088/110] merge --- lib/app_router.dart | 28 +---- .../calendar/services/calendar_service.dart | 2 +- .../calendar/services/calendar_service.g.dart | 2 +- lib/features/diary/models/photo.dart | 3 +- lib/features/diary/models/photo.freezed.dart | 49 ++++---- lib/features/diary/models/photo.g.dart | 4 +- .../diary/presentation/bloc/diary_bloc.dart | 3 +- .../bloc/diary_state.freezed.dart | 10 ++ .../presentation/pages/diary_screen.dart | 106 +++++++++++++----- .../diary/services/diary_service.dart | 28 ++--- .../diary/services/diary_service.g.dart | 28 ++--- lib/locator_service.dart | 16 ++- pubspec.yaml | 1 + 13 files changed, 167 insertions(+), 113 deletions(-) diff --git a/lib/app_router.dart b/lib/app_router.dart index d901f02..2f9d384 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -1,11 +1,13 @@ +import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.dart'; import 'package:eatvio_app/core/token_storage.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/diary/presentation/pages/diary_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'; @@ -14,24 +16,9 @@ import 'package:eatvio_app/presentation/plans/plan_select_screen/plan_select_scr 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/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'; class AppRouter { @@ -78,11 +65,6 @@ class AppRouter { name: 'feedScreen', builder: (context, state) => FeedScreen(), routes: [ - GoRoute( - path: 'blog-post-create-screen', - name: 'blogPostCreateScreen', - builder: (context, state) => BlogPostCreateScreen.builder(context), - ), GoRoute( path: 'blog-post-screen', name: 'blogPostScreen', diff --git a/lib/features/calendar/services/calendar_service.dart b/lib/features/calendar/services/calendar_service.dart index 80b98e6..c33535c 100644 --- a/lib/features/calendar/services/calendar_service.dart +++ b/lib/features/calendar/services/calendar_service.dart @@ -8,6 +8,6 @@ part 'calendar_service.g.dart'; abstract class CalendarService { factory CalendarService(Dio dio, {String baseUrl}) = _CalendarService; - @GET('/calendar/index') + @GET('/api/calendar/index') Future> getCalendar(); } diff --git a/lib/features/calendar/services/calendar_service.g.dart b/lib/features/calendar/services/calendar_service.g.dart index 5703378..226da21 100644 --- a/lib/features/calendar/services/calendar_service.g.dart +++ b/lib/features/calendar/services/calendar_service.g.dart @@ -32,7 +32,7 @@ class _CalendarService implements CalendarService { ) .compose( _dio.options, - '/calendar/index', + '/api/calendar/index', queryParameters: queryParameters, data: _data, ) diff --git a/lib/features/diary/models/photo.dart b/lib/features/diary/models/photo.dart index eef9e8f..f25b8f6 100644 --- a/lib/features/diary/models/photo.dart +++ b/lib/features/diary/models/photo.dart @@ -7,7 +7,8 @@ part 'photo.g.dart'; class Photo with _$Photo { const factory Photo({ required int id, - required String original_name, + @JsonKey(name: 'original_name') + required String originalName, required String path, }) = _Photo; diff --git a/lib/features/diary/models/photo.freezed.dart b/lib/features/diary/models/photo.freezed.dart index d922286..2d9c70b 100644 --- a/lib/features/diary/models/photo.freezed.dart +++ b/lib/features/diary/models/photo.freezed.dart @@ -21,7 +21,8 @@ Photo _$PhotoFromJson(Map json) { /// @nodoc mixin _$Photo { int get id => throw _privateConstructorUsedError; - String get original_name => throw _privateConstructorUsedError; + @JsonKey(name: 'original_name') + String get originalName => throw _privateConstructorUsedError; String get path => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @@ -34,7 +35,10 @@ abstract class $PhotoCopyWith<$Res> { factory $PhotoCopyWith(Photo value, $Res Function(Photo) then) = _$PhotoCopyWithImpl<$Res, Photo>; @useResult - $Res call({int id, String original_name, String path}); + $Res call( + {int id, + @JsonKey(name: 'original_name') String originalName, + String path}); } /// @nodoc @@ -51,7 +55,7 @@ class _$PhotoCopyWithImpl<$Res, $Val extends Photo> @override $Res call({ Object? id = null, - Object? original_name = null, + Object? originalName = null, Object? path = null, }) { return _then(_value.copyWith( @@ -59,9 +63,9 @@ class _$PhotoCopyWithImpl<$Res, $Val extends Photo> ? _value.id : id // ignore: cast_nullable_to_non_nullable as int, - original_name: null == original_name - ? _value.original_name - : original_name // ignore: cast_nullable_to_non_nullable + originalName: null == originalName + ? _value.originalName + : originalName // ignore: cast_nullable_to_non_nullable as String, path: null == path ? _value.path @@ -78,7 +82,10 @@ abstract class _$$PhotoImplCopyWith<$Res> implements $PhotoCopyWith<$Res> { __$$PhotoImplCopyWithImpl<$Res>; @override @useResult - $Res call({int id, String original_name, String path}); + $Res call( + {int id, + @JsonKey(name: 'original_name') String originalName, + String path}); } /// @nodoc @@ -93,7 +100,7 @@ class __$$PhotoImplCopyWithImpl<$Res> @override $Res call({ Object? id = null, - Object? original_name = null, + Object? originalName = null, Object? path = null, }) { return _then(_$PhotoImpl( @@ -101,9 +108,9 @@ class __$$PhotoImplCopyWithImpl<$Res> ? _value.id : id // ignore: cast_nullable_to_non_nullable as int, - original_name: null == original_name - ? _value.original_name - : original_name // ignore: cast_nullable_to_non_nullable + originalName: null == originalName + ? _value.originalName + : originalName // ignore: cast_nullable_to_non_nullable as String, path: null == path ? _value.path @@ -117,7 +124,9 @@ class __$$PhotoImplCopyWithImpl<$Res> @JsonSerializable() class _$PhotoImpl implements _Photo { const _$PhotoImpl( - {required this.id, required this.original_name, required this.path}); + {required this.id, + @JsonKey(name: 'original_name') required this.originalName, + required this.path}); factory _$PhotoImpl.fromJson(Map json) => _$$PhotoImplFromJson(json); @@ -125,13 +134,14 @@ class _$PhotoImpl implements _Photo { @override final int id; @override - final String original_name; + @JsonKey(name: 'original_name') + final String originalName; @override final String path; @override String toString() { - return 'Photo(id: $id, original_name: $original_name, path: $path)'; + return 'Photo(id: $id, originalName: $originalName, path: $path)'; } @override @@ -140,14 +150,14 @@ class _$PhotoImpl implements _Photo { (other.runtimeType == runtimeType && other is _$PhotoImpl && (identical(other.id, id) || other.id == id) && - (identical(other.original_name, original_name) || - other.original_name == original_name) && + (identical(other.originalName, originalName) || + other.originalName == originalName) && (identical(other.path, path) || other.path == path)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, original_name, path); + int get hashCode => Object.hash(runtimeType, id, originalName, path); @JsonKey(ignore: true) @override @@ -166,7 +176,7 @@ class _$PhotoImpl implements _Photo { abstract class _Photo implements Photo { const factory _Photo( {required final int id, - required final String original_name, + @JsonKey(name: 'original_name') required final String originalName, required final String path}) = _$PhotoImpl; factory _Photo.fromJson(Map json) = _$PhotoImpl.fromJson; @@ -174,7 +184,8 @@ abstract class _Photo implements Photo { @override int get id; @override - String get original_name; + @JsonKey(name: 'original_name') + String get originalName; @override String get path; @override diff --git a/lib/features/diary/models/photo.g.dart b/lib/features/diary/models/photo.g.dart index 8cd7bcc..cacf65a 100644 --- a/lib/features/diary/models/photo.g.dart +++ b/lib/features/diary/models/photo.g.dart @@ -8,13 +8,13 @@ part of 'photo.dart'; _$PhotoImpl _$$PhotoImplFromJson(Map json) => _$PhotoImpl( id: (json['id'] as num).toInt(), - original_name: json['original_name'] as String, + originalName: json['original_name'] as String, path: json['path'] as String, ); Map _$$PhotoImplToJson(_$PhotoImpl instance) => { 'id': instance.id, - 'original_name': instance.original_name, + 'original_name': instance.originalName, 'path': instance.path, }; diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index e690335..0cdad7d 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -11,7 +11,6 @@ import 'package:image_picker/image_picker.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; part 'diary_event.dart'; @@ -144,7 +143,7 @@ class DiaryBloc 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', diff --git a/lib/features/diary/presentation/bloc/diary_state.freezed.dart b/lib/features/diary/presentation/bloc/diary_state.freezed.dart index deda872..9bd28b2 100644 --- a/lib/features/diary/presentation/bloc/diary_state.freezed.dart +++ b/lib/features/diary/presentation/bloc/diary_state.freezed.dart @@ -613,6 +613,7 @@ abstract class _$$DiaryStateLoadedImplCopyWith<$Res> { $DiaryModelCopyWith<$Res> get diary; $MealCopyWith<$Res> get currentMeal; + $SelectionPopupModelCopyWith<$Res> get portionController; } /// @nodoc @@ -786,6 +787,15 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> return _then(_value.copyWith(currentMeal: value)); }); } + + @override + @pragma('vm:prefer-inline') + $SelectionPopupModelCopyWith<$Res> get portionController { + return $SelectionPopupModelCopyWith<$Res>(_value.portionController, + (value) { + return _then(_value.copyWith(portionController: value)); + }); + } } /// @nodoc diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index 53937a9..72b1ec5 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -17,7 +17,6 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:image_picker/image_picker.dart'; import 'package:carousel_slider/carousel_slider.dart'; import 'package:syncfusion_flutter_charts/charts.dart'; @@ -111,35 +110,80 @@ class DiaryScreen extends StatelessWidget { _buildNutritionChart(BuildContext context, DiaryStateLoaded state) { return Container( - margin: EdgeInsets.symmetric(horizontal: 16.h, vertical: 16.h), - padding: EdgeInsets.symmetric( - horizontal: 24.h, - vertical: 12.v, - ), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: const BorderRadius.all(Radius.circular(12)), - boxShadow: [ - BoxShadow( - color: Colors.grey.withOpacity(0.5), - spreadRadius: 2, - blurRadius: 5, - offset: Offset(0, 3), - ), - ], - ), - child: SfCircularChart( - title: ChartTitle(text: 'График КБЖУ'), - legend: Legend(isVisible: true), - series: [ - RadialBarSeries( - dataSource: state.chartData, - xValueMapper: (NutritionData data, _) => data.category, - yValueMapper: (NutritionData data, _) => data.nutrition, - pointColorMapper: (NutritionData data, _) => data.color, - ) - ], - )); + margin: EdgeInsets.symmetric(horizontal: 16.h, vertical: 16.h), + padding: EdgeInsets.symmetric( + horizontal: 24.h, + vertical: 12.v, + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: const BorderRadius.all(Radius.circular(12)), + boxShadow: [ + BoxShadow( + color: Colors.grey.withOpacity(0.5), + spreadRadius: 2, + blurRadius: 5, + offset: Offset(0, 3), + ), + ], + ), + child: Column( + children: [ + Text( + "График КБЖУ", + style: theme.textTheme.titleMedium, + textAlign: TextAlign.center, + ), + Transform.rotate( + angle: -1.5708, + child: ClipRect( + child: Align( + alignment: Alignment.centerRight, + widthFactor: 0.5, + child: SfCircularChart( + legend: Legend(isVisible: false), + series: [ + RadialBarSeries( + dataSource: state.chartData, + xValueMapper: (NutritionData data, _) => data.category, + yValueMapper: (NutritionData data, _) => data.nutrition, + pointColorMapper: (NutritionData data, _) => data.color, + ) + ], + ), + ), + )), + SizedBox(height: 16.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Калории'), + Text('Белки'), + Text('Жиры'), + Text('Углеводы'), + ], + ), + Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + '${state.chartData![0].nutrition.toStringAsFixed(1)}'), // Калории + Text( + '${state.chartData![1].nutrition.toStringAsFixed(1)}'), // Белки + Text( + '${state.chartData![2].nutrition.toStringAsFixed(1)}'), // Жиры + Text( + '${state.chartData![3].nutrition.toStringAsFixed(1)}'), // Углеводы + ], + ), + ], + ), + ], + ), + ); } _buildEndDay(BuildContext context) { @@ -759,7 +803,7 @@ class DiaryScreen extends StatelessWidget { borderRadius: BorderRadiusStyle.roundedBorder5, ), child: Image.network( - dotenv.env['STORAGE_URL']! + photo.path, + baseUrl + '/storage/' + photo.path, ), ), Positioned( diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart index 125db49..3c61a35 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -12,46 +12,46 @@ part 'diary_service.g.dart'; abstract class DiaryService { factory DiaryService(Dio dio, {String baseUrl}) = _DiaryService; - @GET('/diary/index') + @GET('/api/diary/index') Future> getDiaryID(); - @GET('/diary/{id}/show/') + @GET('/api/diary/{id}/show/') Future> getDiary(@Path() int id); - @GET('/diary/{id}/dailyNutritionData/') + @GET('/api/diary/{id}/dailyNutritionData/') Future getChart(@Path() int id); - @GET('/diary/product_nutritional_values/filter') + @GET('/api/diary/product_nutritional_values/filter') Future>> getInputProduct( @Query('name') String name); - @POST('/diary/{diary_id}/meal/{meal_id}/satiety/fill') + @POST('/api/diary/{diary_id}/meal/{meal_id}/satiety/fill') Future> sendSatietyData( @Path() int diary_id, @Path() int meal_id, @Query('satiety') int satiety, ); - @POST('/diary/{diary_id}/meal/{meal_id}/mood/fill') + @POST('/api/diary/{diary_id}/meal/{meal_id}/mood/fill') Future> sendMoodData( @Path() int diary_id, @Path() int meal_id, @Query('mood') int mood, ); - @POST('/diary/{diary_id}/wakeup/fill') + @POST('/api/diary/{diary_id}/wakeup/fill') Future sendWakeupData( @Path() int diary_id, @Query('wakeup') String wakeup, ); - @POST('/diary/{diary_id}/retire/fill') + @POST('/api/diary/{diary_id}/retire/fill') Future sendRetireData( @Path() int diary_id, @Query('retire') String retire, ); - @POST('/diary/{diary_id}/meal/{meal_id}/portions/create') + @POST('/api/diary/{diary_id}/meal/{meal_id}/portions/create') Future> sendPortionData( @Path() int diary_id, @Path() int meal_id, @@ -60,14 +60,14 @@ abstract class DiaryService { @Query('quantity') int quantity, ); - @POST('/diary/{diary_id}/meal/{meal_id}/photo/upload') + @POST('/api/diary/{diary_id}/meal/{meal_id}/photo/upload') Future uploadImage( @Path() int diary_id, @Path() int meal_id, @Part() File photo, ); - @POST('/diary/product_nutritional_values/sendToModeration') + @POST('/api/diary/product_nutritional_values/sendToModeration') Future> sendModerationData( @Query('name') String product_name, @Query('energy_on_100gr') double energy_on_100gr, @@ -76,7 +76,7 @@ abstract class DiaryService { @Query('carbohydrates_on_100gr') double carbohydrates_on_100gr, ); - @POST('/diary/{diary_id}/finishDay') + @POST('/api/diary/{diary_id}/finishDay') Future sendFinishDay( @Path() int diary_id, @Query('wakeUp') String wakeup, @@ -84,14 +84,14 @@ abstract class DiaryService { @Query('comment') String comment, ); - @DELETE('/diary/{diary_id}/meal/{meal_id}/portions/{portion_id}/delete') + @DELETE('/api/diary/{diary_id}/meal/{meal_id}/portions/{portion_id}/delete') Future sendRemovePortionData( @Path() int diary_id, @Path() int meal_id, @Path() int portion_id, ); - @DELETE('/diary/{diary_id}/meal/{meal_id}/photo/delete') + @DELETE('/api/diary/{diary_id}/meal/{meal_id}/photo/delete') Future sendRemovePhotoData( @Path() int diary_id, @Path() int meal_id, diff --git a/lib/features/diary/services/diary_service.g.dart b/lib/features/diary/services/diary_service.g.dart index 01a3488..9030ebb 100644 --- a/lib/features/diary/services/diary_service.g.dart +++ b/lib/features/diary/services/diary_service.g.dart @@ -32,7 +32,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/index', + '/api/diary/index', queryParameters: queryParameters, data: _data, ) @@ -59,7 +59,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/${id}/show/', + '/api/diary/${id}/show/', queryParameters: queryParameters, data: _data, ) @@ -86,7 +86,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/${id}/dailyNutritionData/', + '/api/diary/${id}/dailyNutritionData/', queryParameters: queryParameters, data: _data, ) @@ -113,7 +113,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/product_nutritional_values/filter', + '/api/diary/product_nutritional_values/filter', queryParameters: queryParameters, data: _data, ) @@ -148,7 +148,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/${diary_id}/meal/${meal_id}/satiety/fill', + '/api/diary/${diary_id}/meal/${meal_id}/satiety/fill', queryParameters: queryParameters, data: _data, ) @@ -179,7 +179,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/${diary_id}/meal/${meal_id}/mood/fill', + '/api/diary/${diary_id}/meal/${meal_id}/mood/fill', queryParameters: queryParameters, data: _data, ) @@ -209,7 +209,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/${diary_id}/wakeup/fill', + '/api/diary/${diary_id}/wakeup/fill', queryParameters: queryParameters, data: _data, ) @@ -239,7 +239,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/${diary_id}/retire/fill', + '/api/diary/${diary_id}/retire/fill', queryParameters: queryParameters, data: _data, ) @@ -276,7 +276,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/${diary_id}/meal/${meal_id}/portions/create', + '/api/diary/${diary_id}/meal/${meal_id}/portions/create', queryParameters: queryParameters, data: _data, ) @@ -314,7 +314,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/${diary_id}/meal/${meal_id}/photo/upload', + '/api/diary/${diary_id}/meal/${meal_id}/photo/upload', queryParameters: queryParameters, data: _data, ) @@ -351,7 +351,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/product_nutritional_values/sendToModeration', + '/api/diary/product_nutritional_values/sendToModeration', queryParameters: queryParameters, data: _data, ) @@ -386,7 +386,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/${diary_id}/finishDay', + '/api/diary/${diary_id}/finishDay', queryParameters: queryParameters, data: _data, ) @@ -414,7 +414,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/${diary_id}/meal/${meal_id}/portions/${portion_id}/delete', + '/api/diary/${diary_id}/meal/${meal_id}/portions/${portion_id}/delete', queryParameters: queryParameters, data: _data, ) @@ -446,7 +446,7 @@ class _DiaryService implements DiaryService { ) .compose( _dio.options, - '/diary/${diary_id}/meal/${meal_id}/photo/delete', + '/api/diary/${diary_id}/meal/${meal_id}/photo/delete', queryParameters: queryParameters, data: _data, ) diff --git a/lib/locator_service.dart b/lib/locator_service.dart index 7cf4698..e62214a 100644 --- a/lib/locator_service.dart +++ b/lib/locator_service.dart @@ -1,15 +1,23 @@ 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'; import 'package:eatvio_app/features/blog_post/services/blog_post_service.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/notifications_cubit/notifications_cubit.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; import 'package:eatvio_app/features/chat/services/chat_service.dart'; +import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.dart'; +import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; +import 'package:eatvio_app/features/diary/services/diary_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; @@ -23,8 +31,7 @@ Future init() async { sl.registerFactory(() => RegistrationCubit(registrationRepository: sl())); sl.registerFactory(() => ChatRoomCubit(chatRepository: sl(), initializationCubit: sl())); sl.registerFactory(() => FeedCubit(feedRepository: sl())); - sl.registerFactory( - () => BlogPostCubit(blogPostRepository: sl())); + sl.registerFactory(() => BlogPostCubit(blogPostRepository: sl())); sl.registerFactory(() => DiaryBloc(diaryRepository: sl())); // Repository @@ -32,8 +39,7 @@ Future init() async { sl.registerLazySingleton(() => FeedRepository(feedService: sl())); sl.registerLazySingleton(() => BlogPostRepository(blogPostService: sl())); sl.registerLazySingleton(() => RegistrationRepository(registrationService: sl())); - sl.registerLazySingleton( - () => DiaryRepository(diaryService: sl())); + sl.registerLazySingleton(() => DiaryRepository(diaryService: sl())); // Services sl.registerLazySingleton(() => ChatService(sl())); diff --git a/pubspec.yaml b/pubspec.yaml index 2cdbe59..a44d77a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -44,6 +44,7 @@ dependencies: lazy_load_scrollview: ^1.3.0 badges: ^3.1.2 google_fonts: ^6.2.1 + syncfusion_flutter_charts: ^26.1.42 dev_dependencies: build_runner: ^2.4.11 -- 2.49.1 From 35ce394471f691ebd76cd321e5e063f559e7f80d Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Wed, 31 Jul 2024 13:35:26 +0300 Subject: [PATCH 089/110] merge --- lib/app_router.dart | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/app_router.dart b/lib/app_router.dart index 93a75c4..af7073c 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -7,11 +7,9 @@ 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/diary/presentation/pages/diary_screen.dart'; -import 'package:eatvio_app/features/feed/presentation/pages/feed_screen.dart'; import 'package:eatvio_app/features/feed/presentation/pages/feed_screen_new.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/presentation/feed/blog_post_edit_screen/blog_post_edit_screen.dart'; -- 2.49.1 From c9f293159ef76602fa9896a6e34a9db5b3c1d866 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Wed, 31 Jul 2024 13:56:07 +0300 Subject: [PATCH 090/110] merge --- lib/app_router.dart | 6 ++++++ .../presentation/bloc/chat_room_cubit/chat_room_cubit.dart | 1 + lib/main.dart | 7 ++++++- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/app_router.dart b/lib/app_router.dart index af7073c..5eb1d0c 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -3,6 +3,7 @@ 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/calendar/presentation/pages/calendar_screen.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'; @@ -126,6 +127,11 @@ class AppRouter { name: 'planSelectScreen', builder: (context, state) => PlanSelectScreen.builder(context), ), + GoRoute( + path: '/calendar-screen', + name: 'calendarScreen', + builder: (context, state) => CalendarScreen(), + ), GoRoute( path: '/glossary-screen', name: 'glossaryScreen', diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart index 96e2bd2..3773c43 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart @@ -73,6 +73,7 @@ class ChatRoomCubit extends Cubit { isLoading: isLoading, )); } catch (e) { + print(e); emit(ChatRoomState.error(errorMessage: 'Ошибка получеия данных')); } } diff --git a/lib/main.dart b/lib/main.dart index 743ac0c..d9bc52c 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,6 +1,9 @@ import 'package:eatvio_app/app_router.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_state.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/notifications_cubit/notifications_cubit.dart'; +import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_cubit.dart'; 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'; @@ -40,7 +43,9 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MultiBlocProvider( providers: [ - BlocProvider(create: (context) => InitializationCubit(chatRepository: sl())), + 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())), -- 2.49.1 From 6946060c866bbaf62e472b498cc6de02d00da3c1 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Wed, 31 Jul 2024 14:39:36 +0300 Subject: [PATCH 091/110] refactor(baseUrl): -> dev2, fix location --- lib/core/constants/constants.dart | 2 +- .../registration/presentation/pages/city_of_living_screen.dart | 2 ++ .../glossary/glossary_screen/bloc/glossary_screen_bloc.dart | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/core/constants/constants.dart b/lib/core/constants/constants.dart index c0353c4..396c2dc 100644 --- a/lib/core/constants/constants.dart +++ b/lib/core/constants/constants.dart @@ -1 +1 @@ -const String baseUrl = 'https://mobile-stage.eatvio.ru'; +const String baseUrl = 'https://dev2.eatvio.com'; diff --git a/lib/features/registration/presentation/pages/city_of_living_screen.dart b/lib/features/registration/presentation/pages/city_of_living_screen.dart index 808c0cc..b4c8cbe 100644 --- a/lib/features/registration/presentation/pages/city_of_living_screen.dart +++ b/lib/features/registration/presentation/pages/city_of_living_screen.dart @@ -128,6 +128,8 @@ class _CityOfLivingScreenState extends State { final List locations = await context .read() .getLocationsByCoordinates(locationData.latitude.toString(), locationData.longitude.toString()); + final registrationCubit = context.read(); + registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(location: locations.first)); setState(() { cityController.text = locations.first; suggestionsController.suggestions = locations; 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 45b6bcd..3bae9e8 100644 --- a/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_bloc.dart +++ b/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_bloc.dart @@ -32,7 +32,7 @@ class GlossaryBloc extends Bloc { AppRouter.navigatorKey.currentContext?.goNamed('authScreen'); } final responseProductGroups = await http.get( - Uri.parse(baseUrl + '/api/glossary/getProductGroups'), + Uri.parse(baseUrl + '/api/glossaries/group/index'), headers: { 'Authorization': 'Bearer $token', }, -- 2.49.1 From 9cfd59b36f8cfdc4554642819988bcea7117ec87 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Wed, 31 Jul 2024 15:35:14 +0300 Subject: [PATCH 092/110] refactor(chat): fix chat null --- lib/core/initialization_cubit/initialization_cubit.dart | 4 ++-- .../bloc/chat_room_cubit/chat_room_cubit.dart | 3 ++- .../pages/chat_select_screen/bloc/chat_select_bloc.dart | 8 ++++---- .../pages/chat_select_screen/bloc/chat_select_state.dart | 4 ++++ .../pages/chat_select_screen/chat_select_screen.dart | 8 +------- .../presentation/pages/registration_screen.dart | 9 ++++++++- 6 files changed, 21 insertions(+), 15 deletions(-) diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index 4a1bcaf..29a42f6 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -17,7 +17,7 @@ class InitializationCubit extends Cubit { final privateNotificationChannel = await client.privateChannel( 'private-message-events.$userId', authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( - authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), + authorizationEndpoint: Uri.parse(baseUrl + '/broadcasting/auth'), headers: { 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, @@ -35,7 +35,7 @@ class InitializationCubit extends Cubit { final privateMessagesChannel = await client.privateChannel( 'private-new-chat-messages.$userId', authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( - authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), + authorizationEndpoint: Uri.parse(baseUrl + '/broadcasting/auth'), headers: { 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart index 3773c43..aaf9a4e 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart @@ -3,6 +3,7 @@ import 'dart:io'; import 'package:dart_pusher_channels/dart_pusher_channels.dart'; import 'package:easy_debounce/easy_debounce.dart'; +import 'package:eatvio_app/core/constants/constants.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_cubit.dart'; import 'package:eatvio_app/core/initialization_cubit/initialization_state.dart'; import 'package:eatvio_app/core/token_storage.dart'; @@ -87,7 +88,7 @@ class ChatRoomCubit extends Cubit { privateChatChannel = await client.privateChannel( 'private-direct-chat.$chatId', authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( - authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), + authorizationEndpoint: Uri.parse(baseUrl + '/broadcasting/auth'), headers: { 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, 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 8c60e60..2eaff04 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 @@ -14,6 +14,7 @@ import 'package:intl/intl.dart'; import '/core/app_export.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. @@ -27,16 +28,15 @@ class ChatSelectBloc extends Bloc { List fillChatEntryList(List chatRooms) { List chats = []; for (int i = 0; i < chatRooms.length; i++) { - String text = chatRooms[i]['last_message']['data']; - if (chatRooms[i]['last_message']['is_author_message_auth_user'] != null) { + String text = chatRooms[i]['last_message'] is List ? '' : chatRooms[i]['last_message']['data']; + if (chatRooms[i]['last_message'] is !List && chatRooms[i]['last_message']['is_author_message_auth_user'] != null) { text = "Вы: " + text; } chats.add( ChatItemModel( id: chatRooms[i]['id'], - userImage: chatRooms[i]['users']['to_chat_user']['profile_photo_path'], username: chatRooms[i]['users']['to_chat_user']['name'], - dateText: DateFormat('dd.MM').format( + dateText: chatRooms[i]['last_message'] is List ? '' : DateFormat('dd.MM').format( DateTime.parse( chatRooms[i]['last_message']['updated_at'], ), 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 2ee186f..9484c0f 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 @@ -12,6 +12,7 @@ class ChatSelectState extends Equatable { @override List get props => [chatSelectModelObj]; + ChatSelectState copyWith({ChatSelectModel? chatSelectModelObj}) { return ChatSelectState( chatSelectModelObj: chatSelectModelObj ?? this.chatSelectModelObj, @@ -29,11 +30,14 @@ class ChatSelectLoadedState extends ChatSelectState { this.searchController, this.chatSelectModelObj, }) : super(chatSelectModelObj: null); + List? chatRooms; TextEditingController? searchController; ChatSelectModel? chatSelectModelObj; + @override List get props => [chatSelectModelObj, chatRooms, searchController]; + ChatSelectLoadedState copyWith({ ChatSelectModel? chatSelectModelObj, TextEditingController? searchController, 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 5bbd1d7..fb48d2e 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 @@ -13,13 +13,7 @@ class ChatSelectScreen extends StatelessWidget { static Widget builder(BuildContext context) { return BlocProvider( - create: (context) => ChatSelectBloc( - ChatSelectState( - chatSelectModelObj: ChatSelectModel(), - ), - )..add( - ChatSelectInitialEvent(), - ), + create: (context) => ChatSelectBloc(ChatSelectState(chatSelectModelObj: ChatSelectModel()))..add(ChatSelectInitialEvent()), child: ChatSelectScreen(), ); } diff --git a/lib/features/registration/presentation/pages/registration_screen.dart b/lib/features/registration/presentation/pages/registration_screen.dart index 0856290..82e3135 100644 --- a/lib/features/registration/presentation/pages/registration_screen.dart +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -19,6 +19,7 @@ import 'package:eatvio_app/features/registration/presentation/pages/weight_scree import 'package:eatvio_app/locator_service.dart'; import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart'; import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; import 'package:validators/validators.dart'; class RegistrationScreen extends StatefulWidget { @@ -103,7 +104,13 @@ class _RegistrationScreenState extends State { ], ), appBar: AppBar( - automaticallyImplyLeading: true, + automaticallyImplyLeading: false, + leading: Builder( + builder: (context) => IconButton( + icon: Icon(Icons.close_rounded), + onPressed: () => GoRouter.of(context).pop(), + ), + ), centerTitle: true, title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio), actions: [ -- 2.49.1 From 2f1d6425dc5bfbf5dddac4480f7f448b29902888 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Wed, 31 Jul 2024 15:44:04 +0300 Subject: [PATCH 093/110] refactor(registration): remove username --- .../user_registration_model.dart | 1 - .../user_registration_model.freezed.dart | 31 +++---------------- .../user_registration_model.g.dart | 2 -- .../widgets/blog_post_widget.dart | 15 +++++++++ .../registration_cubit.dart | 1 - .../pages/credentials_screen.dart | 15 --------- .../pages/registration_screen.dart | 16 ++-------- 7 files changed, 22 insertions(+), 59 deletions(-) diff --git a/lib/data/models/userRegistrationModel/user_registration_model.dart b/lib/data/models/userRegistrationModel/user_registration_model.dart index a86d064..7a7fb3f 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.dart @@ -6,7 +6,6 @@ part 'user_registration_model.g.dart'; @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, diff --git a/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart b/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart index 70f656f..4a15327 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart @@ -21,7 +21,6 @@ UserRegistrationSheet _$UserRegistrationSheetFromJson( /// @nodoc mixin _$UserRegistrationSheet { - String get name => throw _privateConstructorUsedError; @JsonKey(name: 'first_name') String get firstName => throw _privateConstructorUsedError; @JsonKey(name: 'last_name') @@ -82,8 +81,7 @@ abstract class $UserRegistrationSheetCopyWith<$Res> { _$UserRegistrationSheetCopyWithImpl<$Res, UserRegistrationSheet>; @useResult $Res call( - {String name, - @JsonKey(name: 'first_name') String firstName, + {@JsonKey(name: 'first_name') String firstName, @JsonKey(name: 'last_name') String lastName, String email, String password, @@ -126,7 +124,6 @@ class _$UserRegistrationSheetCopyWithImpl<$Res, @pragma('vm:prefer-inline') @override $Res call({ - Object? name = null, Object? firstName = null, Object? lastName = null, Object? email = null, @@ -156,10 +153,6 @@ class _$UserRegistrationSheetCopyWithImpl<$Res, 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 @@ -282,8 +275,7 @@ abstract class _$$UserRegistrationSheetImplCopyWith<$Res> @override @useResult $Res call( - {String name, - @JsonKey(name: 'first_name') String firstName, + {@JsonKey(name: 'first_name') String firstName, @JsonKey(name: 'last_name') String lastName, String email, String password, @@ -324,7 +316,6 @@ class __$$UserRegistrationSheetImplCopyWithImpl<$Res> @pragma('vm:prefer-inline') @override $Res call({ - Object? name = null, Object? firstName = null, Object? lastName = null, Object? email = null, @@ -354,10 +345,6 @@ class __$$UserRegistrationSheetImplCopyWithImpl<$Res> 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 @@ -474,8 +461,7 @@ class __$$UserRegistrationSheetImplCopyWithImpl<$Res> @JsonSerializable() class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { const _$UserRegistrationSheetImpl( - {required this.name, - @JsonKey(name: 'first_name') required this.firstName, + {@JsonKey(name: 'first_name') required this.firstName, @JsonKey(name: 'last_name') required this.lastName, required this.email, required this.password, @@ -507,8 +493,6 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { factory _$UserRegistrationSheetImpl.fromJson(Map json) => _$$UserRegistrationSheetImplFromJson(json); - @override - final String name; @override @JsonKey(name: 'first_name') final String firstName; @@ -585,7 +569,7 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @override String toString() { - return 'UserRegistrationSheet(name: $name, firstName: $firstName, lastName: $lastName, email: $email, password: $password, passwordConfirmation: $passwordConfirmation, termsAccepted: $termsAccepted, birthdate: $birthdate, gender: $gender, location: $location, responseBody: $responseBody, 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)'; + return 'UserRegistrationSheet(firstName: $firstName, lastName: $lastName, email: $email, password: $password, passwordConfirmation: $passwordConfirmation, termsAccepted: $termsAccepted, birthdate: $birthdate, gender: $gender, location: $location, responseBody: $responseBody, 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 @@ -593,7 +577,6 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { 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) || @@ -648,7 +631,6 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @override int get hashCode => Object.hashAll([ runtimeType, - name, firstName, lastName, email, @@ -695,8 +677,7 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { abstract class _UserRegistrationSheet implements UserRegistrationSheet { const factory _UserRegistrationSheet( - {required final String name, - @JsonKey(name: 'first_name') required final String firstName, + {@JsonKey(name: 'first_name') required final String firstName, @JsonKey(name: 'last_name') required final String lastName, required final String email, required final String password, @@ -733,8 +714,6 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { factory _UserRegistrationSheet.fromJson(Map json) = _$UserRegistrationSheetImpl.fromJson; - @override - String get name; @override @JsonKey(name: 'first_name') String get firstName; diff --git a/lib/data/models/userRegistrationModel/user_registration_model.g.dart b/lib/data/models/userRegistrationModel/user_registration_model.g.dart index 6ca8a1c..9500e91 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.g.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.g.dart @@ -9,7 +9,6 @@ part of 'user_registration_model.dart'; _$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, @@ -43,7 +42,6 @@ _$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson( Map _$$UserRegistrationSheetImplToJson( _$UserRegistrationSheetImpl instance) => { - 'name': instance.name, 'first_name': instance.firstName, 'last_name': instance.lastName, 'email': instance.email, diff --git a/lib/features/feed/presentation/widgets/blog_post_widget.dart b/lib/features/feed/presentation/widgets/blog_post_widget.dart index 6bf0f7e..abfba97 100644 --- a/lib/features/feed/presentation/widgets/blog_post_widget.dart +++ b/lib/features/feed/presentation/widgets/blog_post_widget.dart @@ -87,6 +87,21 @@ class _BlogPostWidgetState extends State { _iconButton(Icons.mode_comment_outlined), SizedBox(width: 8), _iconButton(Icons.reply_rounded), + Spacer(), + Icon( + Icons.visibility_rounded, + size: 16, + color: appTheme.gray500, + ), + SizedBox(width: 4), + Text( + '0', + style: TextStyle( + fontSize: 12, + color: appTheme.gray500, + fontWeight: FontWeight.w400, + ), + ), ], ), ), diff --git a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart index dcad030..cbb2e16 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_cubit.dart @@ -13,7 +13,6 @@ class RegistrationCubit extends Cubit { : super( RegistrationState( sheet: UserRegistrationSheet( - name: '', firstName: '', lastName: '', email: '', diff --git a/lib/features/registration/presentation/pages/credentials_screen.dart b/lib/features/registration/presentation/pages/credentials_screen.dart index 7fa37be..dc9d548 100644 --- a/lib/features/registration/presentation/pages/credentials_screen.dart +++ b/lib/features/registration/presentation/pages/credentials_screen.dart @@ -16,8 +16,6 @@ class CredentialsScreen extends StatefulWidget { class _CredentialsScreenState extends State { final emailController = TextEditingController(); - final nameController = TextEditingController(); - final passwordController = TextEditingController(); final passwordConfirmationController = TextEditingController(); @@ -26,7 +24,6 @@ class _CredentialsScreenState extends State { void initState() { super.initState(); emailController.text = widget.sheet.email; - nameController.text = widget.sheet.name; passwordController.text = widget.sheet.password; passwordConfirmationController.text = widget.sheet.passwordConfirmation; } @@ -52,18 +49,6 @@ class _CredentialsScreenState extends State { }, ), SizedBox(height: 16), - Text("username".tr), - SizedBox(height: 4), - CustomTextFormField( - controller: nameController, - hintText: 'Введите имя пользователя', - textInputAction: TextInputAction.next, - onChanged: (newValue) { - final registrationCubit = context.read(); - registrationCubit.updateSheet(registrationCubit.state.sheet.copyWith(name: newValue)); - }, - ), - SizedBox(height: 16), Text("password".tr), SizedBox(height: 4), CustomTextFormField( diff --git a/lib/features/registration/presentation/pages/registration_screen.dart b/lib/features/registration/presentation/pages/registration_screen.dart index 82e3135..e95639a 100644 --- a/lib/features/registration/presentation/pages/registration_screen.dart +++ b/lib/features/registration/presentation/pages/registration_screen.dart @@ -177,7 +177,7 @@ class _RegistrationScreenState extends State { Future canGoNext(RegistrationState state) async { switch (step) { case 2: - List errors = validateCredentialsFields(state.sheet.email, state.sheet.name, state.sheet.password, state.sheet.passwordConfirmation); + List errors = validateCredentialsFields(state.sheet.email, state.sheet.password, state.sheet.passwordConfirmation); if (errors.isEmpty) { return true; } else { @@ -347,7 +347,7 @@ class _RegistrationScreenState extends State { return errors; } - List validateCredentialsFields(String email, String name, String password, String passwordConfirmation) { + List validateCredentialsFields(String email, String password, String passwordConfirmation) { List errors = []; if (!isEmail(email)) { @@ -358,18 +358,6 @@ class _RegistrationScreenState extends State { 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); } -- 2.49.1 From 264b10bd0da3e17eb65d6b640213fa8ecf7c1bd5 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Wed, 31 Jul 2024 17:41:38 +0300 Subject: [PATCH 094/110] feat(blogPost): add recipes --- lib/app_router.dart | 4 +- lib/features/feed/models/recipes_model.dart | 47 ++ .../feed/models/recipes_model.freezed.dart | 785 ++++++++++++++++++ lib/features/feed/models/recipes_model.g.dart | 72 ++ .../feed/models/recipes_pagination_model.dart | 27 + .../recipes_pagination_model.freezed.dart | 427 ++++++++++ .../models/recipes_pagination_model.g.dart | 43 + .../bloc/recipes_cubit/recipes_cubit.dart | 18 + .../bloc/recipes_cubit/recipes_state.dart | 19 + .../recipes_cubit/recipes_state.freezed.dart | 619 ++++++++++++++ .../feed/presentation/pages/feed_screen.dart | 521 +++++------- .../presentation/pages/feed_screen_new.dart | 214 ----- .../widgets/blog_post_widget.dart | 16 +- .../presentation/widgets/recipes_widget.dart | 187 +++++ .../feed/repositories/feed_repository.dart | 9 + lib/features/feed/services/feed_service.dart | 4 + .../feed/services/feed_service.g.dart | 27 + lib/locator_service.dart | 2 + lib/main.dart | 2 + 19 files changed, 2531 insertions(+), 512 deletions(-) create mode 100644 lib/features/feed/models/recipes_model.dart create mode 100644 lib/features/feed/models/recipes_model.freezed.dart create mode 100644 lib/features/feed/models/recipes_model.g.dart create mode 100644 lib/features/feed/models/recipes_pagination_model.dart create mode 100644 lib/features/feed/models/recipes_pagination_model.freezed.dart create mode 100644 lib/features/feed/models/recipes_pagination_model.g.dart create mode 100644 lib/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart create mode 100644 lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.dart create mode 100644 lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.freezed.dart delete mode 100644 lib/features/feed/presentation/pages/feed_screen_new.dart create mode 100644 lib/features/feed/presentation/widgets/recipes_widget.dart diff --git a/lib/app_router.dart b/lib/app_router.dart index 5eb1d0c..61fac3e 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -8,7 +8,7 @@ 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/diary/presentation/pages/diary_screen.dart'; -import 'package:eatvio_app/features/feed/presentation/pages/feed_screen_new.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/diets/diet_create_screen/diet_create_screen.dart'; @@ -65,7 +65,7 @@ class AppRouter { GoRoute( path: '/feed-screen', name: 'feedScreen', - builder: (context, state) => FeedScreenNew(), + builder: (context, state) => FeedScreen(), ), GoRoute( path: '/diary-screen', diff --git a/lib/features/feed/models/recipes_model.dart b/lib/features/feed/models/recipes_model.dart new file mode 100644 index 0000000..d654faf --- /dev/null +++ b/lib/features/feed/models/recipes_model.dart @@ -0,0 +1,47 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'recipes_model.freezed.dart'; +part 'recipes_model.g.dart'; + +@freezed +class Recipes with _$Recipes { + const factory Recipes({ + required int id, + required String image, + required String state, + @JsonKey(name: "cooking_time") required int cookingTime, + required List ingredients, + required String description, + required List steps, + @JsonKey(name: "video_url") required String videoUrl, + @JsonKey(name: "created_at") required DateTime createdAt, + @JsonKey(name: "updated_at") required DateTime updatedAt, + required String title, + required String type, + required String slug, + @JsonKey(name: "comments_count") required int commentsCount, + }) = _Recipes; + + factory Recipes.fromJson(Map json) => _$RecipesFromJson(json); +} + +@freezed +class Ingredient with _$Ingredient { + const factory Ingredient({ + required String name, + String? unit, + required String portion, + }) = _Ingredient; + + factory Ingredient.fromJson(Map json) => _$IngredientFromJson(json); +} + +@freezed +class Step with _$Step { + const factory Step({ + required String image, + required String description, + }) = _Step; + + factory Step.fromJson(Map json) => _$StepFromJson(json); +} diff --git a/lib/features/feed/models/recipes_model.freezed.dart b/lib/features/feed/models/recipes_model.freezed.dart new file mode 100644 index 0000000..cb55e50 --- /dev/null +++ b/lib/features/feed/models/recipes_model.freezed.dart @@ -0,0 +1,785 @@ +// 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 'recipes_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'); + +Recipes _$RecipesFromJson(Map json) { + return _Recipes.fromJson(json); +} + +/// @nodoc +mixin _$Recipes { + int get id => throw _privateConstructorUsedError; + String get image => throw _privateConstructorUsedError; + String get state => throw _privateConstructorUsedError; + @JsonKey(name: "cooking_time") + int get cookingTime => throw _privateConstructorUsedError; + List get ingredients => throw _privateConstructorUsedError; + String get description => throw _privateConstructorUsedError; + List get steps => throw _privateConstructorUsedError; + @JsonKey(name: "video_url") + String get videoUrl => throw _privateConstructorUsedError; + @JsonKey(name: "created_at") + DateTime get createdAt => throw _privateConstructorUsedError; + @JsonKey(name: "updated_at") + DateTime get updatedAt => throw _privateConstructorUsedError; + String get title => throw _privateConstructorUsedError; + String get type => throw _privateConstructorUsedError; + String get slug => throw _privateConstructorUsedError; + @JsonKey(name: "comments_count") + int get commentsCount => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $RecipesCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $RecipesCopyWith<$Res> { + factory $RecipesCopyWith(Recipes value, $Res Function(Recipes) then) = + _$RecipesCopyWithImpl<$Res, Recipes>; + @useResult + $Res call( + {int id, + String image, + String state, + @JsonKey(name: "cooking_time") int cookingTime, + List ingredients, + String description, + List steps, + @JsonKey(name: "video_url") String videoUrl, + @JsonKey(name: "created_at") DateTime createdAt, + @JsonKey(name: "updated_at") DateTime updatedAt, + String title, + String type, + String slug, + @JsonKey(name: "comments_count") int commentsCount}); +} + +/// @nodoc +class _$RecipesCopyWithImpl<$Res, $Val extends Recipes> + implements $RecipesCopyWith<$Res> { + _$RecipesCopyWithImpl(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 = null, + Object? image = null, + Object? state = null, + Object? cookingTime = null, + Object? ingredients = null, + Object? description = null, + Object? steps = null, + Object? videoUrl = null, + Object? createdAt = null, + Object? updatedAt = null, + Object? title = null, + Object? type = null, + Object? slug = null, + Object? commentsCount = null, + }) { + return _then(_value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + image: null == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as String, + state: null == state + ? _value.state + : state // ignore: cast_nullable_to_non_nullable + as String, + cookingTime: null == cookingTime + ? _value.cookingTime + : cookingTime // ignore: cast_nullable_to_non_nullable + as int, + ingredients: null == ingredients + ? _value.ingredients + : ingredients // ignore: cast_nullable_to_non_nullable + as List, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + steps: null == steps + ? _value.steps + : steps // ignore: cast_nullable_to_non_nullable + as List, + videoUrl: null == videoUrl + ? _value.videoUrl + : videoUrl // ignore: cast_nullable_to_non_nullable + as String, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + updatedAt: null == updatedAt + ? _value.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as DateTime, + title: null == title + ? _value.title + : title // ignore: cast_nullable_to_non_nullable + as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String, + slug: null == slug + ? _value.slug + : slug // ignore: cast_nullable_to_non_nullable + as String, + commentsCount: null == commentsCount + ? _value.commentsCount + : commentsCount // ignore: cast_nullable_to_non_nullable + as int, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$RecipesImplCopyWith<$Res> implements $RecipesCopyWith<$Res> { + factory _$$RecipesImplCopyWith( + _$RecipesImpl value, $Res Function(_$RecipesImpl) then) = + __$$RecipesImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {int id, + String image, + String state, + @JsonKey(name: "cooking_time") int cookingTime, + List ingredients, + String description, + List steps, + @JsonKey(name: "video_url") String videoUrl, + @JsonKey(name: "created_at") DateTime createdAt, + @JsonKey(name: "updated_at") DateTime updatedAt, + String title, + String type, + String slug, + @JsonKey(name: "comments_count") int commentsCount}); +} + +/// @nodoc +class __$$RecipesImplCopyWithImpl<$Res> + extends _$RecipesCopyWithImpl<$Res, _$RecipesImpl> + implements _$$RecipesImplCopyWith<$Res> { + __$$RecipesImplCopyWithImpl( + _$RecipesImpl _value, $Res Function(_$RecipesImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? image = null, + Object? state = null, + Object? cookingTime = null, + Object? ingredients = null, + Object? description = null, + Object? steps = null, + Object? videoUrl = null, + Object? createdAt = null, + Object? updatedAt = null, + Object? title = null, + Object? type = null, + Object? slug = null, + Object? commentsCount = null, + }) { + return _then(_$RecipesImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + image: null == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as String, + state: null == state + ? _value.state + : state // ignore: cast_nullable_to_non_nullable + as String, + cookingTime: null == cookingTime + ? _value.cookingTime + : cookingTime // ignore: cast_nullable_to_non_nullable + as int, + ingredients: null == ingredients + ? _value._ingredients + : ingredients // ignore: cast_nullable_to_non_nullable + as List, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + steps: null == steps + ? _value._steps + : steps // ignore: cast_nullable_to_non_nullable + as List, + videoUrl: null == videoUrl + ? _value.videoUrl + : videoUrl // ignore: cast_nullable_to_non_nullable + as String, + createdAt: null == createdAt + ? _value.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + updatedAt: null == updatedAt + ? _value.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as DateTime, + title: null == title + ? _value.title + : title // ignore: cast_nullable_to_non_nullable + as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String, + slug: null == slug + ? _value.slug + : slug // ignore: cast_nullable_to_non_nullable + as String, + commentsCount: null == commentsCount + ? _value.commentsCount + : commentsCount // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$RecipesImpl implements _Recipes { + const _$RecipesImpl( + {required this.id, + required this.image, + required this.state, + @JsonKey(name: "cooking_time") required this.cookingTime, + required final List ingredients, + required this.description, + required final List steps, + @JsonKey(name: "video_url") required this.videoUrl, + @JsonKey(name: "created_at") required this.createdAt, + @JsonKey(name: "updated_at") required this.updatedAt, + required this.title, + required this.type, + required this.slug, + @JsonKey(name: "comments_count") required this.commentsCount}) + : _ingredients = ingredients, + _steps = steps; + + factory _$RecipesImpl.fromJson(Map json) => + _$$RecipesImplFromJson(json); + + @override + final int id; + @override + final String image; + @override + final String state; + @override + @JsonKey(name: "cooking_time") + final int cookingTime; + final List _ingredients; + @override + List get ingredients { + if (_ingredients is EqualUnmodifiableListView) return _ingredients; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_ingredients); + } + + @override + final String description; + final List _steps; + @override + List get steps { + if (_steps is EqualUnmodifiableListView) return _steps; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_steps); + } + + @override + @JsonKey(name: "video_url") + final String videoUrl; + @override + @JsonKey(name: "created_at") + final DateTime createdAt; + @override + @JsonKey(name: "updated_at") + final DateTime updatedAt; + @override + final String title; + @override + final String type; + @override + final String slug; + @override + @JsonKey(name: "comments_count") + final int commentsCount; + + @override + String toString() { + return 'Recipes(id: $id, image: $image, state: $state, cookingTime: $cookingTime, ingredients: $ingredients, description: $description, steps: $steps, videoUrl: $videoUrl, createdAt: $createdAt, updatedAt: $updatedAt, title: $title, type: $type, slug: $slug, commentsCount: $commentsCount)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$RecipesImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.image, image) || other.image == image) && + (identical(other.state, state) || other.state == state) && + (identical(other.cookingTime, cookingTime) || + other.cookingTime == cookingTime) && + const DeepCollectionEquality() + .equals(other._ingredients, _ingredients) && + (identical(other.description, description) || + other.description == description) && + const DeepCollectionEquality().equals(other._steps, _steps) && + (identical(other.videoUrl, videoUrl) || + other.videoUrl == videoUrl) && + (identical(other.createdAt, createdAt) || + other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt) && + (identical(other.title, title) || other.title == title) && + (identical(other.type, type) || other.type == type) && + (identical(other.slug, slug) || other.slug == slug) && + (identical(other.commentsCount, commentsCount) || + other.commentsCount == commentsCount)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, + id, + image, + state, + cookingTime, + const DeepCollectionEquality().hash(_ingredients), + description, + const DeepCollectionEquality().hash(_steps), + videoUrl, + createdAt, + updatedAt, + title, + type, + slug, + commentsCount); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$RecipesImplCopyWith<_$RecipesImpl> get copyWith => + __$$RecipesImplCopyWithImpl<_$RecipesImpl>(this, _$identity); + + @override + Map toJson() { + return _$$RecipesImplToJson( + this, + ); + } +} + +abstract class _Recipes implements Recipes { + const factory _Recipes( + {required final int id, + required final String image, + required final String state, + @JsonKey(name: "cooking_time") required final int cookingTime, + required final List ingredients, + required final String description, + required final List steps, + @JsonKey(name: "video_url") required final String videoUrl, + @JsonKey(name: "created_at") required final DateTime createdAt, + @JsonKey(name: "updated_at") required final DateTime updatedAt, + required final String title, + required final String type, + required final String slug, + @JsonKey(name: "comments_count") required final int commentsCount}) = + _$RecipesImpl; + + factory _Recipes.fromJson(Map json) = _$RecipesImpl.fromJson; + + @override + int get id; + @override + String get image; + @override + String get state; + @override + @JsonKey(name: "cooking_time") + int get cookingTime; + @override + List get ingredients; + @override + String get description; + @override + List get steps; + @override + @JsonKey(name: "video_url") + String get videoUrl; + @override + @JsonKey(name: "created_at") + DateTime get createdAt; + @override + @JsonKey(name: "updated_at") + DateTime get updatedAt; + @override + String get title; + @override + String get type; + @override + String get slug; + @override + @JsonKey(name: "comments_count") + int get commentsCount; + @override + @JsonKey(ignore: true) + _$$RecipesImplCopyWith<_$RecipesImpl> get copyWith => + throw _privateConstructorUsedError; +} + +Ingredient _$IngredientFromJson(Map json) { + return _Ingredient.fromJson(json); +} + +/// @nodoc +mixin _$Ingredient { + String get name => throw _privateConstructorUsedError; + String? get unit => throw _privateConstructorUsedError; + String get portion => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $IngredientCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $IngredientCopyWith<$Res> { + factory $IngredientCopyWith( + Ingredient value, $Res Function(Ingredient) then) = + _$IngredientCopyWithImpl<$Res, Ingredient>; + @useResult + $Res call({String name, String? unit, String portion}); +} + +/// @nodoc +class _$IngredientCopyWithImpl<$Res, $Val extends Ingredient> + implements $IngredientCopyWith<$Res> { + _$IngredientCopyWithImpl(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? unit = freezed, + Object? portion = null, + }) { + return _then(_value.copyWith( + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + unit: freezed == unit + ? _value.unit + : unit // ignore: cast_nullable_to_non_nullable + as String?, + portion: null == portion + ? _value.portion + : portion // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$IngredientImplCopyWith<$Res> + implements $IngredientCopyWith<$Res> { + factory _$$IngredientImplCopyWith( + _$IngredientImpl value, $Res Function(_$IngredientImpl) then) = + __$$IngredientImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String name, String? unit, String portion}); +} + +/// @nodoc +class __$$IngredientImplCopyWithImpl<$Res> + extends _$IngredientCopyWithImpl<$Res, _$IngredientImpl> + implements _$$IngredientImplCopyWith<$Res> { + __$$IngredientImplCopyWithImpl( + _$IngredientImpl _value, $Res Function(_$IngredientImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? name = null, + Object? unit = freezed, + Object? portion = null, + }) { + return _then(_$IngredientImpl( + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + unit: freezed == unit + ? _value.unit + : unit // ignore: cast_nullable_to_non_nullable + as String?, + portion: null == portion + ? _value.portion + : portion // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$IngredientImpl implements _Ingredient { + const _$IngredientImpl( + {required this.name, this.unit, required this.portion}); + + factory _$IngredientImpl.fromJson(Map json) => + _$$IngredientImplFromJson(json); + + @override + final String name; + @override + final String? unit; + @override + final String portion; + + @override + String toString() { + return 'Ingredient(name: $name, unit: $unit, portion: $portion)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$IngredientImpl && + (identical(other.name, name) || other.name == name) && + (identical(other.unit, unit) || other.unit == unit) && + (identical(other.portion, portion) || other.portion == portion)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, name, unit, portion); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$IngredientImplCopyWith<_$IngredientImpl> get copyWith => + __$$IngredientImplCopyWithImpl<_$IngredientImpl>(this, _$identity); + + @override + Map toJson() { + return _$$IngredientImplToJson( + this, + ); + } +} + +abstract class _Ingredient implements Ingredient { + const factory _Ingredient( + {required final String name, + final String? unit, + required final String portion}) = _$IngredientImpl; + + factory _Ingredient.fromJson(Map json) = + _$IngredientImpl.fromJson; + + @override + String get name; + @override + String? get unit; + @override + String get portion; + @override + @JsonKey(ignore: true) + _$$IngredientImplCopyWith<_$IngredientImpl> get copyWith => + throw _privateConstructorUsedError; +} + +Step _$StepFromJson(Map json) { + return _Step.fromJson(json); +} + +/// @nodoc +mixin _$Step { + String get image => throw _privateConstructorUsedError; + String get description => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $StepCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $StepCopyWith<$Res> { + factory $StepCopyWith(Step value, $Res Function(Step) then) = + _$StepCopyWithImpl<$Res, Step>; + @useResult + $Res call({String image, String description}); +} + +/// @nodoc +class _$StepCopyWithImpl<$Res, $Val extends Step> + implements $StepCopyWith<$Res> { + _$StepCopyWithImpl(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? image = null, + Object? description = null, + }) { + return _then(_value.copyWith( + image: null == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as String, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$StepImplCopyWith<$Res> implements $StepCopyWith<$Res> { + factory _$$StepImplCopyWith( + _$StepImpl value, $Res Function(_$StepImpl) then) = + __$$StepImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String image, String description}); +} + +/// @nodoc +class __$$StepImplCopyWithImpl<$Res> + extends _$StepCopyWithImpl<$Res, _$StepImpl> + implements _$$StepImplCopyWith<$Res> { + __$$StepImplCopyWithImpl(_$StepImpl _value, $Res Function(_$StepImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? image = null, + Object? description = null, + }) { + return _then(_$StepImpl( + image: null == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as String, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$StepImpl implements _Step { + const _$StepImpl({required this.image, required this.description}); + + factory _$StepImpl.fromJson(Map json) => + _$$StepImplFromJson(json); + + @override + final String image; + @override + final String description; + + @override + String toString() { + return 'Step(image: $image, description: $description)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$StepImpl && + (identical(other.image, image) || other.image == image) && + (identical(other.description, description) || + other.description == description)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, image, description); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$StepImplCopyWith<_$StepImpl> get copyWith => + __$$StepImplCopyWithImpl<_$StepImpl>(this, _$identity); + + @override + Map toJson() { + return _$$StepImplToJson( + this, + ); + } +} + +abstract class _Step implements Step { + const factory _Step( + {required final String image, + required final String description}) = _$StepImpl; + + factory _Step.fromJson(Map json) = _$StepImpl.fromJson; + + @override + String get image; + @override + String get description; + @override + @JsonKey(ignore: true) + _$$StepImplCopyWith<_$StepImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/feed/models/recipes_model.g.dart b/lib/features/feed/models/recipes_model.g.dart new file mode 100644 index 0000000..74ecedf --- /dev/null +++ b/lib/features/feed/models/recipes_model.g.dart @@ -0,0 +1,72 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'recipes_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$RecipesImpl _$$RecipesImplFromJson(Map json) => + _$RecipesImpl( + id: (json['id'] as num).toInt(), + image: json['image'] as String, + state: json['state'] as String, + cookingTime: (json['cooking_time'] as num).toInt(), + ingredients: (json['ingredients'] as List) + .map((e) => Ingredient.fromJson(e as Map)) + .toList(), + description: json['description'] as String, + steps: (json['steps'] as List) + .map((e) => Step.fromJson(e as Map)) + .toList(), + videoUrl: json['video_url'] as String, + createdAt: DateTime.parse(json['created_at'] as String), + updatedAt: DateTime.parse(json['updated_at'] as String), + title: json['title'] as String, + type: json['type'] as String, + slug: json['slug'] as String, + commentsCount: (json['comments_count'] as num).toInt(), + ); + +Map _$$RecipesImplToJson(_$RecipesImpl instance) => + { + 'id': instance.id, + 'image': instance.image, + 'state': instance.state, + 'cooking_time': instance.cookingTime, + 'ingredients': instance.ingredients, + 'description': instance.description, + 'steps': instance.steps, + 'video_url': instance.videoUrl, + 'created_at': instance.createdAt.toIso8601String(), + 'updated_at': instance.updatedAt.toIso8601String(), + 'title': instance.title, + 'type': instance.type, + 'slug': instance.slug, + 'comments_count': instance.commentsCount, + }; + +_$IngredientImpl _$$IngredientImplFromJson(Map json) => + _$IngredientImpl( + name: json['name'] as String, + unit: json['unit'] as String?, + portion: json['portion'] as String, + ); + +Map _$$IngredientImplToJson(_$IngredientImpl instance) => + { + 'name': instance.name, + 'unit': instance.unit, + 'portion': instance.portion, + }; + +_$StepImpl _$$StepImplFromJson(Map json) => _$StepImpl( + image: json['image'] as String, + description: json['description'] as String, + ); + +Map _$$StepImplToJson(_$StepImpl instance) => + { + 'image': instance.image, + 'description': instance.description, + }; diff --git a/lib/features/feed/models/recipes_pagination_model.dart b/lib/features/feed/models/recipes_pagination_model.dart new file mode 100644 index 0000000..fb27b88 --- /dev/null +++ b/lib/features/feed/models/recipes_pagination_model.dart @@ -0,0 +1,27 @@ +import 'package:eatvio_app/features/feed/models/recipes_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'recipes_pagination_model.freezed.dart'; + +part 'recipes_pagination_model.g.dart'; + +@freezed +class RecipesPagination with _$RecipesPagination { + const factory RecipesPagination({ + @JsonKey(name: 'data') + required List recipesList, + @JsonKey(name: "current_page") required int currentPage, + @JsonKey(name: "first_page_url") required String firstPageUrl, + required int from, + @JsonKey(name: "last_page") required int lastPage, + @JsonKey(name: "last_page_url") required String lastPageUrl, + @JsonKey(name: "next_page_url") required String nextPageUrl, + required String path, + @JsonKey(name: "per_page") required int perPage, + @JsonKey(name: "prev_page_url") required dynamic prevPageUrl, + required int to, + required int total, + }) = _RecipesPagination; + + factory RecipesPagination.fromJson(Map json) => _$RecipesPaginationFromJson(json); +} diff --git a/lib/features/feed/models/recipes_pagination_model.freezed.dart b/lib/features/feed/models/recipes_pagination_model.freezed.dart new file mode 100644 index 0000000..272422c --- /dev/null +++ b/lib/features/feed/models/recipes_pagination_model.freezed.dart @@ -0,0 +1,427 @@ +// 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 'recipes_pagination_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'); + +RecipesPagination _$RecipesPaginationFromJson(Map json) { + return _RecipesPagination.fromJson(json); +} + +/// @nodoc +mixin _$RecipesPagination { + @JsonKey(name: 'data') + List get recipesList => throw _privateConstructorUsedError; + @JsonKey(name: "current_page") + int get currentPage => throw _privateConstructorUsedError; + @JsonKey(name: "first_page_url") + String get firstPageUrl => throw _privateConstructorUsedError; + int get from => throw _privateConstructorUsedError; + @JsonKey(name: "last_page") + int get lastPage => throw _privateConstructorUsedError; + @JsonKey(name: "last_page_url") + String get lastPageUrl => throw _privateConstructorUsedError; + @JsonKey(name: "next_page_url") + String get nextPageUrl => throw _privateConstructorUsedError; + String get path => throw _privateConstructorUsedError; + @JsonKey(name: "per_page") + int get perPage => throw _privateConstructorUsedError; + @JsonKey(name: "prev_page_url") + dynamic get prevPageUrl => throw _privateConstructorUsedError; + int get to => throw _privateConstructorUsedError; + int get total => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $RecipesPaginationCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $RecipesPaginationCopyWith<$Res> { + factory $RecipesPaginationCopyWith( + RecipesPagination value, $Res Function(RecipesPagination) then) = + _$RecipesPaginationCopyWithImpl<$Res, RecipesPagination>; + @useResult + $Res call( + {@JsonKey(name: 'data') List recipesList, + @JsonKey(name: "current_page") int currentPage, + @JsonKey(name: "first_page_url") String firstPageUrl, + int from, + @JsonKey(name: "last_page") int lastPage, + @JsonKey(name: "last_page_url") String lastPageUrl, + @JsonKey(name: "next_page_url") String nextPageUrl, + String path, + @JsonKey(name: "per_page") int perPage, + @JsonKey(name: "prev_page_url") dynamic prevPageUrl, + int to, + int total}); +} + +/// @nodoc +class _$RecipesPaginationCopyWithImpl<$Res, $Val extends RecipesPagination> + implements $RecipesPaginationCopyWith<$Res> { + _$RecipesPaginationCopyWithImpl(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? recipesList = null, + Object? currentPage = null, + Object? firstPageUrl = null, + Object? from = null, + Object? lastPage = null, + Object? lastPageUrl = null, + Object? nextPageUrl = null, + Object? path = null, + Object? perPage = null, + Object? prevPageUrl = freezed, + Object? to = null, + Object? total = null, + }) { + return _then(_value.copyWith( + recipesList: null == recipesList + ? _value.recipesList + : recipesList // ignore: cast_nullable_to_non_nullable + as List, + currentPage: null == currentPage + ? _value.currentPage + : currentPage // ignore: cast_nullable_to_non_nullable + as int, + firstPageUrl: null == firstPageUrl + ? _value.firstPageUrl + : firstPageUrl // ignore: cast_nullable_to_non_nullable + as String, + from: null == from + ? _value.from + : from // ignore: cast_nullable_to_non_nullable + as int, + lastPage: null == lastPage + ? _value.lastPage + : lastPage // ignore: cast_nullable_to_non_nullable + as int, + lastPageUrl: null == lastPageUrl + ? _value.lastPageUrl + : lastPageUrl // ignore: cast_nullable_to_non_nullable + as String, + nextPageUrl: null == nextPageUrl + ? _value.nextPageUrl + : nextPageUrl // ignore: cast_nullable_to_non_nullable + as String, + path: null == path + ? _value.path + : path // ignore: cast_nullable_to_non_nullable + as String, + perPage: null == perPage + ? _value.perPage + : perPage // ignore: cast_nullable_to_non_nullable + as int, + prevPageUrl: freezed == prevPageUrl + ? _value.prevPageUrl + : prevPageUrl // ignore: cast_nullable_to_non_nullable + as dynamic, + to: null == to + ? _value.to + : to // ignore: cast_nullable_to_non_nullable + as int, + total: null == total + ? _value.total + : total // ignore: cast_nullable_to_non_nullable + as int, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$RecipesPaginationImplCopyWith<$Res> + implements $RecipesPaginationCopyWith<$Res> { + factory _$$RecipesPaginationImplCopyWith(_$RecipesPaginationImpl value, + $Res Function(_$RecipesPaginationImpl) then) = + __$$RecipesPaginationImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {@JsonKey(name: 'data') List recipesList, + @JsonKey(name: "current_page") int currentPage, + @JsonKey(name: "first_page_url") String firstPageUrl, + int from, + @JsonKey(name: "last_page") int lastPage, + @JsonKey(name: "last_page_url") String lastPageUrl, + @JsonKey(name: "next_page_url") String nextPageUrl, + String path, + @JsonKey(name: "per_page") int perPage, + @JsonKey(name: "prev_page_url") dynamic prevPageUrl, + int to, + int total}); +} + +/// @nodoc +class __$$RecipesPaginationImplCopyWithImpl<$Res> + extends _$RecipesPaginationCopyWithImpl<$Res, _$RecipesPaginationImpl> + implements _$$RecipesPaginationImplCopyWith<$Res> { + __$$RecipesPaginationImplCopyWithImpl(_$RecipesPaginationImpl _value, + $Res Function(_$RecipesPaginationImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? recipesList = null, + Object? currentPage = null, + Object? firstPageUrl = null, + Object? from = null, + Object? lastPage = null, + Object? lastPageUrl = null, + Object? nextPageUrl = null, + Object? path = null, + Object? perPage = null, + Object? prevPageUrl = freezed, + Object? to = null, + Object? total = null, + }) { + return _then(_$RecipesPaginationImpl( + recipesList: null == recipesList + ? _value._recipesList + : recipesList // ignore: cast_nullable_to_non_nullable + as List, + currentPage: null == currentPage + ? _value.currentPage + : currentPage // ignore: cast_nullable_to_non_nullable + as int, + firstPageUrl: null == firstPageUrl + ? _value.firstPageUrl + : firstPageUrl // ignore: cast_nullable_to_non_nullable + as String, + from: null == from + ? _value.from + : from // ignore: cast_nullable_to_non_nullable + as int, + lastPage: null == lastPage + ? _value.lastPage + : lastPage // ignore: cast_nullable_to_non_nullable + as int, + lastPageUrl: null == lastPageUrl + ? _value.lastPageUrl + : lastPageUrl // ignore: cast_nullable_to_non_nullable + as String, + nextPageUrl: null == nextPageUrl + ? _value.nextPageUrl + : nextPageUrl // ignore: cast_nullable_to_non_nullable + as String, + path: null == path + ? _value.path + : path // ignore: cast_nullable_to_non_nullable + as String, + perPage: null == perPage + ? _value.perPage + : perPage // ignore: cast_nullable_to_non_nullable + as int, + prevPageUrl: freezed == prevPageUrl + ? _value.prevPageUrl + : prevPageUrl // ignore: cast_nullable_to_non_nullable + as dynamic, + to: null == to + ? _value.to + : to // ignore: cast_nullable_to_non_nullable + as int, + total: null == total + ? _value.total + : total // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$RecipesPaginationImpl implements _RecipesPagination { + const _$RecipesPaginationImpl( + {@JsonKey(name: 'data') required final List recipesList, + @JsonKey(name: "current_page") required this.currentPage, + @JsonKey(name: "first_page_url") required this.firstPageUrl, + required this.from, + @JsonKey(name: "last_page") required this.lastPage, + @JsonKey(name: "last_page_url") required this.lastPageUrl, + @JsonKey(name: "next_page_url") required this.nextPageUrl, + required this.path, + @JsonKey(name: "per_page") required this.perPage, + @JsonKey(name: "prev_page_url") required this.prevPageUrl, + required this.to, + required this.total}) + : _recipesList = recipesList; + + factory _$RecipesPaginationImpl.fromJson(Map json) => + _$$RecipesPaginationImplFromJson(json); + + final List _recipesList; + @override + @JsonKey(name: 'data') + List get recipesList { + if (_recipesList is EqualUnmodifiableListView) return _recipesList; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_recipesList); + } + + @override + @JsonKey(name: "current_page") + final int currentPage; + @override + @JsonKey(name: "first_page_url") + final String firstPageUrl; + @override + final int from; + @override + @JsonKey(name: "last_page") + final int lastPage; + @override + @JsonKey(name: "last_page_url") + final String lastPageUrl; + @override + @JsonKey(name: "next_page_url") + final String nextPageUrl; + @override + final String path; + @override + @JsonKey(name: "per_page") + final int perPage; + @override + @JsonKey(name: "prev_page_url") + final dynamic prevPageUrl; + @override + final int to; + @override + final int total; + + @override + String toString() { + return 'RecipesPagination(recipesList: $recipesList, currentPage: $currentPage, firstPageUrl: $firstPageUrl, from: $from, lastPage: $lastPage, lastPageUrl: $lastPageUrl, nextPageUrl: $nextPageUrl, path: $path, perPage: $perPage, prevPageUrl: $prevPageUrl, to: $to, total: $total)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$RecipesPaginationImpl && + const DeepCollectionEquality() + .equals(other._recipesList, _recipesList) && + (identical(other.currentPage, currentPage) || + other.currentPage == currentPage) && + (identical(other.firstPageUrl, firstPageUrl) || + other.firstPageUrl == firstPageUrl) && + (identical(other.from, from) || other.from == from) && + (identical(other.lastPage, lastPage) || + other.lastPage == lastPage) && + (identical(other.lastPageUrl, lastPageUrl) || + other.lastPageUrl == lastPageUrl) && + (identical(other.nextPageUrl, nextPageUrl) || + other.nextPageUrl == nextPageUrl) && + (identical(other.path, path) || other.path == path) && + (identical(other.perPage, perPage) || other.perPage == perPage) && + const DeepCollectionEquality() + .equals(other.prevPageUrl, prevPageUrl) && + (identical(other.to, to) || other.to == to) && + (identical(other.total, total) || other.total == total)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_recipesList), + currentPage, + firstPageUrl, + from, + lastPage, + lastPageUrl, + nextPageUrl, + path, + perPage, + const DeepCollectionEquality().hash(prevPageUrl), + to, + total); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$RecipesPaginationImplCopyWith<_$RecipesPaginationImpl> get copyWith => + __$$RecipesPaginationImplCopyWithImpl<_$RecipesPaginationImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$RecipesPaginationImplToJson( + this, + ); + } +} + +abstract class _RecipesPagination implements RecipesPagination { + const factory _RecipesPagination( + {@JsonKey(name: 'data') required final List recipesList, + @JsonKey(name: "current_page") required final int currentPage, + @JsonKey(name: "first_page_url") required final String firstPageUrl, + required final int from, + @JsonKey(name: "last_page") required final int lastPage, + @JsonKey(name: "last_page_url") required final String lastPageUrl, + @JsonKey(name: "next_page_url") required final String nextPageUrl, + required final String path, + @JsonKey(name: "per_page") required final int perPage, + @JsonKey(name: "prev_page_url") required final dynamic prevPageUrl, + required final int to, + required final int total}) = _$RecipesPaginationImpl; + + factory _RecipesPagination.fromJson(Map json) = + _$RecipesPaginationImpl.fromJson; + + @override + @JsonKey(name: 'data') + List get recipesList; + @override + @JsonKey(name: "current_page") + int get currentPage; + @override + @JsonKey(name: "first_page_url") + String get firstPageUrl; + @override + int get from; + @override + @JsonKey(name: "last_page") + int get lastPage; + @override + @JsonKey(name: "last_page_url") + String get lastPageUrl; + @override + @JsonKey(name: "next_page_url") + String get nextPageUrl; + @override + String get path; + @override + @JsonKey(name: "per_page") + int get perPage; + @override + @JsonKey(name: "prev_page_url") + dynamic get prevPageUrl; + @override + int get to; + @override + int get total; + @override + @JsonKey(ignore: true) + _$$RecipesPaginationImplCopyWith<_$RecipesPaginationImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/feed/models/recipes_pagination_model.g.dart b/lib/features/feed/models/recipes_pagination_model.g.dart new file mode 100644 index 0000000..d1e483f --- /dev/null +++ b/lib/features/feed/models/recipes_pagination_model.g.dart @@ -0,0 +1,43 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'recipes_pagination_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$RecipesPaginationImpl _$$RecipesPaginationImplFromJson( + Map json) => + _$RecipesPaginationImpl( + recipesList: (json['data'] as List) + .map((e) => Recipes.fromJson(e as Map)) + .toList(), + currentPage: (json['current_page'] as num).toInt(), + firstPageUrl: json['first_page_url'] as String, + from: (json['from'] as num).toInt(), + lastPage: (json['last_page'] as num).toInt(), + lastPageUrl: json['last_page_url'] as String, + nextPageUrl: json['next_page_url'] as String, + path: json['path'] as String, + perPage: (json['per_page'] as num).toInt(), + prevPageUrl: json['prev_page_url'], + to: (json['to'] as num).toInt(), + total: (json['total'] as num).toInt(), + ); + +Map _$$RecipesPaginationImplToJson( + _$RecipesPaginationImpl instance) => + { + 'data': instance.recipesList, + 'current_page': instance.currentPage, + 'first_page_url': instance.firstPageUrl, + 'from': instance.from, + 'last_page': instance.lastPage, + 'last_page_url': instance.lastPageUrl, + 'next_page_url': instance.nextPageUrl, + 'path': instance.path, + 'per_page': instance.perPage, + 'prev_page_url': instance.prevPageUrl, + 'to': instance.to, + 'total': instance.total, + }; diff --git a/lib/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart b/lib/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart new file mode 100644 index 0000000..8d8aeb2 --- /dev/null +++ b/lib/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart @@ -0,0 +1,18 @@ +import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes_state.dart'; +import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +class RecipesCubit extends Cubit { + final FeedRepository feedRepository; + + RecipesCubit({required this.feedRepository}) : super(const RecipesState.loading()); + + loadRecipesList() async { + try { + final recipesList = await feedRepository.getRecipes(); + emit(RecipesState.loaded(recipesList: recipesList)); + } catch (e) { + emit(RecipesState.error(errorMessage: e.toString())); + } + } +} \ No newline at end of file diff --git a/lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.dart b/lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.dart new file mode 100644 index 0000000..ecdf17c --- /dev/null +++ b/lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.dart @@ -0,0 +1,19 @@ +import 'package:eatvio_app/features/feed/models/recipes_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'recipes_state.freezed.dart'; + +@freezed +abstract class RecipesState with _$RecipesState { + const factory RecipesState() = _RecipesState; + + const factory RecipesState.loading() = RecipesStateLoading; + + const factory RecipesState.loaded({ + required List recipesList, + }) = RecipesStateLoaded; + + const factory RecipesState.error({ + required String errorMessage, + }) = RecipesStateError; +} diff --git a/lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.freezed.dart b/lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.freezed.dart new file mode 100644 index 0000000..e8aa88e --- /dev/null +++ b/lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.freezed.dart @@ -0,0 +1,619 @@ +// 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 'recipes_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 _$RecipesState { + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(List recipesList) loaded, + required TResult Function(String errorMessage) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(List recipesList)? loaded, + TResult? Function(String errorMessage)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(List recipesList)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map( + TResult Function(_RecipesState value) $default, { + required TResult Function(RecipesStateLoading value) loading, + required TResult Function(RecipesStateLoaded value) loaded, + required TResult Function(RecipesStateError value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_RecipesState value)? $default, { + TResult? Function(RecipesStateLoading value)? loading, + TResult? Function(RecipesStateLoaded value)? loaded, + TResult? Function(RecipesStateError value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap( + TResult Function(_RecipesState value)? $default, { + TResult Function(RecipesStateLoading value)? loading, + TResult Function(RecipesStateLoaded value)? loaded, + TResult Function(RecipesStateError value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $RecipesStateCopyWith<$Res> { + factory $RecipesStateCopyWith( + RecipesState value, $Res Function(RecipesState) then) = + _$RecipesStateCopyWithImpl<$Res, RecipesState>; +} + +/// @nodoc +class _$RecipesStateCopyWithImpl<$Res, $Val extends RecipesState> + implements $RecipesStateCopyWith<$Res> { + _$RecipesStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; +} + +/// @nodoc +abstract class _$$RecipesStateImplCopyWith<$Res> { + factory _$$RecipesStateImplCopyWith( + _$RecipesStateImpl value, $Res Function(_$RecipesStateImpl) then) = + __$$RecipesStateImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$RecipesStateImplCopyWithImpl<$Res> + extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateImpl> + implements _$$RecipesStateImplCopyWith<$Res> { + __$$RecipesStateImplCopyWithImpl( + _$RecipesStateImpl _value, $Res Function(_$RecipesStateImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$RecipesStateImpl implements _RecipesState { + const _$RecipesStateImpl(); + + @override + String toString() { + return 'RecipesState()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$RecipesStateImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(List recipesList) loaded, + required TResult Function(String errorMessage) error, + }) { + return $default(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(List recipesList)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return $default?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(List recipesList)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_RecipesState value) $default, { + required TResult Function(RecipesStateLoading value) loading, + required TResult Function(RecipesStateLoaded value) loaded, + required TResult Function(RecipesStateError value) error, + }) { + return $default(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_RecipesState value)? $default, { + TResult? Function(RecipesStateLoading value)? loading, + TResult? Function(RecipesStateLoaded value)? loaded, + TResult? Function(RecipesStateError value)? error, + }) { + return $default?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_RecipesState value)? $default, { + TResult Function(RecipesStateLoading value)? loading, + TResult Function(RecipesStateLoaded value)? loaded, + TResult Function(RecipesStateError value)? error, + required TResult orElse(), + }) { + if ($default != null) { + return $default(this); + } + return orElse(); + } +} + +abstract class _RecipesState implements RecipesState { + const factory _RecipesState() = _$RecipesStateImpl; +} + +/// @nodoc +abstract class _$$RecipesStateLoadingImplCopyWith<$Res> { + factory _$$RecipesStateLoadingImplCopyWith(_$RecipesStateLoadingImpl value, + $Res Function(_$RecipesStateLoadingImpl) then) = + __$$RecipesStateLoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$RecipesStateLoadingImplCopyWithImpl<$Res> + extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateLoadingImpl> + implements _$$RecipesStateLoadingImplCopyWith<$Res> { + __$$RecipesStateLoadingImplCopyWithImpl(_$RecipesStateLoadingImpl _value, + $Res Function(_$RecipesStateLoadingImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$RecipesStateLoadingImpl implements RecipesStateLoading { + const _$RecipesStateLoadingImpl(); + + @override + String toString() { + return 'RecipesState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$RecipesStateLoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(List recipesList) loaded, + required TResult Function(String errorMessage) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(List recipesList)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(List recipesList)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_RecipesState value) $default, { + required TResult Function(RecipesStateLoading value) loading, + required TResult Function(RecipesStateLoaded value) loaded, + required TResult Function(RecipesStateError value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_RecipesState value)? $default, { + TResult? Function(RecipesStateLoading value)? loading, + TResult? Function(RecipesStateLoaded value)? loaded, + TResult? Function(RecipesStateError value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_RecipesState value)? $default, { + TResult Function(RecipesStateLoading value)? loading, + TResult Function(RecipesStateLoaded value)? loaded, + TResult Function(RecipesStateError value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class RecipesStateLoading implements RecipesState { + const factory RecipesStateLoading() = _$RecipesStateLoadingImpl; +} + +/// @nodoc +abstract class _$$RecipesStateLoadedImplCopyWith<$Res> { + factory _$$RecipesStateLoadedImplCopyWith(_$RecipesStateLoadedImpl value, + $Res Function(_$RecipesStateLoadedImpl) then) = + __$$RecipesStateLoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({List recipesList}); +} + +/// @nodoc +class __$$RecipesStateLoadedImplCopyWithImpl<$Res> + extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateLoadedImpl> + implements _$$RecipesStateLoadedImplCopyWith<$Res> { + __$$RecipesStateLoadedImplCopyWithImpl(_$RecipesStateLoadedImpl _value, + $Res Function(_$RecipesStateLoadedImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? recipesList = null, + }) { + return _then(_$RecipesStateLoadedImpl( + recipesList: null == recipesList + ? _value._recipesList + : recipesList // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class _$RecipesStateLoadedImpl implements RecipesStateLoaded { + const _$RecipesStateLoadedImpl({required final List recipesList}) + : _recipesList = recipesList; + + final List _recipesList; + @override + List get recipesList { + if (_recipesList is EqualUnmodifiableListView) return _recipesList; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_recipesList); + } + + @override + String toString() { + return 'RecipesState.loaded(recipesList: $recipesList)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$RecipesStateLoadedImpl && + const DeepCollectionEquality() + .equals(other._recipesList, _recipesList)); + } + + @override + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_recipesList)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$RecipesStateLoadedImplCopyWith<_$RecipesStateLoadedImpl> get copyWith => + __$$RecipesStateLoadedImplCopyWithImpl<_$RecipesStateLoadedImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(List recipesList) loaded, + required TResult Function(String errorMessage) error, + }) { + return loaded(recipesList); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(List recipesList)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return loaded?.call(recipesList); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(List recipesList)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(recipesList); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_RecipesState value) $default, { + required TResult Function(RecipesStateLoading value) loading, + required TResult Function(RecipesStateLoaded value) loaded, + required TResult Function(RecipesStateError value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_RecipesState value)? $default, { + TResult? Function(RecipesStateLoading value)? loading, + TResult? Function(RecipesStateLoaded value)? loaded, + TResult? Function(RecipesStateError value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_RecipesState value)? $default, { + TResult Function(RecipesStateLoading value)? loading, + TResult Function(RecipesStateLoaded value)? loaded, + TResult Function(RecipesStateError value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class RecipesStateLoaded implements RecipesState { + const factory RecipesStateLoaded({required final List recipesList}) = + _$RecipesStateLoadedImpl; + + List get recipesList; + @JsonKey(ignore: true) + _$$RecipesStateLoadedImplCopyWith<_$RecipesStateLoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$RecipesStateErrorImplCopyWith<$Res> { + factory _$$RecipesStateErrorImplCopyWith(_$RecipesStateErrorImpl value, + $Res Function(_$RecipesStateErrorImpl) then) = + __$$RecipesStateErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String errorMessage}); +} + +/// @nodoc +class __$$RecipesStateErrorImplCopyWithImpl<$Res> + extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateErrorImpl> + implements _$$RecipesStateErrorImplCopyWith<$Res> { + __$$RecipesStateErrorImplCopyWithImpl(_$RecipesStateErrorImpl _value, + $Res Function(_$RecipesStateErrorImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? errorMessage = null, + }) { + return _then(_$RecipesStateErrorImpl( + errorMessage: null == errorMessage + ? _value.errorMessage + : errorMessage // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$RecipesStateErrorImpl implements RecipesStateError { + const _$RecipesStateErrorImpl({required this.errorMessage}); + + @override + final String errorMessage; + + @override + String toString() { + return 'RecipesState.error(errorMessage: $errorMessage)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$RecipesStateErrorImpl && + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); + } + + @override + int get hashCode => Object.hash(runtimeType, errorMessage); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$RecipesStateErrorImplCopyWith<_$RecipesStateErrorImpl> get copyWith => + __$$RecipesStateErrorImplCopyWithImpl<_$RecipesStateErrorImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when( + TResult Function() $default, { + required TResult Function() loading, + required TResult Function(List recipesList) loaded, + required TResult Function(String errorMessage) error, + }) { + return error(errorMessage); + } + + @override + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function()? $default, { + TResult? Function()? loading, + TResult? Function(List recipesList)? loaded, + TResult? Function(String errorMessage)? error, + }) { + return error?.call(errorMessage); + } + + @override + @optionalTypeArgs + TResult maybeWhen( + TResult Function()? $default, { + TResult Function()? loading, + TResult Function(List recipesList)? loaded, + TResult Function(String errorMessage)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(errorMessage); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map( + TResult Function(_RecipesState value) $default, { + required TResult Function(RecipesStateLoading value) loading, + required TResult Function(RecipesStateLoaded value) loaded, + required TResult Function(RecipesStateError value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_RecipesState value)? $default, { + TResult? Function(RecipesStateLoading value)? loading, + TResult? Function(RecipesStateLoaded value)? loaded, + TResult? Function(RecipesStateError value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap( + TResult Function(_RecipesState value)? $default, { + TResult Function(RecipesStateLoading value)? loading, + TResult Function(RecipesStateLoaded value)? loaded, + TResult Function(RecipesStateError value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class RecipesStateError implements RecipesState { + const factory RecipesStateError({required final String errorMessage}) = + _$RecipesStateErrorImpl; + + String get errorMessage; + @JsonKey(ignore: true) + _$$RecipesStateErrorImplCopyWith<_$RecipesStateErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/feed/presentation/pages/feed_screen.dart b/lib/features/feed/presentation/pages/feed_screen.dart index 93697eb..cb6c714 100644 --- a/lib/features/feed/presentation/pages/feed_screen.dart +++ b/lib/features/feed/presentation/pages/feed_screen.dart @@ -1,323 +1,256 @@ -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: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/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart'; +import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes_state.dart'; +import 'package:eatvio_app/features/feed/presentation/widgets/blog_post_widget.dart'; +import 'package:eatvio_app/features/feed/presentation/widgets/recipes_widget.dart'; +import 'package:eatvio_app/theme/theme_helper.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; -import 'package:intl/intl.dart'; -class FeedScreen extends StatelessWidget { +class FeedScreen extends StatefulWidget { + const FeedScreen({super.key}); + + @override + State createState() => _FeedScreenState(); +} + +class _FeedScreenState extends State { + final List chipsLabelList = ['Все', 'Рецепты', 'Диеты', 'Планы питания', 'Консультанты']; + + int _selectedChipIndex = 0; + + @override Widget build(BuildContext context) { - return BlocBuilder( - builder: (BuildContext context, FeedState state) { - if (state is FeedStateLoaded) { - return _buildFeedScreen(context, state); - } else if (state is FeedStateError) { - return Scaffold( - body: Padding( - padding: const EdgeInsets.all(16), - child: Center( - child: Text(state.errorMessage), - ), - ), - ); - } else { - return Scaffold( - body: Center( - child: CupertinoActivityIndicator(), - ), - ); - } - }, - ); - } - - _buildFeedScreen(BuildContext context, FeedStateLoaded state) { - mediaQueryData = MediaQuery.of(context); - return RefreshIndicator( - onRefresh: () => context.read().loadFeedBlogPostList(), - child: Scaffold( - appBar: AppBar( - toolbarHeight: 0, + return Scaffold( + appBar: AppBar( + backgroundColor: Colors.white, + toolbarHeight: 0, + systemOverlayStyle: SystemUiOverlayStyle( + statusBarColor: Colors.white, ), - backgroundColor: Colors.grey[200], - resizeToAvoidBottomInset: true, - body: SingleChildScrollView( - child: Container( - width: double.maxFinite, - decoration: BoxDecoration(color: Colors.grey[200]), - child: Padding( - padding: EdgeInsets.all(16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, + ), + backgroundColor: Colors.grey.shade200, + body: NestedScrollView( + headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { + return [ + SliverAppBar( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(bottom: Radius.circular(12)), + ), + backgroundColor: Colors.white, + foregroundColor: Colors.white, + automaticallyImplyLeading: false, + stretchTriggerOffset: 1, + floating: true, + snap: true, + scrolledUnderElevation: 0, + bottom: _chipGroup(), + title: Row( children: [ - SizedBox(height: 20), - _buildSearch(context), - SizedBox(height: 20), - _buildMenu(context, state), - SizedBox(height: 20), - _buildBlogPostList(context, state), + _searchBar(), + SizedBox(width: 12), + _addBlogPostButton(), ], ), ), + ]; + }, + body: _selectedChipIndex == 0 ? _buildAllBlogPosts() : _buildAllRecipes(), + ), + ); + } + + _buildAllBlogPosts() { + return RefreshIndicator( + onRefresh: () => context.read().loadFeedBlogPostList(), + child: BlocBuilder( + builder: (BuildContext context, FeedState state) { + if (state is FeedStateLoaded) { + return ListView.separated( + padding: EdgeInsets.symmetric(vertical: 8), + shrinkWrap: true, + physics: BouncingScrollPhysics(), + itemBuilder: (context, index) { + return BlogPostWidget(feedBlogPostModel: state.feedBlogPostList[index]); + }, + separatorBuilder: (context, index) { + return SizedBox(height: 8); + }, + itemCount: state.feedBlogPostList.length, + ); + } else if (state is FeedStateError) { + return Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: Center( + child: Text(state.errorMessage), + ), + ), + ); + } else { + return Scaffold( + body: Center( + child: CupertinoActivityIndicator(), + ), + ); + } + }, + ), + ); + } + + _buildAllRecipes() { + return RefreshIndicator( + onRefresh: () => context.read().loadRecipesList(), + child: BlocBuilder( + builder: (BuildContext context, RecipesState state) { + if (state is RecipesStateLoaded) { + return ListView.separated( + padding: EdgeInsets.symmetric(vertical: 8), + shrinkWrap: true, + physics: BouncingScrollPhysics(), + itemBuilder: (context, index) { + return RecipesWidget(recipes: state.recipesList[index]); + }, + separatorBuilder: (context, index) { + return SizedBox(height: 8); + }, + itemCount: state.recipesList.length, + ); + } else if (state is RecipesStateError) { + return Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: Center( + child: Text(state.errorMessage), + ), + ), + ); + } else { + return Scaffold( + body: Center( + child: CupertinoActivityIndicator(), + ), + ); + } + }, + ), + ); + } + + _chipGroup() { + return PreferredSize( + preferredSize: Size(MediaQuery.of(context).size.width, 32), + child: Align( + alignment: Alignment.centerLeft, + child: SingleChildScrollView( + padding: EdgeInsets.symmetric(horizontal: 16), + scrollDirection: Axis.horizontal, + child: Row( + children: [ + _choiceChipWidget(0), + SizedBox(width: 8), + _choiceChipWidget(1), + SizedBox(width: 8), + _choiceChipWidget(2), + SizedBox(width: 8), + _choiceChipWidget(3), + SizedBox(width: 8), + _choiceChipWidget(4), + ], ), ), ), ); } - _buildSearch(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: 2, - blurRadius: 5, - offset: Offset(0, 3), - ), - ], + _addBlogPostButton() { + return InkWell( + onTap: () => GoRouter.of(context).pushNamed('blogPostCreateScreen'), + borderRadius: BorderRadius.circular(64), + child: Ink( + decoration: BoxDecoration( + color: appTheme.blueA400, + shape: BoxShape.circle, + ), + child: Icon( + Icons.add_rounded, + color: appTheme.gray100, + ), + width: 40, + height: 40, ), - child: Padding( - padding: const EdgeInsets.all(12.0), - child: Column( - children: [ - CustomSearchView( - hintText: "Поиск записей", - ), - SizedBox(height: 10), - Row( - children: [ - Flexible( - flex: 5, - child: CustomOutlinedButton( - text: "Найти запись", - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - ), - ), - SizedBox(width: 8), // Add some spacing between the buttons - Flexible( - flex: 1, - child: CustomOutlinedButton( - text: "+", - onPressed: () => GoRouter.of(context).pushNamed('blogPostCreateScreen'), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - ), - ), - ], - ), - ], + ); + } + + _searchBar() { + return SizedBox( + height: 40, + width: MediaQuery.of(context).size.width - 84, + child: TextFormField( + style: TextStyle( + fontSize: 12, + ), + decoration: InputDecoration( + hintText: 'Поиск', + hintStyle: TextStyle( + fontSize: 12, + color: appTheme.gray600, + fontWeight: FontWeight.w400, + ), + prefixIcon: Icon( + Icons.search, + color: appTheme.gray600, + size: 16, + ), + isDense: false, + contentPadding: EdgeInsets.all(8), + fillColor: appTheme.gray100, + filled: true, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(16), + borderSide: BorderSide.none, + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(16), + borderSide: BorderSide.none, + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(16), + borderSide: BorderSide.none, + ), ), ), ); } - _buildBlogPostList(BuildContext context, FeedStateLoaded state) { - List postWidgets = []; - - for (var post in state.feedBlogPostList) { - postWidgets.add(_buildFeedEntry(post, context)); - } - - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: postWidgets, - ); - } - - _buildFeedEntry(FeedBlogPostModel post, 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: 2, - blurRadius: 5, - offset: Offset(0, 3), - ), - ], + _choiceChipWidget(int index) { + return ChoiceChip( + selectedColor: appTheme.blueA400, + pressElevation: 0, + showCheckmark: false, + side: BorderSide.none, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), ), - child: Column( - children: [ - ListTile( - leading: CachedNetworkImage( - imageUrl: baseUrl + '/storage/' + (''), - - /// todo profile photo path - imageBuilder: (context, imageProvider) => CircleAvatar( - backgroundImage: imageProvider, - radius: 24, - ), - placeholder: (context, url) => CircleAvatar( - child: Icon(Icons.person), - backgroundColor: Colors.white, - radius: 24, - ), - errorWidget: (context, url, error) => CircleAvatar( - child: Icon(Icons.person), - backgroundColor: Colors.white, - radius: 24, - ), - ), - title: Text( - 'Authorae', - - /// todo author name - style: CustomTextStyles.titleMediumSemiBold, - ), - subtitle: Text( - DateFormat('dd.MM.yyyy').format(post.updatedAt), - style: theme.textTheme.bodyMedium, - ), - onTap: () => GoRouter.of(context).goNamed( - 'blogPostScreen', - extra: post.id.toString(), - ), - trailing: PopupMenuButton( - onSelected: (value) => print("tap"), - itemBuilder: (BuildContext context) => >[ - PopupMenuItem( - value: 'edit', - child: Text('Редактировать'), - ), - PopupMenuItem( - value: 'delete', - child: Text('Удалить'), - ), - ], - ), - ), - Padding( - padding: const EdgeInsets.all(16.0), - child: Column( - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Spacer(), - Align( - alignment: Alignment.center, - child: Text( - post.title, - style: CustomTextStyles.titleMediumBlack, - ), - ), - Spacer(), - ], - ), - SizedBox(height: 8.0), - Text( - post.description, - style: CustomTextStyles.bodyMediumBluegray800, - ), - SizedBox(height: 16.0), - CachedNetworkImage( - imageUrl: baseUrl + '/storage/' + (post.image), - imageBuilder: (context, imageProvider) => Stack( - children: [ - ClipRRect( - borderRadius: const BorderRadius.all(Radius.circular(8.0)), - child: Image( - image: imageProvider, - ), - ), - ], - ), - placeholder: (context, url) => CircularProgressIndicator(), - ), - SizedBox(height: 16.0), - Row( - children: [ - Padding( - padding: EdgeInsets.only(left: 4), - child: Row( - children: [ - Padding( - padding: EdgeInsets.only(right: 4), - child: Icon(Icons.comment_outlined), - ), - Text( - "Комментировать", - ), - ], - ), - ), - Spacer(), - Row( - children: [ - Padding( - padding: const EdgeInsets.only(right: 4), - child: Icon(Icons.favorite_outline), - ), - Text( - "Нравится", - ), - ], - ), - Spacer(), - Padding( - padding: EdgeInsets.only(right: 4), - child: Icon(Icons.share_outlined), - ), - ], - ), - ], - ), - ), - ], - ), - ); - } - - Function onTapBack(BuildContext context) { - return () { - onTapArrowLeft(context); - }; - } - - onTapArrowLeft(BuildContext context) { - GoRouter.of(context).pop(); - } - - _buildMenu(BuildContext context, FeedStateLoaded state) { - return Container( - padding: EdgeInsets.all(12), - 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: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - children: [ - ScrollItem(title: 'Все'), - ScrollItem(title: 'Рецепты'), - ScrollItem(title: 'Диеты'), - ScrollItem(title: 'Планы'), - ScrollItem(title: 'Записи'), - ], - ), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + label: Text(chipsLabelList[index]), + labelStyle: TextStyle( + color: index == _selectedChipIndex ? Colors.white : appTheme.gray600, + fontWeight: FontWeight.w500, + fontSize: 12, ), + selected: _selectedChipIndex == index, + backgroundColor: appTheme.gray100, + onSelected: (bool selected) { + setState(() { + _selectedChipIndex = index; + }); + }, ); } } diff --git a/lib/features/feed/presentation/pages/feed_screen_new.dart b/lib/features/feed/presentation/pages/feed_screen_new.dart deleted file mode 100644 index 6b5e183..0000000 --- a/lib/features/feed/presentation/pages/feed_screen_new.dart +++ /dev/null @@ -1,214 +0,0 @@ -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:eatvio_app/features/feed/presentation/widgets/blog_post_widget.dart'; -import 'package:eatvio_app/theme/theme_helper.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:go_router/go_router.dart'; - -class FeedScreenNew extends StatefulWidget { - const FeedScreenNew({super.key}); - - @override - State createState() => _FeedScreenNewState(); -} - -class _FeedScreenNewState extends State { - final List chipsLabelList = ['Все', 'Рецепты', 'Диеты', 'Планы питания', 'Консультанты']; - - int _selectedChipIndex = 0; - - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - backgroundColor: Colors.white, - toolbarHeight: 0, - systemOverlayStyle: SystemUiOverlayStyle( - statusBarColor: Colors.white, - ), - ), - backgroundColor: Colors.grey.shade200, - body: NestedScrollView( - headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { - return [ - SliverAppBar( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.vertical(bottom: Radius.circular(12)), - ), - backgroundColor: Colors.white, - foregroundColor: Colors.white, - automaticallyImplyLeading: false, - stretchTriggerOffset: 1, - floating: true, - snap: true, - scrolledUnderElevation: 0, - bottom: _chipGroup(), - title: Row( - children: [ - _searchBar(), - SizedBox(width: 12), - _addBlogPostButton(), - ], - ), - ), - ]; - }, - body: _buildAllBlogPosts(), - ), - ); - } - - _buildAllBlogPosts() { - return RefreshIndicator( - onRefresh: () => context.read().loadFeedBlogPostList(), - child: BlocBuilder( - builder: (BuildContext context, FeedState state) { - if (state is FeedStateLoaded) { - return ListView.separated( - padding: EdgeInsets.symmetric(vertical: 8), - shrinkWrap: true, - physics: BouncingScrollPhysics(), - itemBuilder: (context, index) { - return BlogPostWidget(feedBlogPostModel: state.feedBlogPostList[index]); - }, - separatorBuilder: (context, index) { - return SizedBox(height: 8); - }, - itemCount: state.feedBlogPostList.length, - ); - } else if (state is FeedStateError) { - return Scaffold( - body: Padding( - padding: const EdgeInsets.all(16), - child: Center( - child: Text(state.errorMessage), - ), - ), - ); - } else { - return Scaffold( - body: Center( - child: CupertinoActivityIndicator(), - ), - ); - } - }, - ), - ); - } - - _chipGroup() { - return PreferredSize( - preferredSize: Size(MediaQuery.of(context).size.width, 32), - child: Align( - alignment: Alignment.centerLeft, - child: SingleChildScrollView( - padding: EdgeInsets.symmetric(horizontal: 16), - scrollDirection: Axis.horizontal, - child: Row( - children: [ - _choiceChipWidget(0), - SizedBox(width: 8), - _choiceChipWidget(1), - SizedBox(width: 8), - _choiceChipWidget(2), - SizedBox(width: 8), - _choiceChipWidget(3), - SizedBox(width: 8), - _choiceChipWidget(4), - ], - ), - ), - ), - ); - } - - _addBlogPostButton() { - return InkWell( - onTap: () => GoRouter.of(context).pushNamed('blogPostCreateScreen'), - borderRadius: BorderRadius.circular(64), - child: Ink( - decoration: BoxDecoration( - color: appTheme.blueA400, - shape: BoxShape.circle, - ), - child: Icon( - Icons.add_rounded, - color: appTheme.gray100, - ), - width: 40, - height: 40, - ), - ); - } - - _searchBar() { - return SizedBox( - height: 40, - width: MediaQuery.of(context).size.width - 84, - child: TextFormField( - style: TextStyle( - fontSize: 12, - ), - decoration: InputDecoration( - hintText: 'Поиск', - hintStyle: TextStyle( - fontSize: 12, - color: appTheme.gray600, - fontWeight: FontWeight.w400, - ), - prefixIcon: Icon( - Icons.search, - color: appTheme.gray600, - size: 16, - ), - isDense: false, - contentPadding: EdgeInsets.all(8), - fillColor: appTheme.gray100, - filled: true, - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(16), - borderSide: BorderSide.none, - ), - enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(16), - borderSide: BorderSide.none, - ), - focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(16), - borderSide: BorderSide.none, - ), - ), - ), - ); - } - - _choiceChipWidget(int index) { - return ChoiceChip( - selectedColor: appTheme.blueA400, - pressElevation: 0, - showCheckmark: false, - side: BorderSide.none, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(16), - ), - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), - label: Text(chipsLabelList[index]), - labelStyle: TextStyle( - color: index == _selectedChipIndex ? Colors.white : appTheme.gray600, - fontWeight: FontWeight.w500, - fontSize: 12, - ), - selected: _selectedChipIndex == index, - backgroundColor: appTheme.gray100, - onSelected: (bool selected) { - setState(() { - _selectedChipIndex = index; - }); - }, - ); - } -} diff --git a/lib/features/feed/presentation/widgets/blog_post_widget.dart b/lib/features/feed/presentation/widgets/blog_post_widget.dart index abfba97..1139fe0 100644 --- a/lib/features/feed/presentation/widgets/blog_post_widget.dart +++ b/lib/features/feed/presentation/widgets/blog_post_widget.dart @@ -19,6 +19,7 @@ class _BlogPostWidgetState extends State { @override Widget build(BuildContext context) { return InkWell( + borderRadius: BorderRadius.circular(12), onTap: () => GoRouter.of(context).pushNamed( 'blogPostScreen', extra: widget.feedBlogPostModel.id.toString(), @@ -52,12 +53,23 @@ class _BlogPostWidgetState extends State { if (widget.feedBlogPostModel.title.isNotEmpty || widget.feedBlogPostModel.description.isNotEmpty) SizedBox(height: 12), Padding( padding: const EdgeInsets.symmetric(horizontal: 12), - child: Text(widget.feedBlogPostModel.title), + child: Text( + widget.feedBlogPostModel.title, + style: TextStyle( + fontWeight: FontWeight.w600, + color: Colors.black87, + ), + ), ), if (widget.feedBlogPostModel.title.isNotEmpty && widget.feedBlogPostModel.description.isNotEmpty) SizedBox(height: 8), Padding( padding: const EdgeInsets.symmetric(horizontal: 12), - child: Text(widget.feedBlogPostModel.description), + child: Text( + widget.feedBlogPostModel.description, + style: TextStyle( + color: Colors.black87, + ), + ), ), if (widget.feedBlogPostModel.title.isNotEmpty || widget.feedBlogPostModel.description.isNotEmpty) SizedBox(height: 8), GestureDetector( diff --git a/lib/features/feed/presentation/widgets/recipes_widget.dart b/lib/features/feed/presentation/widgets/recipes_widget.dart new file mode 100644 index 0000000..233e45b --- /dev/null +++ b/lib/features/feed/presentation/widgets/recipes_widget.dart @@ -0,0 +1,187 @@ +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:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; +import 'package:eatvio_app/features/feed/models/recipes_model.dart'; +import 'package:flutter/material.dart'; + +class RecipesWidget extends StatefulWidget { + final Recipes recipes; + + const RecipesWidget({super.key, required this.recipes}); + + @override + State createState() => _RecipesWidgetState(); +} + +class _RecipesWidgetState extends State { + @override + Widget build(BuildContext context) { + return InkWell( + borderRadius: BorderRadius.circular(12), + onTap: () {}, + child: Ink( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + color: Colors.white, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Stack( + alignment: Alignment.bottomLeft, + children: [ + ClipRRect( + borderRadius: BorderRadius.vertical(top: Radius.circular(12)), + child: GestureDetector( + onTap: () { + context.pushTransparentRoute( + rootNavigator: true, + PhotoViewScreen( + imageUrls: [baseUrl + '/storage/' + widget.recipes.image], + index: 0, + ), + ); + }, + child: Hero( + tag: baseUrl + '/storage/' + widget.recipes.image, + child: CachedNetworkImage( + imageUrl: baseUrl + '/storage/' + widget.recipes.image, + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.all(8.0), + child: Row( + children: [ + Container( + padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: Colors.white54, + borderRadius: BorderRadius.circular(16), + ), + child: Row( + children: [ + Icon( + Icons.visibility_rounded, + size: 20, + color: Colors.black, + ), + SizedBox(width: 4), + Text( + '0', + style: TextStyle( + fontSize: 14, + color: Colors.black, + fontWeight: FontWeight.w400, + ), + ), + ], + ), + ), + SizedBox(width: 8), + Container( + padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: Colors.white54, + borderRadius: BorderRadius.circular(16), + ), + child: Row( + children: [ + Icon( + Icons.favorite_border_rounded, + size: 20, + color: Colors.black, + ), + SizedBox(width: 4), + Text( + '0', + style: TextStyle( + fontSize: 14, + color: Colors.black, + fontWeight: FontWeight.w400, + ), + ), + ], + ), + ), + ], + ), + ), + ], + ), + SizedBox(height: 12), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Text( + widget.recipes.title, + style: TextStyle( + fontWeight: FontWeight.w600, + color: Colors.black87, + ), + ), + ), + SizedBox(height: 8), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Text( + widget.recipes.description, + style: TextStyle( + color: Colors.black87, + ), + ), + ), + SizedBox(height: 12), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Wrap( + runSpacing: 8, + children: [ + _iconButton(Icons.fastfood, '139.9 ккал'), + SizedBox(width: 8), + _iconButton(Icons.timer_rounded, widget.recipes.cookingTime.toString() + ' минут'), + SizedBox(width: 8), + _iconButton(Icons.fast_forward_rounded, widget.recipes.steps.length.toString() + ' этапов'), + ], + ), + ), + SizedBox(height: 8), + ], + ), + ), + ); + } + + _iconButton(IconData icon, [String? text]) { + return Ink( + padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4), + decoration: BoxDecoration( + color: appTheme.gray100, + borderRadius: BorderRadius.circular(16), + ), + height: 32, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + icon, + size: 20, + color: appTheme.gray600, + ), + if (text != null) SizedBox(width: 8), + if (text != null) + Text( + text, + style: TextStyle( + fontSize: 14, + color: appTheme.gray600, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/feed/repositories/feed_repository.dart b/lib/features/feed/repositories/feed_repository.dart index 319ac32..60cd1df 100644 --- a/lib/features/feed/repositories/feed_repository.dart +++ b/lib/features/feed/repositories/feed_repository.dart @@ -1,4 +1,5 @@ import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; +import 'package:eatvio_app/features/feed/models/recipes_model.dart'; import 'package:eatvio_app/features/feed/services/feed_service.dart'; class FeedRepository { @@ -13,4 +14,12 @@ class FeedRepository { rethrow; } } + + Future> getRecipes() async { + try { + return (await feedService.getRecipes()).recipesList; + } catch (e) { + rethrow; + } + } } diff --git a/lib/features/feed/services/feed_service.dart b/lib/features/feed/services/feed_service.dart index d96ba1c..d9bf881 100644 --- a/lib/features/feed/services/feed_service.dart +++ b/lib/features/feed/services/feed_service.dart @@ -1,5 +1,6 @@ import 'package:dio/dio.dart'; import 'package:eatvio_app/features/feed/models/feed_blog_post_settings_model.dart'; +import 'package:eatvio_app/features/feed/models/recipes_pagination_model.dart'; import 'package:retrofit/retrofit.dart'; part 'feed_service.g.dart'; @@ -10,4 +11,7 @@ abstract class FeedService { @GET('/api/blogPosts/index') Future getBlocPostList(); + + @GET('/api/recipes/index') + Future getRecipes(); } diff --git a/lib/features/feed/services/feed_service.g.dart b/lib/features/feed/services/feed_service.g.dart index 89003f6..fbccc93 100644 --- a/lib/features/feed/services/feed_service.g.dart +++ b/lib/features/feed/services/feed_service.g.dart @@ -45,6 +45,33 @@ class _FeedService implements FeedService { return _value; } + @override + Future getRecipes() async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio + .fetch>(_setStreamType(Options( + method: 'GET', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/api/recipes/index', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = RecipesPagination.fromJson(_result.data!); + return _value; + } + RequestOptions _setStreamType(RequestOptions requestOptions) { if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || diff --git a/lib/locator_service.dart b/lib/locator_service.dart index 592aff9..5947a11 100644 --- a/lib/locator_service.dart +++ b/lib/locator_service.dart @@ -13,6 +13,7 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_ import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; 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/presentation/bloc/recipes_cubit/recipes_cubit.dart'; import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; import 'package:eatvio_app/features/feed/services/feed_service.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.dart'; @@ -34,6 +35,7 @@ Future init() async { sl.registerFactory(() => RegistrationCubit(registrationRepository: sl())); sl.registerFactory(() => ChatRoomCubit(chatRepository: sl(), initializationCubit: sl())); sl.registerFactory(() => FeedCubit(feedRepository: sl())); + sl.registerFactory(() => RecipesCubit(feedRepository: sl())); sl.registerFactory(() => BlogPostCubit(blogPostRepository: sl())); sl.registerFactory(() => DiaryBloc(diaryRepository: sl())); sl.registerFactory(() => CalendarCubit(calendarRepository: sl())); diff --git a/lib/main.dart b/lib/main.dart index d9bc52c..03f769a 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -7,6 +7,7 @@ import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_cubit.da 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/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart'; import 'package:eatvio_app/locator_service.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.dart'; import 'package:eatvio_app/presentation/profile/my_profile_screen/bloc/my_profile_bloc.dart'; @@ -48,6 +49,7 @@ class MyApp extends StatelessWidget { BlocProvider(create: (context) => sl()), BlocProvider(create: (context) => ThemeBloc(ThemeState(themeType: PrefUtils().getThemeData()))), BlocProvider(create: (context) => sl()..loadFeedBlogPostList()), + BlocProvider(create: (context) => sl()..loadRecipesList()), BlocProvider(create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent())), BlocProvider(create: (context) => sl()..add(LoadDiary())), BlocProvider( -- 2.49.1 From c83bfee7cc81552fcd6a716723d6d0e786e704e2 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 2 Aug 2024 10:20:06 +0300 Subject: [PATCH 095/110] feat(app): Server changed to dev2 --- lib/core/constants/constants.dart | 2 +- .../initialization_cubit.dart | 23 +++++++++++++------ .../bloc/chat_room_cubit/chat_room_cubit.dart | 21 ++++++++++++----- 3 files changed, 32 insertions(+), 14 deletions(-) diff --git a/lib/core/constants/constants.dart b/lib/core/constants/constants.dart index c0353c4..4daf523 100644 --- a/lib/core/constants/constants.dart +++ b/lib/core/constants/constants.dart @@ -1 +1 @@ -const String baseUrl = 'https://mobile-stage.eatvio.ru'; +const String baseUrl = 'https://dev2.eatvio.ru'; diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index 4a1bcaf..dd06a97 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -11,13 +11,18 @@ class InitializationCubit extends Cubit { final ChatRepository chatRepository; bool wasInitialized = false; - InitializationCubit({required this.chatRepository}) : super(const InitializationState.loading()); + InitializationCubit({required this.chatRepository}) + : super(const InitializationState.loading()); - Future subscribeNotifications(int userId, PusherChannelsClient client) async { + Future subscribeNotifications( + int userId, PusherChannelsClient client) async { final privateNotificationChannel = await client.privateChannel( 'private-message-events.$userId', - authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( - authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), + authorizationDelegate: + EndpointAuthorizableChannelTokenAuthorizationDelegate + .forPrivateChannel( + authorizationEndpoint: + Uri.parse('https://dev2.eatvio.ru/broadcasting/auth'), headers: { 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, @@ -31,11 +36,15 @@ class InitializationCubit extends Cubit { }); } - Future subscribeChatMessages(int userId, PusherChannelsClient client) async { + Future subscribeChatMessages( + int userId, PusherChannelsClient client) async { final privateMessagesChannel = await client.privateChannel( 'private-new-chat-messages.$userId', - authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( - authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), + authorizationDelegate: + EndpointAuthorizableChannelTokenAuthorizationDelegate + .forPrivateChannel( + authorizationEndpoint: + Uri.parse('https://dev2.eatvio.ru/broadcasting/auth'), headers: { 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart index 3773c43..49ab767 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart @@ -39,12 +39,16 @@ class ChatRoomCubit extends Cubit { )); try { - final chatMessages = await chatRepository.getChatMessages(chatId, currentPage + 1); + final chatMessages = + await chatRepository.getChatMessages(chatId, currentPage + 1); isLoading = false; emit(ChatRoomState.loaded( chatRoom: (state as ChatRoomStateLoaded).chatRoom, - chatMessages: [...(state as ChatRoomStateLoaded).chatMessages, ...chatMessages.messagesList], + chatMessages: [ + ...(state as ChatRoomStateLoaded).chatMessages, + ...chatMessages.messagesList + ], isTyping: (state as ChatRoomStateLoaded).isTyping, isLoading: isLoading, )); @@ -61,10 +65,12 @@ class ChatRoomCubit extends Cubit { try { final chatRoom = await chatRepository.getChatRoom(chatId); - final chatMessages = await chatRepository.getChatMessages(chatId, currentPage); + final chatMessages = + await chatRepository.getChatMessages(chatId, currentPage); lastPage = chatMessages.meta.lastPage; - await subscribeToChatChannel(initCubit: initializationCubit, chatId: chatId); + await subscribeToChatChannel( + initCubit: initializationCubit, chatId: chatId); emit(ChatRoomState.loaded( chatRoom: chatRoom, @@ -86,8 +92,11 @@ class ChatRoomCubit extends Cubit { privateChatChannel = await client.privateChannel( 'private-direct-chat.$chatId', - authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( - authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), + authorizationDelegate: + EndpointAuthorizableChannelTokenAuthorizationDelegate + .forPrivateChannel( + authorizationEndpoint: + Uri.parse('https://dev2.eatvio.ru/broadcasting/auth'), headers: { 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, -- 2.49.1 From f3d099fe0c938d8b0e09f1c0660f510340028100 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 2 Aug 2024 07:29:32 +0000 Subject: [PATCH 096/110] revert c83bfee7cc81552fcd6a716723d6d0e786e704e2 revert feat(app): Server changed to dev2 --- lib/core/constants/constants.dart | 2 +- .../initialization_cubit.dart | 23 ++++++------------- .../bloc/chat_room_cubit/chat_room_cubit.dart | 21 +++++------------ 3 files changed, 14 insertions(+), 32 deletions(-) diff --git a/lib/core/constants/constants.dart b/lib/core/constants/constants.dart index 4daf523..c0353c4 100644 --- a/lib/core/constants/constants.dart +++ b/lib/core/constants/constants.dart @@ -1 +1 @@ -const String baseUrl = 'https://dev2.eatvio.ru'; +const String baseUrl = 'https://mobile-stage.eatvio.ru'; diff --git a/lib/core/initialization_cubit/initialization_cubit.dart b/lib/core/initialization_cubit/initialization_cubit.dart index dd06a97..4a1bcaf 100644 --- a/lib/core/initialization_cubit/initialization_cubit.dart +++ b/lib/core/initialization_cubit/initialization_cubit.dart @@ -11,18 +11,13 @@ class InitializationCubit extends Cubit { final ChatRepository chatRepository; bool wasInitialized = false; - InitializationCubit({required this.chatRepository}) - : super(const InitializationState.loading()); + InitializationCubit({required this.chatRepository}) : super(const InitializationState.loading()); - Future subscribeNotifications( - int userId, PusherChannelsClient client) async { + Future subscribeNotifications(int userId, PusherChannelsClient client) async { final privateNotificationChannel = await client.privateChannel( 'private-message-events.$userId', - authorizationDelegate: - EndpointAuthorizableChannelTokenAuthorizationDelegate - .forPrivateChannel( - authorizationEndpoint: - Uri.parse('https://dev2.eatvio.ru/broadcasting/auth'), + authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( + authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), headers: { 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, @@ -36,15 +31,11 @@ class InitializationCubit extends Cubit { }); } - Future subscribeChatMessages( - int userId, PusherChannelsClient client) async { + Future subscribeChatMessages(int userId, PusherChannelsClient client) async { final privateMessagesChannel = await client.privateChannel( 'private-new-chat-messages.$userId', - authorizationDelegate: - EndpointAuthorizableChannelTokenAuthorizationDelegate - .forPrivateChannel( - authorizationEndpoint: - Uri.parse('https://dev2.eatvio.ru/broadcasting/auth'), + authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( + authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), headers: { 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart index 49ab767..3773c43 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart @@ -39,16 +39,12 @@ class ChatRoomCubit extends Cubit { )); try { - final chatMessages = - await chatRepository.getChatMessages(chatId, currentPage + 1); + final chatMessages = await chatRepository.getChatMessages(chatId, currentPage + 1); isLoading = false; emit(ChatRoomState.loaded( chatRoom: (state as ChatRoomStateLoaded).chatRoom, - chatMessages: [ - ...(state as ChatRoomStateLoaded).chatMessages, - ...chatMessages.messagesList - ], + chatMessages: [...(state as ChatRoomStateLoaded).chatMessages, ...chatMessages.messagesList], isTyping: (state as ChatRoomStateLoaded).isTyping, isLoading: isLoading, )); @@ -65,12 +61,10 @@ class ChatRoomCubit extends Cubit { try { final chatRoom = await chatRepository.getChatRoom(chatId); - final chatMessages = - await chatRepository.getChatMessages(chatId, currentPage); + final chatMessages = await chatRepository.getChatMessages(chatId, currentPage); lastPage = chatMessages.meta.lastPage; - await subscribeToChatChannel( - initCubit: initializationCubit, chatId: chatId); + await subscribeToChatChannel(initCubit: initializationCubit, chatId: chatId); emit(ChatRoomState.loaded( chatRoom: chatRoom, @@ -92,11 +86,8 @@ class ChatRoomCubit extends Cubit { privateChatChannel = await client.privateChannel( 'private-direct-chat.$chatId', - authorizationDelegate: - EndpointAuthorizableChannelTokenAuthorizationDelegate - .forPrivateChannel( - authorizationEndpoint: - Uri.parse('https://dev2.eatvio.ru/broadcasting/auth'), + authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel( + authorizationEndpoint: Uri.parse('https://mobile-stage.eatvio.ru/broadcasting/auth'), headers: { 'Authorization': 'Bearer ${await TokenStorage.getTokenFromStorage()}', }, -- 2.49.1 From c78f8dacdfd1da536cc63103ab8801710256e26c Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Fri, 2 Aug 2024 11:50:47 +0300 Subject: [PATCH 097/110] feat(feed): recipes screen --- lib/features/recipes/presentation/pages/about_recipes_screen.dart | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 lib/features/recipes/presentation/pages/about_recipes_screen.dart diff --git a/lib/features/recipes/presentation/pages/about_recipes_screen.dart b/lib/features/recipes/presentation/pages/about_recipes_screen.dart new file mode 100644 index 0000000..e69de29 -- 2.49.1 From 904adbba2fec878f14d9dbee763def394b705bcd Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Fri, 2 Aug 2024 11:52:10 +0300 Subject: [PATCH 098/110] feat(feed): add recipes screen --- lib/app_router.dart | 9 + .../initialization_state.freezed.dart | 96 +++----- lib/core/utils/image_constant.dart | 1 + .../selection_popup_model.freezed.dart | 53 ++--- .../user_registration_model.dart | 3 +- .../user_registration_model.freezed.dart | 183 ++++++++------- .../user_registration_model.g.dart | 11 +- .../models/blog_post_model.freezed.dart | 81 +++---- .../blog_post/models/blog_post_model.g.dart | 6 +- .../bloc/blog_post_state.freezed.dart | 88 +++---- .../presentation/pages/blog_post_screen.dart | 1 + .../services/blog_post_service.g.dart | 29 +-- .../repositories/blog_repository.dart | 2 +- .../services/blog_service.dart | 2 +- .../new_messages_state.freezed.dart | 92 +++----- .../notifications_state.freezed.dart | 95 +++----- .../models/chat_message_model.freezed.dart | 73 +++--- .../chat/models/chat_message_model.g.dart | 8 +- .../chat/models/chat_messages_model.dart | 1 + .../models/chat_messages_model.freezed.dart | 70 ++---- .../chat/models/chat_messages_model.g.dart | 12 +- .../chat/models/chat_meta_model.freezed.dart | 54 ++--- .../chat/models/chat_meta_model.g.dart | 6 +- .../chat/models/chat_room_model.freezed.dart | 78 +++--- .../chat/models/chat_room_model.g.dart | 12 +- .../chat_room_settings_model.freezed.dart | 78 +++--- .../models/chat_room_settings_model.g.dart | 8 +- .../chat/models/chat_user_model.freezed.dart | 78 +++--- .../chat/models/chat_user_model.g.dart | 6 +- .../models/websocket_info_model.freezed.dart | 81 +++---- .../chat/models/websocket_info_model.g.dart | 8 +- .../chat_room_state.freezed.dart | 171 +++++--------- .../bloc/chat_select_bloc.dart | 15 +- .../models/chat_select_model.dart | 1 + .../chat/services/chat_service.g.dart | 82 +++---- lib/features/diary/models/meal.dart | 1 + lib/features/diary/models/meal.freezed.dart | 136 ++++++----- lib/features/diary/models/meal.g.dart | 3 +- lib/features/diary/models/photo.dart | 4 +- lib/features/diary/models/photo.freezed.dart | 62 ++--- lib/features/diary/models/photo.g.dart | 3 +- lib/features/diary/models/portion.dart | 1 + .../diary/models/portion.freezed.dart | 58 +++-- lib/features/diary/models/product.dart | 1 + .../diary/models/product.freezed.dart | 30 ++- .../models/feed_blog_post_model.freezed.dart | 70 +++--- .../feed/models/feed_blog_post_model.g.dart | 8 +- .../models/feed_blog_post_settings_model.dart | 1 + ...feed_blog_post_settings_model.freezed.dart | 69 ++---- .../feed_blog_post_settings_model.g.dart | 6 +- .../feed/models/recipes_model.freezed.dart | 222 ++++++++---------- lib/features/feed/models/recipes_model.g.dart | 23 +- .../feed/models/recipes_pagination_model.dart | 4 +- .../recipes_pagination_model.freezed.dart | 101 ++++---- .../models/recipes_pagination_model.g.dart | 12 +- .../bloc/feed_cubit/feed_state.freezed.dart | 102 +++----- .../bloc/recipes_cubit/recipes_cubit.dart | 2 +- .../recipes_cubit/recipes_state.freezed.dart | 96 +++----- .../widgets/blog_post_widget.dart | 9 +- .../presentation/widgets/recipes_widget.dart | 150 ++++++------ .../feed/services/feed_service.g.dart | 54 ++--- .../pages/about_recipes_screen.dart | 49 ++++ .../models/location_model.freezed.dart | 71 ++---- .../registration/models/location_model.g.dart | 9 +- .../registration_state.freezed.dart | 41 ++-- .../pages/credentials_screen.dart | 1 + .../services/registration_service.g.dart | 82 +++---- lib/localization/app_localization.dart | 2 + lib/locator_service.dart | 6 +- lib/main.dart | 11 +- .../auth/auth_screen/auth_screen.dart | 1 + .../auth/auth_screen/bloc/auth_state.dart | 1 + .../bloc/diet_create_state.dart | 3 + .../bloc/diet_select_event.dart | 2 + .../bloc/diet_select_state.dart | 2 + .../bloc/diet_show_event.dart | 2 + .../bloc/diet_show_state.dart | 3 + .../bloc/blog_post_create_bloc.dart | 2 +- .../bloc/blog_post_edit_state.dart | 3 + .../models/blog_post_model.dart | 2 + .../bloc/glossary_screen_event.dart | 4 + .../bloc/glossary_screen_state.dart | 3 + .../models/glossary_screen_model.dart | 1 + .../bloc/plan_create_state.dart | 3 + .../bloc/plan_edit_state.dart | 3 + .../bloc/plan_select_event.dart | 2 + .../bloc/plan_select_state.dart | 2 + .../bloc/plan_show_event.dart | 2 + .../bloc/plan_show_state.dart | 3 + .../bloc/my_profile_event.dart | 2 + .../bloc/my_profile_state.dart | 2 + .../bloc/recipe_create_event.dart | 4 + .../bloc/recipe_create_state.dart | 3 + .../bloc/recipe_edit_event.dart | 4 + .../bloc/recipe_edit_state.dart | 3 + .../bloc/recipe_select_event.dart | 2 + .../bloc/recipe_select_state.dart | 2 + .../bloc/recipe_show_event.dart | 4 + .../bloc/recipe_show_state.dart | 3 + .../bloc/subscribers_state.dart | 2 + lib/theme/app_decoration.dart | 17 ++ lib/theme/bloc/theme_state.dart | 1 + lib/theme/custom_button_style.dart | 1 + lib/widgets/custom_drop_down.dart | 31 +-- lib/widgets/custom_edit_drop_down.dart | 30 ++- lib/widgets/custom_expandable_list.dart | 35 +-- lib/widgets/custom_hyper_switch.dart | 1 + lib/widgets/custom_hypo_switch.dart | 1 + lib/widgets/custom_language_drop_down.dart | 3 +- lib/widgets/custom_outlined_button.dart | 2 +- lib/widgets/custom_text_form_field.dart | 4 +- 111 files changed, 1511 insertions(+), 1784 deletions(-) diff --git a/lib/app_router.dart b/lib/app_router.dart index 61fac3e..19b9f1f 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -8,7 +8,9 @@ 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/diary/presentation/pages/diary_screen.dart'; +import 'package:eatvio_app/features/feed/models/recipes_model.dart'; import 'package:eatvio_app/features/feed/presentation/pages/feed_screen.dart'; +import 'package:eatvio_app/features/recipes/presentation/pages/about_recipes_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/diets/diet_create_screen/diet_create_screen.dart'; @@ -79,6 +81,13 @@ class AppRouter { ), ], ), + GoRoute( + path: '/about-recipes-screen', + name: 'aboutRecipesScreen', + builder: (context, state) => AboutRecipesScreen( + recipes: state.extra as Recipes, + ), + ), GoRoute( path: '/blog-post-create-screen', name: 'blogPostCreateScreen', diff --git a/lib/core/initialization_cubit/initialization_state.freezed.dart b/lib/core/initialization_cubit/initialization_state.freezed.dart index 3364e44..5d54500 100644 --- a/lib/core/initialization_cubit/initialization_state.freezed.dart +++ b/lib/core/initialization_cubit/initialization_state.freezed.dart @@ -24,6 +24,7 @@ mixin _$InitializationState { required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; + @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { @@ -70,36 +71,31 @@ mixin _$InitializationState { /// @nodoc abstract class $InitializationStateCopyWith<$Res> { - factory $InitializationStateCopyWith( - InitializationState value, $Res Function(InitializationState) then) = + factory $InitializationStateCopyWith(InitializationState value, $Res Function(InitializationState) then) = _$InitializationStateCopyWithImpl<$Res, InitializationState>; } /// @nodoc -class _$InitializationStateCopyWithImpl<$Res, $Val extends InitializationState> - implements $InitializationStateCopyWith<$Res> { +class _$InitializationStateCopyWithImpl<$Res, $Val extends InitializationState> implements $InitializationStateCopyWith<$Res> { _$InitializationStateCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; } /// @nodoc abstract class _$$InitializationStateImplCopyWith<$Res> { - factory _$$InitializationStateImplCopyWith(_$InitializationStateImpl value, - $Res Function(_$InitializationStateImpl) then) = + factory _$$InitializationStateImplCopyWith(_$InitializationStateImpl value, $Res Function(_$InitializationStateImpl) then) = __$$InitializationStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$InitializationStateImplCopyWithImpl<$Res> - extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateImpl> +class __$$InitializationStateImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateImpl> implements _$$InitializationStateImplCopyWith<$Res> { - __$$InitializationStateImplCopyWithImpl(_$InitializationStateImpl _value, - $Res Function(_$InitializationStateImpl) _then) - : super(_value, _then); + __$$InitializationStateImplCopyWithImpl(_$InitializationStateImpl _value, $Res Function(_$InitializationStateImpl) _then) : super(_value, _then); } /// @nodoc @@ -114,9 +110,7 @@ class _$InitializationStateImpl implements _InitializationState { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$InitializationStateImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$InitializationStateImpl); } @override @@ -203,20 +197,14 @@ abstract class _InitializationState implements InitializationState { /// @nodoc abstract class _$$InitializationStateLoadingImplCopyWith<$Res> { - factory _$$InitializationStateLoadingImplCopyWith( - _$InitializationStateLoadingImpl value, - $Res Function(_$InitializationStateLoadingImpl) then) = + factory _$$InitializationStateLoadingImplCopyWith(_$InitializationStateLoadingImpl value, $Res Function(_$InitializationStateLoadingImpl) then) = __$$InitializationStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$InitializationStateLoadingImplCopyWithImpl<$Res> - extends _$InitializationStateCopyWithImpl<$Res, - _$InitializationStateLoadingImpl> +class __$$InitializationStateLoadingImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateLoadingImpl> implements _$$InitializationStateLoadingImplCopyWith<$Res> { - __$$InitializationStateLoadingImplCopyWithImpl( - _$InitializationStateLoadingImpl _value, - $Res Function(_$InitializationStateLoadingImpl) _then) + __$$InitializationStateLoadingImplCopyWithImpl(_$InitializationStateLoadingImpl _value, $Res Function(_$InitializationStateLoadingImpl) _then) : super(_value, _then); } @@ -232,9 +220,7 @@ class _$InitializationStateLoadingImpl implements InitializationStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$InitializationStateLoadingImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$InitializationStateLoadingImpl); } @override @@ -321,22 +307,17 @@ abstract class InitializationStateLoading implements InitializationState { /// @nodoc abstract class _$$InitializationStateSuccessImplCopyWith<$Res> { - factory _$$InitializationStateSuccessImplCopyWith( - _$InitializationStateSuccessImpl value, - $Res Function(_$InitializationStateSuccessImpl) then) = + factory _$$InitializationStateSuccessImplCopyWith(_$InitializationStateSuccessImpl value, $Res Function(_$InitializationStateSuccessImpl) then) = __$$InitializationStateSuccessImplCopyWithImpl<$Res>; + @useResult $Res call({PusherChannelsClient client}); } /// @nodoc -class __$$InitializationStateSuccessImplCopyWithImpl<$Res> - extends _$InitializationStateCopyWithImpl<$Res, - _$InitializationStateSuccessImpl> +class __$$InitializationStateSuccessImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateSuccessImpl> implements _$$InitializationStateSuccessImplCopyWith<$Res> { - __$$InitializationStateSuccessImplCopyWithImpl( - _$InitializationStateSuccessImpl _value, - $Res Function(_$InitializationStateSuccessImpl) _then) + __$$InitializationStateSuccessImplCopyWithImpl(_$InitializationStateSuccessImpl _value, $Res Function(_$InitializationStateSuccessImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -369,9 +350,7 @@ class _$InitializationStateSuccessImpl implements InitializationStateSuccess { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$InitializationStateSuccessImpl && - (identical(other.client, client) || other.client == client)); + (other.runtimeType == runtimeType && other is _$InitializationStateSuccessImpl && (identical(other.client, client) || other.client == client)); } @override @@ -380,9 +359,8 @@ class _$InitializationStateSuccessImpl implements InitializationStateSuccess { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> - get copyWith => __$$InitializationStateSuccessImplCopyWithImpl< - _$InitializationStateSuccessImpl>(this, _$identity); + _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> get copyWith => + __$$InitializationStateSuccessImplCopyWithImpl<_$InitializationStateSuccessImpl>(this, _$identity); @override @optionalTypeArgs @@ -460,34 +438,27 @@ class _$InitializationStateSuccessImpl implements InitializationStateSuccess { } abstract class InitializationStateSuccess implements InitializationState { - const factory InitializationStateSuccess( - {required final PusherChannelsClient client}) = - _$InitializationStateSuccessImpl; + const factory InitializationStateSuccess({required final PusherChannelsClient client}) = _$InitializationStateSuccessImpl; PusherChannelsClient get client; + @JsonKey(ignore: true) - _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> - get copyWith => throw _privateConstructorUsedError; + _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$InitializationStateErrorImplCopyWith<$Res> { - factory _$$InitializationStateErrorImplCopyWith( - _$InitializationStateErrorImpl value, - $Res Function(_$InitializationStateErrorImpl) then) = + factory _$$InitializationStateErrorImplCopyWith(_$InitializationStateErrorImpl value, $Res Function(_$InitializationStateErrorImpl) then) = __$$InitializationStateErrorImplCopyWithImpl<$Res>; + @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$InitializationStateErrorImplCopyWithImpl<$Res> - extends _$InitializationStateCopyWithImpl<$Res, - _$InitializationStateErrorImpl> +class __$$InitializationStateErrorImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateErrorImpl> implements _$$InitializationStateErrorImplCopyWith<$Res> { - __$$InitializationStateErrorImplCopyWithImpl( - _$InitializationStateErrorImpl _value, - $Res Function(_$InitializationStateErrorImpl) _then) + __$$InitializationStateErrorImplCopyWithImpl(_$InitializationStateErrorImpl _value, $Res Function(_$InitializationStateErrorImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -522,8 +493,7 @@ class _$InitializationStateErrorImpl implements InitializationStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$InitializationStateErrorImpl && - (identical(other.errorMessage, errorMessage) || - other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); } @override @@ -532,9 +502,8 @@ class _$InitializationStateErrorImpl implements InitializationStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> - get copyWith => __$$InitializationStateErrorImplCopyWithImpl< - _$InitializationStateErrorImpl>(this, _$identity); + _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> get copyWith => + __$$InitializationStateErrorImplCopyWithImpl<_$InitializationStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -612,11 +581,10 @@ class _$InitializationStateErrorImpl implements InitializationStateError { } abstract class InitializationStateError implements InitializationState { - const factory InitializationStateError({required final String errorMessage}) = - _$InitializationStateErrorImpl; + const factory InitializationStateError({required final String errorMessage}) = _$InitializationStateErrorImpl; String get errorMessage; + @JsonKey(ignore: true) - _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> - get copyWith => throw _privateConstructorUsedError; + _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/core/utils/image_constant.dart b/lib/core/utils/image_constant.dart index 6a7785a..791dacc 100644 --- a/lib/core/utils/image_constant.dart +++ b/lib/core/utils/image_constant.dart @@ -15,6 +15,7 @@ class ImageConstant { static String imageNotFound = 'assets/images/image_not_found.png'; static String imaGlass = 'assets/images/image_glass.svg'; + // Настройки images static String imgClose = '$imagePath/img_close.svg'; diff --git a/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart b/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart index 917785c..79d30b4 100644 --- a/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart +++ b/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart @@ -17,31 +17,33 @@ final _privateConstructorUsedError = UnsupportedError( /// @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; + $SelectionPopupModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $SelectionPopupModelCopyWith<$Res> { - factory $SelectionPopupModelCopyWith( - SelectionPopupModel value, $Res Function(SelectionPopupModel) then) = + 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> { +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; @@ -75,23 +77,19 @@ class _$SelectionPopupModelCopyWithImpl<$Res, $Val extends SelectionPopupModel> } /// @nodoc -abstract class _$$SelectionPopupModelImplCopyWith<$Res> - implements $SelectionPopupModelCopyWith<$Res> { - factory _$$SelectionPopupModelImplCopyWith(_$SelectionPopupModelImpl value, - $Res Function(_$SelectionPopupModelImpl) then) = +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> +class __$$SelectionPopupModelImplCopyWithImpl<$Res> extends _$SelectionPopupModelCopyWithImpl<$Res, _$SelectionPopupModelImpl> implements _$$SelectionPopupModelImplCopyWith<$Res> { - __$$SelectionPopupModelImplCopyWithImpl(_$SelectionPopupModelImpl _value, - $Res Function(_$SelectionPopupModelImpl) _then) - : super(_value, _then); + __$$SelectionPopupModelImplCopyWithImpl(_$SelectionPopupModelImpl _value, $Res Function(_$SelectionPopupModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -125,8 +123,7 @@ class __$$SelectionPopupModelImplCopyWithImpl<$Res> /// @nodoc class _$SelectionPopupModelImpl implements _SelectionPopupModel { - const _$SelectionPopupModelImpl( - {this.id, required this.title, this.value, this.isSelected = false}); + const _$SelectionPopupModelImpl({this.id, required this.title, this.value, this.isSelected = false}); @override final int? id; @@ -151,39 +148,35 @@ class _$SelectionPopupModelImpl implements _SelectionPopupModel { (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)); + (identical(other.isSelected, isSelected) || other.isSelected == isSelected)); } @override - int get hashCode => Object.hash(runtimeType, id, title, - const DeepCollectionEquality().hash(value), isSelected); + 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); + __$$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; + 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; + _$$SelectionPopupModelImplCopyWith<_$SelectionPopupModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/data/models/userRegistrationModel/user_registration_model.dart b/lib/data/models/userRegistrationModel/user_registration_model.dart index 7a7fb3f..419ee5c 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.dart @@ -15,8 +15,7 @@ class UserRegistrationSheet with _$UserRegistrationSheet { required String birthdate, required String gender, required String location, - @JsonKey(name: 'response_body') - required String responseBody, + @JsonKey(name: 'response_body') required String responseBody, required String lang, required int weight, required int height, diff --git a/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart b/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart index 4a15327..4950c89 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart +++ b/lib/data/models/userRegistrationModel/user_registration_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'); -UserRegistrationSheet _$UserRegistrationSheetFromJson( - Map json) { +UserRegistrationSheet _$UserRegistrationSheetFromJson(Map json) { return _UserRegistrationSheet.fromJson(json); } @@ -23,62 +22,88 @@ UserRegistrationSheet _$UserRegistrationSheetFromJson( mixin _$UserRegistrationSheet { @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 location => throw _privateConstructorUsedError; + @JsonKey(name: 'response_body') String get responseBody => 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; + $UserRegistrationSheetCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $UserRegistrationSheetCopyWith<$Res> { - factory $UserRegistrationSheetCopyWith(UserRegistrationSheet value, - $Res Function(UserRegistrationSheet) then) = + factory $UserRegistrationSheetCopyWith(UserRegistrationSheet value, $Res Function(UserRegistrationSheet) then) = _$UserRegistrationSheetCopyWithImpl<$Res, UserRegistrationSheet>; + @useResult $Res call( {@JsonKey(name: 'first_name') String firstName, @@ -111,13 +136,12 @@ abstract class $UserRegistrationSheetCopyWith<$Res> { } /// @nodoc -class _$UserRegistrationSheetCopyWithImpl<$Res, - $Val extends UserRegistrationSheet> - implements $UserRegistrationSheetCopyWith<$Res> { +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; @@ -266,12 +290,10 @@ class _$UserRegistrationSheetCopyWithImpl<$Res, } /// @nodoc -abstract class _$$UserRegistrationSheetImplCopyWith<$Res> - implements $UserRegistrationSheetCopyWith<$Res> { - factory _$$UserRegistrationSheetImplCopyWith( - _$UserRegistrationSheetImpl value, - $Res Function(_$UserRegistrationSheetImpl) then) = +abstract class _$$UserRegistrationSheetImplCopyWith<$Res> implements $UserRegistrationSheetCopyWith<$Res> { + factory _$$UserRegistrationSheetImplCopyWith(_$UserRegistrationSheetImpl value, $Res Function(_$UserRegistrationSheetImpl) then) = __$$UserRegistrationSheetImplCopyWithImpl<$Res>; + @override @useResult $Res call( @@ -305,13 +327,9 @@ abstract class _$$UserRegistrationSheetImplCopyWith<$Res> } /// @nodoc -class __$$UserRegistrationSheetImplCopyWithImpl<$Res> - extends _$UserRegistrationSheetCopyWithImpl<$Res, - _$UserRegistrationSheetImpl> +class __$$UserRegistrationSheetImplCopyWithImpl<$Res> extends _$UserRegistrationSheetCopyWithImpl<$Res, _$UserRegistrationSheetImpl> implements _$$UserRegistrationSheetImplCopyWith<$Res> { - __$$UserRegistrationSheetImplCopyWithImpl(_$UserRegistrationSheetImpl _value, - $Res Function(_$UserRegistrationSheetImpl) _then) - : super(_value, _then); + __$$UserRegistrationSheetImplCopyWithImpl(_$UserRegistrationSheetImpl _value, $Res Function(_$UserRegistrationSheetImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -465,8 +483,7 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @JsonKey(name: 'last_name') required this.lastName, required this.email, required this.password, - @JsonKey(name: 'password_confirmation') - required this.passwordConfirmation, + @JsonKey(name: 'password_confirmation') required this.passwordConfirmation, @JsonKey(name: 'terms') this.termsAccepted = 'accepted', required this.birthdate, required this.gender, @@ -490,8 +507,7 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @JsonKey(name: 'additional_info') required this.additionalInfo, @JsonKey(name: 'activity_coefficient') this.activityCoefficient = 1.2}); - factory _$UserRegistrationSheetImpl.fromJson(Map json) => - _$$UserRegistrationSheetImplFromJson(json); + factory _$UserRegistrationSheetImpl.fromJson(Map json) => _$$UserRegistrationSheetImplFromJson(json); @override @JsonKey(name: 'first_name') @@ -577,54 +593,33 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { return identical(this, other) || (other.runtimeType == runtimeType && other is _$UserRegistrationSheetImpl && - (identical(other.firstName, firstName) || - other.firstName == firstName) && - (identical(other.lastName, lastName) || - other.lastName == lastName) && + (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.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.location, location) || - other.location == location) && - (identical(other.responseBody, responseBody) || - other.responseBody == responseBody) && + (identical(other.location, location) || other.location == location) && + (identical(other.responseBody, responseBody) || other.responseBody == responseBody) && (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.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)); + (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) @@ -663,9 +658,8 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$UserRegistrationSheetImplCopyWith<_$UserRegistrationSheetImpl> - get copyWith => __$$UserRegistrationSheetImplCopyWithImpl< - _$UserRegistrationSheetImpl>(this, _$identity); + _$$UserRegistrationSheetImplCopyWith<_$UserRegistrationSheetImpl> get copyWith => + __$$UserRegistrationSheetImplCopyWithImpl<_$UserRegistrationSheetImpl>(this, _$identity); @override Map toJson() { @@ -681,8 +675,7 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { @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: 'password_confirmation') required final String passwordConfirmation, @JsonKey(name: 'terms') final String termsAccepted, required final String birthdate, required final String gender, @@ -691,104 +684,124 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { 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: '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: '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: '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; + @JsonKey(name: 'activity_coefficient') final double activityCoefficient}) = _$UserRegistrationSheetImpl; - factory _UserRegistrationSheet.fromJson(Map json) = - _$UserRegistrationSheetImpl.fromJson; + factory _UserRegistrationSheet.fromJson(Map json) = _$UserRegistrationSheetImpl.fromJson; @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 location; + @override @JsonKey(name: 'response_body') String get responseBody; + @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; + _$$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 index 9500e91..7690dbb 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.g.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.g.dart @@ -6,9 +6,7 @@ part of 'user_registration_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson( - Map json) => - _$UserRegistrationSheetImpl( +_$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson(Map json) => _$UserRegistrationSheetImpl( firstName: json['first_name'] as String, lastName: json['last_name'] as String, email: json['email'] as String, @@ -35,13 +33,10 @@ _$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson( 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, + activityCoefficient: (json['activity_coefficient'] as num?)?.toDouble() ?? 1.2, ); -Map _$$UserRegistrationSheetImplToJson( - _$UserRegistrationSheetImpl instance) => - { +Map _$$UserRegistrationSheetImplToJson(_$UserRegistrationSheetImpl instance) => { 'first_name': instance.firstName, 'last_name': instance.lastName, 'email': instance.email, diff --git a/lib/features/blog_post/models/blog_post_model.freezed.dart b/lib/features/blog_post/models/blog_post_model.freezed.dart index 7c0a750..058bff6 100644 --- a/lib/features/blog_post/models/blog_post_model.freezed.dart +++ b/lib/features/blog_post/models/blog_post_model.freezed.dart @@ -21,30 +21,38 @@ BlogPostModel _$BlogPostModelFromJson(Map json) { /// @nodoc mixin _$BlogPostModel { int get id => throw _privateConstructorUsedError; + String get state => throw _privateConstructorUsedError; + String? get image => throw _privateConstructorUsedError; + String get description => throw _privateConstructorUsedError; + String? get author_name => throw _privateConstructorUsedError; + String? get author_avatar_path => throw _privateConstructorUsedError; + @JsonKey(name: "youtube_url") String get youtubeUrl => throw _privateConstructorUsedError; + @JsonKey(name: "created_at") DateTime get createdAt => throw _privateConstructorUsedError; + @JsonKey(name: "updated_at") DateTime get updatedAt => throw _privateConstructorUsedError; + String get title => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) - $BlogPostModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $BlogPostModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $BlogPostModelCopyWith<$Res> { - factory $BlogPostModelCopyWith( - BlogPostModel value, $Res Function(BlogPostModel) then) = - _$BlogPostModelCopyWithImpl<$Res, BlogPostModel>; + factory $BlogPostModelCopyWith(BlogPostModel value, $Res Function(BlogPostModel) then) = _$BlogPostModelCopyWithImpl<$Res, BlogPostModel>; + @useResult $Res call( {int id, @@ -60,12 +68,12 @@ abstract class $BlogPostModelCopyWith<$Res> { } /// @nodoc -class _$BlogPostModelCopyWithImpl<$Res, $Val extends BlogPostModel> - implements $BlogPostModelCopyWith<$Res> { +class _$BlogPostModelCopyWithImpl<$Res, $Val extends BlogPostModel> implements $BlogPostModelCopyWith<$Res> { _$BlogPostModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -129,11 +137,9 @@ class _$BlogPostModelCopyWithImpl<$Res, $Val extends BlogPostModel> } /// @nodoc -abstract class _$$BlogPostModelImplCopyWith<$Res> - implements $BlogPostModelCopyWith<$Res> { - factory _$$BlogPostModelImplCopyWith( - _$BlogPostModelImpl value, $Res Function(_$BlogPostModelImpl) then) = - __$$BlogPostModelImplCopyWithImpl<$Res>; +abstract class _$$BlogPostModelImplCopyWith<$Res> implements $BlogPostModelCopyWith<$Res> { + factory _$$BlogPostModelImplCopyWith(_$BlogPostModelImpl value, $Res Function(_$BlogPostModelImpl) then) = __$$BlogPostModelImplCopyWithImpl<$Res>; + @override @useResult $Res call( @@ -150,12 +156,8 @@ abstract class _$$BlogPostModelImplCopyWith<$Res> } /// @nodoc -class __$$BlogPostModelImplCopyWithImpl<$Res> - extends _$BlogPostModelCopyWithImpl<$Res, _$BlogPostModelImpl> - implements _$$BlogPostModelImplCopyWith<$Res> { - __$$BlogPostModelImplCopyWithImpl( - _$BlogPostModelImpl _value, $Res Function(_$BlogPostModelImpl) _then) - : super(_value, _then); +class __$$BlogPostModelImplCopyWithImpl<$Res> extends _$BlogPostModelCopyWithImpl<$Res, _$BlogPostModelImpl> implements _$$BlogPostModelImplCopyWith<$Res> { + __$$BlogPostModelImplCopyWithImpl(_$BlogPostModelImpl _value, $Res Function(_$BlogPostModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -231,8 +233,7 @@ class _$BlogPostModelImpl implements _BlogPostModel { @JsonKey(name: "updated_at") required this.updatedAt, required this.title}); - factory _$BlogPostModelImpl.fromJson(Map json) => - _$$BlogPostModelImplFromJson(json); + factory _$BlogPostModelImpl.fromJson(Map json) => _$$BlogPostModelImplFromJson(json); @override final int id; @@ -271,31 +272,23 @@ class _$BlogPostModelImpl implements _BlogPostModel { (identical(other.id, id) || other.id == id) && (identical(other.state, state) || other.state == state) && (identical(other.image, image) || other.image == image) && - (identical(other.description, description) || - other.description == description) && - (identical(other.author_name, author_name) || - other.author_name == author_name) && - (identical(other.author_avatar_path, author_avatar_path) || - other.author_avatar_path == author_avatar_path) && - (identical(other.youtubeUrl, youtubeUrl) || - other.youtubeUrl == youtubeUrl) && - (identical(other.createdAt, createdAt) || - other.createdAt == createdAt) && - (identical(other.updatedAt, updatedAt) || - other.updatedAt == updatedAt) && + (identical(other.description, description) || other.description == description) && + (identical(other.author_name, author_name) || other.author_name == author_name) && + (identical(other.author_avatar_path, author_avatar_path) || other.author_avatar_path == author_avatar_path) && + (identical(other.youtubeUrl, youtubeUrl) || other.youtubeUrl == youtubeUrl) && + (identical(other.createdAt, createdAt) || other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt) && (identical(other.title, title) || other.title == title)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, state, image, description, - author_name, author_avatar_path, youtubeUrl, createdAt, updatedAt, title); + int get hashCode => Object.hash(runtimeType, id, state, image, description, author_name, author_avatar_path, youtubeUrl, createdAt, updatedAt, title); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => - __$$BlogPostModelImplCopyWithImpl<_$BlogPostModelImpl>(this, _$identity); + _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => __$$BlogPostModelImplCopyWithImpl<_$BlogPostModelImpl>(this, _$identity); @override Map toJson() { @@ -318,34 +311,42 @@ abstract class _BlogPostModel implements BlogPostModel { @JsonKey(name: "updated_at") required final DateTime updatedAt, required final String title}) = _$BlogPostModelImpl; - factory _BlogPostModel.fromJson(Map json) = - _$BlogPostModelImpl.fromJson; + factory _BlogPostModel.fromJson(Map json) = _$BlogPostModelImpl.fromJson; @override int get id; + @override String get state; + @override String? get image; + @override String get description; + @override String? get author_name; + @override String? get author_avatar_path; + @override @JsonKey(name: "youtube_url") String get youtubeUrl; + @override @JsonKey(name: "created_at") DateTime get createdAt; + @override @JsonKey(name: "updated_at") DateTime get updatedAt; + @override String get title; + @override @JsonKey(ignore: true) - _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/blog_post/models/blog_post_model.g.dart b/lib/features/blog_post/models/blog_post_model.g.dart index 2e3233c..137652f 100644 --- a/lib/features/blog_post/models/blog_post_model.g.dart +++ b/lib/features/blog_post/models/blog_post_model.g.dart @@ -6,8 +6,7 @@ part of 'blog_post_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$BlogPostModelImpl _$$BlogPostModelImplFromJson(Map json) => - _$BlogPostModelImpl( +_$BlogPostModelImpl _$$BlogPostModelImplFromJson(Map json) => _$BlogPostModelImpl( id: (json['id'] as num).toInt(), state: json['state'] as String, image: json['image'] as String?, @@ -20,8 +19,7 @@ _$BlogPostModelImpl _$$BlogPostModelImplFromJson(Map json) => title: json['title'] as String, ); -Map _$$BlogPostModelImplToJson(_$BlogPostModelImpl instance) => - { +Map _$$BlogPostModelImplToJson(_$BlogPostModelImpl instance) => { 'id': instance.id, 'state': instance.state, 'image': instance.image, diff --git a/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart b/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart index 4f99a3c..3776000 100644 --- a/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart +++ b/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart @@ -24,6 +24,7 @@ mixin _$BlogPostState { required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; + @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { @@ -70,36 +71,28 @@ mixin _$BlogPostState { /// @nodoc abstract class $BlogPostStateCopyWith<$Res> { - factory $BlogPostStateCopyWith( - BlogPostState value, $Res Function(BlogPostState) then) = - _$BlogPostStateCopyWithImpl<$Res, BlogPostState>; + factory $BlogPostStateCopyWith(BlogPostState value, $Res Function(BlogPostState) then) = _$BlogPostStateCopyWithImpl<$Res, BlogPostState>; } /// @nodoc -class _$BlogPostStateCopyWithImpl<$Res, $Val extends BlogPostState> - implements $BlogPostStateCopyWith<$Res> { +class _$BlogPostStateCopyWithImpl<$Res, $Val extends BlogPostState> implements $BlogPostStateCopyWith<$Res> { _$BlogPostStateCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; } /// @nodoc abstract class _$$BlogPostStateImplCopyWith<$Res> { - factory _$$BlogPostStateImplCopyWith( - _$BlogPostStateImpl value, $Res Function(_$BlogPostStateImpl) then) = - __$$BlogPostStateImplCopyWithImpl<$Res>; + factory _$$BlogPostStateImplCopyWith(_$BlogPostStateImpl value, $Res Function(_$BlogPostStateImpl) then) = __$$BlogPostStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$BlogPostStateImplCopyWithImpl<$Res> - extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateImpl> - implements _$$BlogPostStateImplCopyWith<$Res> { - __$$BlogPostStateImplCopyWithImpl( - _$BlogPostStateImpl _value, $Res Function(_$BlogPostStateImpl) _then) - : super(_value, _then); +class __$$BlogPostStateImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateImpl> implements _$$BlogPostStateImplCopyWith<$Res> { + __$$BlogPostStateImplCopyWithImpl(_$BlogPostStateImpl _value, $Res Function(_$BlogPostStateImpl) _then) : super(_value, _then); } /// @nodoc @@ -114,8 +107,7 @@ class _$BlogPostStateImpl implements _BlogPostState { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is _$BlogPostStateImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$BlogPostStateImpl); } @override @@ -202,18 +194,14 @@ abstract class _BlogPostState implements BlogPostState { /// @nodoc abstract class _$$BlogPostStateLoadingImplCopyWith<$Res> { - factory _$$BlogPostStateLoadingImplCopyWith(_$BlogPostStateLoadingImpl value, - $Res Function(_$BlogPostStateLoadingImpl) then) = + factory _$$BlogPostStateLoadingImplCopyWith(_$BlogPostStateLoadingImpl value, $Res Function(_$BlogPostStateLoadingImpl) then) = __$$BlogPostStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$BlogPostStateLoadingImplCopyWithImpl<$Res> - extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadingImpl> +class __$$BlogPostStateLoadingImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadingImpl> implements _$$BlogPostStateLoadingImplCopyWith<$Res> { - __$$BlogPostStateLoadingImplCopyWithImpl(_$BlogPostStateLoadingImpl _value, - $Res Function(_$BlogPostStateLoadingImpl) _then) - : super(_value, _then); + __$$BlogPostStateLoadingImplCopyWithImpl(_$BlogPostStateLoadingImpl _value, $Res Function(_$BlogPostStateLoadingImpl) _then) : super(_value, _then); } /// @nodoc @@ -228,9 +216,7 @@ class _$BlogPostStateLoadingImpl implements BlogPostStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$BlogPostStateLoadingImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$BlogPostStateLoadingImpl); } @override @@ -317,9 +303,9 @@ abstract class BlogPostStateLoading implements BlogPostState { /// @nodoc abstract class _$$BlogPostStateLoadedImplCopyWith<$Res> { - factory _$$BlogPostStateLoadedImplCopyWith(_$BlogPostStateLoadedImpl value, - $Res Function(_$BlogPostStateLoadedImpl) then) = + factory _$$BlogPostStateLoadedImplCopyWith(_$BlogPostStateLoadedImpl value, $Res Function(_$BlogPostStateLoadedImpl) then) = __$$BlogPostStateLoadedImplCopyWithImpl<$Res>; + @useResult $Res call({BlogPostModel blogPost}); @@ -327,12 +313,9 @@ abstract class _$$BlogPostStateLoadedImplCopyWith<$Res> { } /// @nodoc -class __$$BlogPostStateLoadedImplCopyWithImpl<$Res> - extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadedImpl> +class __$$BlogPostStateLoadedImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadedImpl> implements _$$BlogPostStateLoadedImplCopyWith<$Res> { - __$$BlogPostStateLoadedImplCopyWithImpl(_$BlogPostStateLoadedImpl _value, - $Res Function(_$BlogPostStateLoadedImpl) _then) - : super(_value, _then); + __$$BlogPostStateLoadedImplCopyWithImpl(_$BlogPostStateLoadedImpl _value, $Res Function(_$BlogPostStateLoadedImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -372,10 +355,7 @@ class _$BlogPostStateLoadedImpl implements BlogPostStateLoaded { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$BlogPostStateLoadedImpl && - (identical(other.blogPost, blogPost) || - other.blogPost == blogPost)); + (other.runtimeType == runtimeType && other is _$BlogPostStateLoadedImpl && (identical(other.blogPost, blogPost) || other.blogPost == blogPost)); } @override @@ -385,8 +365,7 @@ class _$BlogPostStateLoadedImpl implements BlogPostStateLoaded { @override @pragma('vm:prefer-inline') _$$BlogPostStateLoadedImplCopyWith<_$BlogPostStateLoadedImpl> get copyWith => - __$$BlogPostStateLoadedImplCopyWithImpl<_$BlogPostStateLoadedImpl>( - this, _$identity); + __$$BlogPostStateLoadedImplCopyWithImpl<_$BlogPostStateLoadedImpl>(this, _$identity); @override @optionalTypeArgs @@ -464,31 +443,27 @@ class _$BlogPostStateLoadedImpl implements BlogPostStateLoaded { } abstract class BlogPostStateLoaded implements BlogPostState { - const factory BlogPostStateLoaded({required final BlogPostModel blogPost}) = - _$BlogPostStateLoadedImpl; + const factory BlogPostStateLoaded({required final BlogPostModel blogPost}) = _$BlogPostStateLoadedImpl; BlogPostModel get blogPost; + @JsonKey(ignore: true) - _$$BlogPostStateLoadedImplCopyWith<_$BlogPostStateLoadedImpl> get copyWith => - throw _privateConstructorUsedError; + _$$BlogPostStateLoadedImplCopyWith<_$BlogPostStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$BlogPostStateErrorImplCopyWith<$Res> { - factory _$$BlogPostStateErrorImplCopyWith(_$BlogPostStateErrorImpl value, - $Res Function(_$BlogPostStateErrorImpl) then) = + factory _$$BlogPostStateErrorImplCopyWith(_$BlogPostStateErrorImpl value, $Res Function(_$BlogPostStateErrorImpl) then) = __$$BlogPostStateErrorImplCopyWithImpl<$Res>; + @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$BlogPostStateErrorImplCopyWithImpl<$Res> - extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateErrorImpl> +class __$$BlogPostStateErrorImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateErrorImpl> implements _$$BlogPostStateErrorImplCopyWith<$Res> { - __$$BlogPostStateErrorImplCopyWithImpl(_$BlogPostStateErrorImpl _value, - $Res Function(_$BlogPostStateErrorImpl) _then) - : super(_value, _then); + __$$BlogPostStateErrorImplCopyWithImpl(_$BlogPostStateErrorImpl _value, $Res Function(_$BlogPostStateErrorImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -522,8 +497,7 @@ class _$BlogPostStateErrorImpl implements BlogPostStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$BlogPostStateErrorImpl && - (identical(other.errorMessage, errorMessage) || - other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); } @override @@ -533,8 +507,7 @@ class _$BlogPostStateErrorImpl implements BlogPostStateError { @override @pragma('vm:prefer-inline') _$$BlogPostStateErrorImplCopyWith<_$BlogPostStateErrorImpl> get copyWith => - __$$BlogPostStateErrorImplCopyWithImpl<_$BlogPostStateErrorImpl>( - this, _$identity); + __$$BlogPostStateErrorImplCopyWithImpl<_$BlogPostStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -612,11 +585,10 @@ class _$BlogPostStateErrorImpl implements BlogPostStateError { } abstract class BlogPostStateError implements BlogPostState { - const factory BlogPostStateError({required final String errorMessage}) = - _$BlogPostStateErrorImpl; + const factory BlogPostStateError({required final String errorMessage}) = _$BlogPostStateErrorImpl; String get errorMessage; + @JsonKey(ignore: true) - _$$BlogPostStateErrorImplCopyWith<_$BlogPostStateErrorImpl> get copyWith => - throw _privateConstructorUsedError; + _$$BlogPostStateErrorImplCopyWith<_$BlogPostStateErrorImpl> get copyWith => throw _privateConstructorUsedError; } 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 8bb6630..c9f14dc 100644 --- a/lib/features/blog_post/presentation/pages/blog_post_screen.dart +++ b/lib/features/blog_post/presentation/pages/blog_post_screen.dart @@ -14,6 +14,7 @@ class BlogPostScreen extends StatelessWidget { final String blogPostID; const BlogPostScreen({super.key, required this.blogPostID}); + Widget build(BuildContext context) { return BlocProvider( create: (context) => sl()..loadBlogPost(blogPostID), 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 5ea30fc..422f042 100644 --- a/lib/features/blog_post/services/blog_post_service.g.dart +++ b/lib/features/blog_post/services/blog_post_service.g.dart @@ -24,31 +24,28 @@ class _BlogPostService implements BlogPostService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType(Options( + final _result = await _dio.fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/blogPosts/show/${id}', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/blogPosts/show/${id}', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = BlogPostModel.fromJson(_result.data!); return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && - !(requestOptions.responseType == ResponseType.bytes || - requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { diff --git a/lib/features/blog_post_create/repositories/blog_repository.dart b/lib/features/blog_post_create/repositories/blog_repository.dart index ee11cd1..3d1846a 100644 --- a/lib/features/blog_post_create/repositories/blog_repository.dart +++ b/lib/features/blog_post_create/repositories/blog_repository.dart @@ -18,4 +18,4 @@ class BlogRepository { } } } -*/ \ No newline at end of file +*/ diff --git a/lib/features/blog_post_create/services/blog_service.dart b/lib/features/blog_post_create/services/blog_service.dart index d8e9449..4b11062 100644 --- a/lib/features/blog_post_create/services/blog_service.dart +++ b/lib/features/blog_post_create/services/blog_service.dart @@ -13,4 +13,4 @@ abstract class BlogService { Future createBlogPost( BlogPostCreateCredentialsModel model); } -*/ \ No newline at end of file +*/ diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart index 02a1c4b..e150ef9 100644 --- a/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart +++ b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart @@ -24,6 +24,7 @@ mixin _$NewMessagesState { required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; + @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { @@ -70,36 +71,30 @@ mixin _$NewMessagesState { /// @nodoc abstract class $NewMessagesStateCopyWith<$Res> { - factory $NewMessagesStateCopyWith( - NewMessagesState value, $Res Function(NewMessagesState) then) = - _$NewMessagesStateCopyWithImpl<$Res, NewMessagesState>; + factory $NewMessagesStateCopyWith(NewMessagesState value, $Res Function(NewMessagesState) then) = _$NewMessagesStateCopyWithImpl<$Res, NewMessagesState>; } /// @nodoc -class _$NewMessagesStateCopyWithImpl<$Res, $Val extends NewMessagesState> - implements $NewMessagesStateCopyWith<$Res> { +class _$NewMessagesStateCopyWithImpl<$Res, $Val extends NewMessagesState> implements $NewMessagesStateCopyWith<$Res> { _$NewMessagesStateCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; } /// @nodoc abstract class _$$NewMessagesStateImplCopyWith<$Res> { - factory _$$NewMessagesStateImplCopyWith(_$NewMessagesStateImpl value, - $Res Function(_$NewMessagesStateImpl) then) = + factory _$$NewMessagesStateImplCopyWith(_$NewMessagesStateImpl value, $Res Function(_$NewMessagesStateImpl) then) = __$$NewMessagesStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NewMessagesStateImplCopyWithImpl<$Res> - extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateImpl> +class __$$NewMessagesStateImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateImpl> implements _$$NewMessagesStateImplCopyWith<$Res> { - __$$NewMessagesStateImplCopyWithImpl(_$NewMessagesStateImpl _value, - $Res Function(_$NewMessagesStateImpl) _then) - : super(_value, _then); + __$$NewMessagesStateImplCopyWithImpl(_$NewMessagesStateImpl _value, $Res Function(_$NewMessagesStateImpl) _then) : super(_value, _then); } /// @nodoc @@ -114,8 +109,7 @@ class _$NewMessagesStateImpl implements _NewMessagesState { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is _$NewMessagesStateImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateImpl); } @override @@ -202,19 +196,14 @@ abstract class _NewMessagesState implements NewMessagesState { /// @nodoc abstract class _$$NewMessagesStateEmptyImplCopyWith<$Res> { - factory _$$NewMessagesStateEmptyImplCopyWith( - _$NewMessagesStateEmptyImpl value, - $Res Function(_$NewMessagesStateEmptyImpl) then) = + factory _$$NewMessagesStateEmptyImplCopyWith(_$NewMessagesStateEmptyImpl value, $Res Function(_$NewMessagesStateEmptyImpl) then) = __$$NewMessagesStateEmptyImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NewMessagesStateEmptyImplCopyWithImpl<$Res> - extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateEmptyImpl> +class __$$NewMessagesStateEmptyImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateEmptyImpl> implements _$$NewMessagesStateEmptyImplCopyWith<$Res> { - __$$NewMessagesStateEmptyImplCopyWithImpl(_$NewMessagesStateEmptyImpl _value, - $Res Function(_$NewMessagesStateEmptyImpl) _then) - : super(_value, _then); + __$$NewMessagesStateEmptyImplCopyWithImpl(_$NewMessagesStateEmptyImpl _value, $Res Function(_$NewMessagesStateEmptyImpl) _then) : super(_value, _then); } /// @nodoc @@ -229,9 +218,7 @@ class _$NewMessagesStateEmptyImpl implements NewMessagesStateEmpty { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$NewMessagesStateEmptyImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateEmptyImpl); } @override @@ -318,22 +305,17 @@ abstract class NewMessagesStateEmpty implements NewMessagesState { /// @nodoc abstract class _$$NewMessagesStateLoadedImplCopyWith<$Res> { - factory _$$NewMessagesStateLoadedImplCopyWith( - _$NewMessagesStateLoadedImpl value, - $Res Function(_$NewMessagesStateLoadedImpl) then) = + factory _$$NewMessagesStateLoadedImplCopyWith(_$NewMessagesStateLoadedImpl value, $Res Function(_$NewMessagesStateLoadedImpl) then) = __$$NewMessagesStateLoadedImplCopyWithImpl<$Res>; + @useResult $Res call({int messagesCount}); } /// @nodoc -class __$$NewMessagesStateLoadedImplCopyWithImpl<$Res> - extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateLoadedImpl> +class __$$NewMessagesStateLoadedImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateLoadedImpl> implements _$$NewMessagesStateLoadedImplCopyWith<$Res> { - __$$NewMessagesStateLoadedImplCopyWithImpl( - _$NewMessagesStateLoadedImpl _value, - $Res Function(_$NewMessagesStateLoadedImpl) _then) - : super(_value, _then); + __$$NewMessagesStateLoadedImplCopyWithImpl(_$NewMessagesStateLoadedImpl _value, $Res Function(_$NewMessagesStateLoadedImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -367,8 +349,7 @@ class _$NewMessagesStateLoadedImpl implements NewMessagesStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateLoadedImpl && - (identical(other.messagesCount, messagesCount) || - other.messagesCount == messagesCount)); + (identical(other.messagesCount, messagesCount) || other.messagesCount == messagesCount)); } @override @@ -377,9 +358,8 @@ class _$NewMessagesStateLoadedImpl implements NewMessagesStateLoaded { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> - get copyWith => __$$NewMessagesStateLoadedImplCopyWithImpl< - _$NewMessagesStateLoadedImpl>(this, _$identity); + _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> get copyWith => + __$$NewMessagesStateLoadedImplCopyWithImpl<_$NewMessagesStateLoadedImpl>(this, _$identity); @override @optionalTypeArgs @@ -457,32 +437,27 @@ class _$NewMessagesStateLoadedImpl implements NewMessagesStateLoaded { } abstract class NewMessagesStateLoaded implements NewMessagesState { - const factory NewMessagesStateLoaded({required final int messagesCount}) = - _$NewMessagesStateLoadedImpl; + const factory NewMessagesStateLoaded({required final int messagesCount}) = _$NewMessagesStateLoadedImpl; int get messagesCount; + @JsonKey(ignore: true) - _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> - get copyWith => throw _privateConstructorUsedError; + _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$NewMessagesStateErrorImplCopyWith<$Res> { - factory _$$NewMessagesStateErrorImplCopyWith( - _$NewMessagesStateErrorImpl value, - $Res Function(_$NewMessagesStateErrorImpl) then) = + factory _$$NewMessagesStateErrorImplCopyWith(_$NewMessagesStateErrorImpl value, $Res Function(_$NewMessagesStateErrorImpl) then) = __$$NewMessagesStateErrorImplCopyWithImpl<$Res>; + @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$NewMessagesStateErrorImplCopyWithImpl<$Res> - extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateErrorImpl> +class __$$NewMessagesStateErrorImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateErrorImpl> implements _$$NewMessagesStateErrorImplCopyWith<$Res> { - __$$NewMessagesStateErrorImplCopyWithImpl(_$NewMessagesStateErrorImpl _value, - $Res Function(_$NewMessagesStateErrorImpl) _then) - : super(_value, _then); + __$$NewMessagesStateErrorImplCopyWithImpl(_$NewMessagesStateErrorImpl _value, $Res Function(_$NewMessagesStateErrorImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -516,8 +491,7 @@ class _$NewMessagesStateErrorImpl implements NewMessagesStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateErrorImpl && - (identical(other.errorMessage, errorMessage) || - other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); } @override @@ -526,9 +500,8 @@ class _$NewMessagesStateErrorImpl implements NewMessagesStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> - get copyWith => __$$NewMessagesStateErrorImplCopyWithImpl< - _$NewMessagesStateErrorImpl>(this, _$identity); + _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> get copyWith => + __$$NewMessagesStateErrorImplCopyWithImpl<_$NewMessagesStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -606,11 +579,10 @@ class _$NewMessagesStateErrorImpl implements NewMessagesStateError { } abstract class NewMessagesStateError implements NewMessagesState { - const factory NewMessagesStateError({required final String errorMessage}) = - _$NewMessagesStateErrorImpl; + const factory NewMessagesStateError({required final String errorMessage}) = _$NewMessagesStateErrorImpl; String get errorMessage; + @JsonKey(ignore: true) - _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> - get copyWith => throw _privateConstructorUsedError; + _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart b/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart index 0deeebb..b4b95e0 100644 --- a/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart +++ b/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart @@ -24,6 +24,7 @@ mixin _$NotificationsState { required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; + @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { @@ -70,36 +71,31 @@ mixin _$NotificationsState { /// @nodoc abstract class $NotificationsStateCopyWith<$Res> { - factory $NotificationsStateCopyWith( - NotificationsState value, $Res Function(NotificationsState) then) = + factory $NotificationsStateCopyWith(NotificationsState value, $Res Function(NotificationsState) then) = _$NotificationsStateCopyWithImpl<$Res, NotificationsState>; } /// @nodoc -class _$NotificationsStateCopyWithImpl<$Res, $Val extends NotificationsState> - implements $NotificationsStateCopyWith<$Res> { +class _$NotificationsStateCopyWithImpl<$Res, $Val extends NotificationsState> implements $NotificationsStateCopyWith<$Res> { _$NotificationsStateCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; } /// @nodoc abstract class _$$NotificationsStateImplCopyWith<$Res> { - factory _$$NotificationsStateImplCopyWith(_$NotificationsStateImpl value, - $Res Function(_$NotificationsStateImpl) then) = + factory _$$NotificationsStateImplCopyWith(_$NotificationsStateImpl value, $Res Function(_$NotificationsStateImpl) then) = __$$NotificationsStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NotificationsStateImplCopyWithImpl<$Res> - extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateImpl> +class __$$NotificationsStateImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateImpl> implements _$$NotificationsStateImplCopyWith<$Res> { - __$$NotificationsStateImplCopyWithImpl(_$NotificationsStateImpl _value, - $Res Function(_$NotificationsStateImpl) _then) - : super(_value, _then); + __$$NotificationsStateImplCopyWithImpl(_$NotificationsStateImpl _value, $Res Function(_$NotificationsStateImpl) _then) : super(_value, _then); } /// @nodoc @@ -114,8 +110,7 @@ class _$NotificationsStateImpl implements _NotificationsState { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is _$NotificationsStateImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateImpl); } @override @@ -202,21 +197,14 @@ abstract class _NotificationsState implements NotificationsState { /// @nodoc abstract class _$$NotificationsStateEmptyImplCopyWith<$Res> { - factory _$$NotificationsStateEmptyImplCopyWith( - _$NotificationsStateEmptyImpl value, - $Res Function(_$NotificationsStateEmptyImpl) then) = + factory _$$NotificationsStateEmptyImplCopyWith(_$NotificationsStateEmptyImpl value, $Res Function(_$NotificationsStateEmptyImpl) then) = __$$NotificationsStateEmptyImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NotificationsStateEmptyImplCopyWithImpl<$Res> - extends _$NotificationsStateCopyWithImpl<$Res, - _$NotificationsStateEmptyImpl> +class __$$NotificationsStateEmptyImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateEmptyImpl> implements _$$NotificationsStateEmptyImplCopyWith<$Res> { - __$$NotificationsStateEmptyImplCopyWithImpl( - _$NotificationsStateEmptyImpl _value, - $Res Function(_$NotificationsStateEmptyImpl) _then) - : super(_value, _then); + __$$NotificationsStateEmptyImplCopyWithImpl(_$NotificationsStateEmptyImpl _value, $Res Function(_$NotificationsStateEmptyImpl) _then) : super(_value, _then); } /// @nodoc @@ -231,9 +219,7 @@ class _$NotificationsStateEmptyImpl implements NotificationsStateEmpty { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$NotificationsStateEmptyImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateEmptyImpl); } @override @@ -320,22 +306,17 @@ abstract class NotificationsStateEmpty implements NotificationsState { /// @nodoc abstract class _$$NotificationsStateLoadedImplCopyWith<$Res> { - factory _$$NotificationsStateLoadedImplCopyWith( - _$NotificationsStateLoadedImpl value, - $Res Function(_$NotificationsStateLoadedImpl) then) = + factory _$$NotificationsStateLoadedImplCopyWith(_$NotificationsStateLoadedImpl value, $Res Function(_$NotificationsStateLoadedImpl) then) = __$$NotificationsStateLoadedImplCopyWithImpl<$Res>; + @useResult $Res call({int notificationsCount}); } /// @nodoc -class __$$NotificationsStateLoadedImplCopyWithImpl<$Res> - extends _$NotificationsStateCopyWithImpl<$Res, - _$NotificationsStateLoadedImpl> +class __$$NotificationsStateLoadedImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateLoadedImpl> implements _$$NotificationsStateLoadedImplCopyWith<$Res> { - __$$NotificationsStateLoadedImplCopyWithImpl( - _$NotificationsStateLoadedImpl _value, - $Res Function(_$NotificationsStateLoadedImpl) _then) + __$$NotificationsStateLoadedImplCopyWithImpl(_$NotificationsStateLoadedImpl _value, $Res Function(_$NotificationsStateLoadedImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -370,8 +351,7 @@ class _$NotificationsStateLoadedImpl implements NotificationsStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateLoadedImpl && - (identical(other.notificationsCount, notificationsCount) || - other.notificationsCount == notificationsCount)); + (identical(other.notificationsCount, notificationsCount) || other.notificationsCount == notificationsCount)); } @override @@ -380,9 +360,8 @@ class _$NotificationsStateLoadedImpl implements NotificationsStateLoaded { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> - get copyWith => __$$NotificationsStateLoadedImplCopyWithImpl< - _$NotificationsStateLoadedImpl>(this, _$identity); + _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> get copyWith => + __$$NotificationsStateLoadedImplCopyWithImpl<_$NotificationsStateLoadedImpl>(this, _$identity); @override @optionalTypeArgs @@ -460,34 +439,27 @@ class _$NotificationsStateLoadedImpl implements NotificationsStateLoaded { } abstract class NotificationsStateLoaded implements NotificationsState { - const factory NotificationsStateLoaded( - {required final int notificationsCount}) = _$NotificationsStateLoadedImpl; + const factory NotificationsStateLoaded({required final int notificationsCount}) = _$NotificationsStateLoadedImpl; int get notificationsCount; + @JsonKey(ignore: true) - _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> - get copyWith => throw _privateConstructorUsedError; + _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$NotificationsStateErrorImplCopyWith<$Res> { - factory _$$NotificationsStateErrorImplCopyWith( - _$NotificationsStateErrorImpl value, - $Res Function(_$NotificationsStateErrorImpl) then) = + factory _$$NotificationsStateErrorImplCopyWith(_$NotificationsStateErrorImpl value, $Res Function(_$NotificationsStateErrorImpl) then) = __$$NotificationsStateErrorImplCopyWithImpl<$Res>; + @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$NotificationsStateErrorImplCopyWithImpl<$Res> - extends _$NotificationsStateCopyWithImpl<$Res, - _$NotificationsStateErrorImpl> +class __$$NotificationsStateErrorImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateErrorImpl> implements _$$NotificationsStateErrorImplCopyWith<$Res> { - __$$NotificationsStateErrorImplCopyWithImpl( - _$NotificationsStateErrorImpl _value, - $Res Function(_$NotificationsStateErrorImpl) _then) - : super(_value, _then); + __$$NotificationsStateErrorImplCopyWithImpl(_$NotificationsStateErrorImpl _value, $Res Function(_$NotificationsStateErrorImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -521,8 +493,7 @@ class _$NotificationsStateErrorImpl implements NotificationsStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateErrorImpl && - (identical(other.errorMessage, errorMessage) || - other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); } @override @@ -531,9 +502,8 @@ class _$NotificationsStateErrorImpl implements NotificationsStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> - get copyWith => __$$NotificationsStateErrorImplCopyWithImpl< - _$NotificationsStateErrorImpl>(this, _$identity); + _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> get copyWith => + __$$NotificationsStateErrorImplCopyWithImpl<_$NotificationsStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -611,11 +581,10 @@ class _$NotificationsStateErrorImpl implements NotificationsStateError { } abstract class NotificationsStateError implements NotificationsState { - const factory NotificationsStateError({required final String errorMessage}) = - _$NotificationsStateErrorImpl; + const factory NotificationsStateError({required final String errorMessage}) = _$NotificationsStateErrorImpl; String get errorMessage; + @JsonKey(ignore: true) - _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> - get copyWith => throw _privateConstructorUsedError; + _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_message_model.freezed.dart b/lib/features/chat/models/chat_message_model.freezed.dart index 76a91cb..6dfda16 100644 --- a/lib/features/chat/models/chat_message_model.freezed.dart +++ b/lib/features/chat/models/chat_message_model.freezed.dart @@ -21,25 +21,28 @@ ChatMessageModel _$ChatMessageModelFromJson(Map json) { /// @nodoc mixin _$ChatMessageModel { int get id => throw _privateConstructorUsedError; + String get data => throw _privateConstructorUsedError; + @JsonKey(name: 'media_data') List? get mediaData => throw _privateConstructorUsedError; + @JsonKey(name: 'author_id') int get authorId => throw _privateConstructorUsedError; + @JsonKey(name: 'updated_at') String get updatedAt => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) - $ChatMessageModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $ChatMessageModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatMessageModelCopyWith<$Res> { - factory $ChatMessageModelCopyWith( - ChatMessageModel value, $Res Function(ChatMessageModel) then) = - _$ChatMessageModelCopyWithImpl<$Res, ChatMessageModel>; + factory $ChatMessageModelCopyWith(ChatMessageModel value, $Res Function(ChatMessageModel) then) = _$ChatMessageModelCopyWithImpl<$Res, ChatMessageModel>; + @useResult $Res call( {int id, @@ -50,12 +53,12 @@ abstract class $ChatMessageModelCopyWith<$Res> { } /// @nodoc -class _$ChatMessageModelCopyWithImpl<$Res, $Val extends ChatMessageModel> - implements $ChatMessageModelCopyWith<$Res> { +class _$ChatMessageModelCopyWithImpl<$Res, $Val extends ChatMessageModel> implements $ChatMessageModelCopyWith<$Res> { _$ChatMessageModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -94,11 +97,10 @@ class _$ChatMessageModelCopyWithImpl<$Res, $Val extends ChatMessageModel> } /// @nodoc -abstract class _$$ChatMessageModelImplCopyWith<$Res> - implements $ChatMessageModelCopyWith<$Res> { - factory _$$ChatMessageModelImplCopyWith(_$ChatMessageModelImpl value, - $Res Function(_$ChatMessageModelImpl) then) = +abstract class _$$ChatMessageModelImplCopyWith<$Res> implements $ChatMessageModelCopyWith<$Res> { + factory _$$ChatMessageModelImplCopyWith(_$ChatMessageModelImpl value, $Res Function(_$ChatMessageModelImpl) then) = __$$ChatMessageModelImplCopyWithImpl<$Res>; + @override @useResult $Res call( @@ -110,12 +112,9 @@ abstract class _$$ChatMessageModelImplCopyWith<$Res> } /// @nodoc -class __$$ChatMessageModelImplCopyWithImpl<$Res> - extends _$ChatMessageModelCopyWithImpl<$Res, _$ChatMessageModelImpl> +class __$$ChatMessageModelImplCopyWithImpl<$Res> extends _$ChatMessageModelCopyWithImpl<$Res, _$ChatMessageModelImpl> implements _$$ChatMessageModelImplCopyWith<$Res> { - __$$ChatMessageModelImplCopyWithImpl(_$ChatMessageModelImpl _value, - $Res Function(_$ChatMessageModelImpl) _then) - : super(_value, _then); + __$$ChatMessageModelImplCopyWithImpl(_$ChatMessageModelImpl _value, $Res Function(_$ChatMessageModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -162,14 +161,14 @@ class _$ChatMessageModelImpl implements _ChatMessageModel { @JsonKey(name: 'updated_at') required this.updatedAt}) : _mediaData = mediaData; - factory _$ChatMessageModelImpl.fromJson(Map json) => - _$$ChatMessageModelImplFromJson(json); + factory _$ChatMessageModelImpl.fromJson(Map json) => _$$ChatMessageModelImplFromJson(json); @override final int id; @override final String data; final List? _mediaData; + @override @JsonKey(name: 'media_data') List? get mediaData { @@ -199,25 +198,19 @@ class _$ChatMessageModelImpl implements _ChatMessageModel { other is _$ChatMessageModelImpl && (identical(other.id, id) || other.id == id) && (identical(other.data, data) || other.data == data) && - const DeepCollectionEquality() - .equals(other._mediaData, _mediaData) && - (identical(other.authorId, authorId) || - other.authorId == authorId) && - (identical(other.updatedAt, updatedAt) || - other.updatedAt == updatedAt)); + const DeepCollectionEquality().equals(other._mediaData, _mediaData) && + (identical(other.authorId, authorId) || other.authorId == authorId) && + (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, data, - const DeepCollectionEquality().hash(_mediaData), authorId, updatedAt); + int get hashCode => Object.hash(runtimeType, id, data, const DeepCollectionEquality().hash(_mediaData), authorId, updatedAt); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => - __$$ChatMessageModelImplCopyWithImpl<_$ChatMessageModelImpl>( - this, _$identity); + _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => __$$ChatMessageModelImplCopyWithImpl<_$ChatMessageModelImpl>(this, _$identity); @override Map toJson() { @@ -229,31 +222,33 @@ class _$ChatMessageModelImpl implements _ChatMessageModel { abstract class _ChatMessageModel implements ChatMessageModel { const factory _ChatMessageModel( - {required final int id, - required final String data, - @JsonKey(name: 'media_data') required final List? mediaData, - @JsonKey(name: 'author_id') required final int authorId, - @JsonKey(name: 'updated_at') required final String updatedAt}) = - _$ChatMessageModelImpl; + {required final int id, + required final String data, + @JsonKey(name: 'media_data') required final List? mediaData, + @JsonKey(name: 'author_id') required final int authorId, + @JsonKey(name: 'updated_at') required final String updatedAt}) = _$ChatMessageModelImpl; - factory _ChatMessageModel.fromJson(Map json) = - _$ChatMessageModelImpl.fromJson; + factory _ChatMessageModel.fromJson(Map json) = _$ChatMessageModelImpl.fromJson; @override int get id; + @override String get data; + @override @JsonKey(name: 'media_data') List? get mediaData; + @override @JsonKey(name: 'author_id') int get authorId; + @override @JsonKey(name: 'updated_at') String get updatedAt; + @override @JsonKey(ignore: true) - _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_message_model.g.dart b/lib/features/chat/models/chat_message_model.g.dart index 3a8d182..7053109 100644 --- a/lib/features/chat/models/chat_message_model.g.dart +++ b/lib/features/chat/models/chat_message_model.g.dart @@ -6,9 +6,7 @@ part of 'chat_message_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatMessageModelImpl _$$ChatMessageModelImplFromJson( - Map json) => - _$ChatMessageModelImpl( +_$ChatMessageModelImpl _$$ChatMessageModelImplFromJson(Map json) => _$ChatMessageModelImpl( id: (json['id'] as num).toInt(), data: json['data'] as String, mediaData: json['media_data'] as List?, @@ -16,9 +14,7 @@ _$ChatMessageModelImpl _$$ChatMessageModelImplFromJson( updatedAt: json['updated_at'] as String, ); -Map _$$ChatMessageModelImplToJson( - _$ChatMessageModelImpl instance) => - { +Map _$$ChatMessageModelImplToJson(_$ChatMessageModelImpl instance) => { 'id': instance.id, 'data': instance.data, 'media_data': instance.mediaData, diff --git a/lib/features/chat/models/chat_messages_model.dart b/lib/features/chat/models/chat_messages_model.dart index 999f598..84a51b4 100644 --- a/lib/features/chat/models/chat_messages_model.dart +++ b/lib/features/chat/models/chat_messages_model.dart @@ -3,6 +3,7 @@ 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_messages_model.freezed.dart b/lib/features/chat/models/chat_messages_model.freezed.dart index a970241..88f6278 100644 --- a/lib/features/chat/models/chat_messages_model.freezed.dart +++ b/lib/features/chat/models/chat_messages_model.freezed.dart @@ -22,34 +22,32 @@ ChatMessagesModel _$ChatMessagesModelFromJson(Map json) { mixin _$ChatMessagesModel { @JsonKey(name: 'data') List get messagesList => throw _privateConstructorUsedError; + ChatMetaModel get meta => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) - $ChatMessagesModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $ChatMessagesModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatMessagesModelCopyWith<$Res> { - factory $ChatMessagesModelCopyWith( - ChatMessagesModel value, $Res Function(ChatMessagesModel) then) = - _$ChatMessagesModelCopyWithImpl<$Res, ChatMessagesModel>; + factory $ChatMessagesModelCopyWith(ChatMessagesModel value, $Res Function(ChatMessagesModel) then) = _$ChatMessagesModelCopyWithImpl<$Res, ChatMessagesModel>; + @useResult - $Res call( - {@JsonKey(name: 'data') List messagesList, - ChatMetaModel meta}); + $Res call({@JsonKey(name: 'data') List messagesList, ChatMetaModel meta}); $ChatMetaModelCopyWith<$Res> get meta; } /// @nodoc -class _$ChatMessagesModelCopyWithImpl<$Res, $Val extends ChatMessagesModel> - implements $ChatMessagesModelCopyWith<$Res> { +class _$ChatMessagesModelCopyWithImpl<$Res, $Val extends ChatMessagesModel> implements $ChatMessagesModelCopyWith<$Res> { _$ChatMessagesModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -81,28 +79,22 @@ class _$ChatMessagesModelCopyWithImpl<$Res, $Val extends ChatMessagesModel> } /// @nodoc -abstract class _$$ChatMessagesModelImplCopyWith<$Res> - implements $ChatMessagesModelCopyWith<$Res> { - factory _$$ChatMessagesModelImplCopyWith(_$ChatMessagesModelImpl value, - $Res Function(_$ChatMessagesModelImpl) then) = +abstract class _$$ChatMessagesModelImplCopyWith<$Res> implements $ChatMessagesModelCopyWith<$Res> { + factory _$$ChatMessagesModelImplCopyWith(_$ChatMessagesModelImpl value, $Res Function(_$ChatMessagesModelImpl) then) = __$$ChatMessagesModelImplCopyWithImpl<$Res>; + @override @useResult - $Res call( - {@JsonKey(name: 'data') List messagesList, - ChatMetaModel meta}); + $Res call({@JsonKey(name: 'data') List messagesList, ChatMetaModel meta}); @override $ChatMetaModelCopyWith<$Res> get meta; } /// @nodoc -class __$$ChatMessagesModelImplCopyWithImpl<$Res> - extends _$ChatMessagesModelCopyWithImpl<$Res, _$ChatMessagesModelImpl> +class __$$ChatMessagesModelImplCopyWithImpl<$Res> extends _$ChatMessagesModelCopyWithImpl<$Res, _$ChatMessagesModelImpl> implements _$$ChatMessagesModelImplCopyWith<$Res> { - __$$ChatMessagesModelImplCopyWithImpl(_$ChatMessagesModelImpl _value, - $Res Function(_$ChatMessagesModelImpl) _then) - : super(_value, _then); + __$$ChatMessagesModelImplCopyWithImpl(_$ChatMessagesModelImpl _value, $Res Function(_$ChatMessagesModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -126,16 +118,12 @@ class __$$ChatMessagesModelImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() class _$ChatMessagesModelImpl implements _ChatMessagesModel { - const _$ChatMessagesModelImpl( - {@JsonKey(name: 'data') - required final List messagesList, - required this.meta}) - : _messagesList = messagesList; + const _$ChatMessagesModelImpl({@JsonKey(name: 'data') required final List messagesList, required this.meta}) : _messagesList = messagesList; - factory _$ChatMessagesModelImpl.fromJson(Map json) => - _$$ChatMessagesModelImplFromJson(json); + factory _$ChatMessagesModelImpl.fromJson(Map json) => _$$ChatMessagesModelImplFromJson(json); final List _messagesList; + @override @JsonKey(name: 'data') List get messagesList { @@ -157,22 +145,18 @@ class _$ChatMessagesModelImpl implements _ChatMessagesModel { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatMessagesModelImpl && - const DeepCollectionEquality() - .equals(other._messagesList, _messagesList) && + const DeepCollectionEquality().equals(other._messagesList, _messagesList) && (identical(other.meta, meta) || other.meta == meta)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash( - runtimeType, const DeepCollectionEquality().hash(_messagesList), meta); + int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_messagesList), meta); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => - __$$ChatMessagesModelImplCopyWithImpl<_$ChatMessagesModelImpl>( - this, _$identity); + _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => __$$ChatMessagesModelImplCopyWithImpl<_$ChatMessagesModelImpl>(this, _$identity); @override Map toJson() { @@ -183,21 +167,19 @@ class _$ChatMessagesModelImpl implements _ChatMessagesModel { } abstract class _ChatMessagesModel implements ChatMessagesModel { - const factory _ChatMessagesModel( - {@JsonKey(name: 'data') - required final List messagesList, - required final ChatMetaModel meta}) = _$ChatMessagesModelImpl; + const factory _ChatMessagesModel({@JsonKey(name: 'data') required final List messagesList, required final ChatMetaModel meta}) = + _$ChatMessagesModelImpl; - factory _ChatMessagesModel.fromJson(Map json) = - _$ChatMessagesModelImpl.fromJson; + factory _ChatMessagesModel.fromJson(Map json) = _$ChatMessagesModelImpl.fromJson; @override @JsonKey(name: 'data') List get messagesList; + @override ChatMetaModel get meta; + @override @JsonKey(ignore: true) - _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_messages_model.g.dart b/lib/features/chat/models/chat_messages_model.g.dart index 6216cd8..1a7fe48 100644 --- a/lib/features/chat/models/chat_messages_model.g.dart +++ b/lib/features/chat/models/chat_messages_model.g.dart @@ -6,18 +6,12 @@ part of 'chat_messages_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatMessagesModelImpl _$$ChatMessagesModelImplFromJson( - Map json) => - _$ChatMessagesModelImpl( - messagesList: (json['data'] as List) - .map((e) => ChatMessageModel.fromJson(e as Map)) - .toList(), +_$ChatMessagesModelImpl _$$ChatMessagesModelImplFromJson(Map json) => _$ChatMessagesModelImpl( + messagesList: (json['data'] as List).map((e) => ChatMessageModel.fromJson(e as Map)).toList(), meta: ChatMetaModel.fromJson(json['meta'] as Map), ); -Map _$$ChatMessagesModelImplToJson( - _$ChatMessagesModelImpl instance) => - { +Map _$$ChatMessagesModelImplToJson(_$ChatMessagesModelImpl instance) => { 'data': instance.messagesList, 'meta': instance.meta, }; diff --git a/lib/features/chat/models/chat_meta_model.freezed.dart b/lib/features/chat/models/chat_meta_model.freezed.dart index 11ecb9e..206048f 100644 --- a/lib/features/chat/models/chat_meta_model.freezed.dart +++ b/lib/features/chat/models/chat_meta_model.freezed.dart @@ -24,27 +24,26 @@ mixin _$ChatMetaModel { int get lastPage => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) - $ChatMetaModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $ChatMetaModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatMetaModelCopyWith<$Res> { - factory $ChatMetaModelCopyWith( - ChatMetaModel value, $Res Function(ChatMetaModel) then) = - _$ChatMetaModelCopyWithImpl<$Res, ChatMetaModel>; + factory $ChatMetaModelCopyWith(ChatMetaModel value, $Res Function(ChatMetaModel) then) = _$ChatMetaModelCopyWithImpl<$Res, ChatMetaModel>; + @useResult $Res call({@JsonKey(name: "last_page") int lastPage}); } /// @nodoc -class _$ChatMetaModelCopyWithImpl<$Res, $Val extends ChatMetaModel> - implements $ChatMetaModelCopyWith<$Res> { +class _$ChatMetaModelCopyWithImpl<$Res, $Val extends ChatMetaModel> implements $ChatMetaModelCopyWith<$Res> { _$ChatMetaModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -63,23 +62,17 @@ class _$ChatMetaModelCopyWithImpl<$Res, $Val extends ChatMetaModel> } /// @nodoc -abstract class _$$ChatMetaModelImplCopyWith<$Res> - implements $ChatMetaModelCopyWith<$Res> { - factory _$$ChatMetaModelImplCopyWith( - _$ChatMetaModelImpl value, $Res Function(_$ChatMetaModelImpl) then) = - __$$ChatMetaModelImplCopyWithImpl<$Res>; +abstract class _$$ChatMetaModelImplCopyWith<$Res> implements $ChatMetaModelCopyWith<$Res> { + factory _$$ChatMetaModelImplCopyWith(_$ChatMetaModelImpl value, $Res Function(_$ChatMetaModelImpl) then) = __$$ChatMetaModelImplCopyWithImpl<$Res>; + @override @useResult $Res call({@JsonKey(name: "last_page") int lastPage}); } /// @nodoc -class __$$ChatMetaModelImplCopyWithImpl<$Res> - extends _$ChatMetaModelCopyWithImpl<$Res, _$ChatMetaModelImpl> - implements _$$ChatMetaModelImplCopyWith<$Res> { - __$$ChatMetaModelImplCopyWithImpl( - _$ChatMetaModelImpl _value, $Res Function(_$ChatMetaModelImpl) _then) - : super(_value, _then); +class __$$ChatMetaModelImplCopyWithImpl<$Res> extends _$ChatMetaModelCopyWithImpl<$Res, _$ChatMetaModelImpl> implements _$$ChatMetaModelImplCopyWith<$Res> { + __$$ChatMetaModelImplCopyWithImpl(_$ChatMetaModelImpl _value, $Res Function(_$ChatMetaModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -98,11 +91,9 @@ class __$$ChatMetaModelImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() class _$ChatMetaModelImpl implements _ChatMetaModel { - const _$ChatMetaModelImpl( - {@JsonKey(name: "last_page") required this.lastPage}); + const _$ChatMetaModelImpl({@JsonKey(name: "last_page") required this.lastPage}); - factory _$ChatMetaModelImpl.fromJson(Map json) => - _$$ChatMetaModelImplFromJson(json); + factory _$ChatMetaModelImpl.fromJson(Map json) => _$$ChatMetaModelImplFromJson(json); @override @JsonKey(name: "last_page") @@ -116,10 +107,7 @@ class _$ChatMetaModelImpl implements _ChatMetaModel { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$ChatMetaModelImpl && - (identical(other.lastPage, lastPage) || - other.lastPage == lastPage)); + (other.runtimeType == runtimeType && other is _$ChatMetaModelImpl && (identical(other.lastPage, lastPage) || other.lastPage == lastPage)); } @JsonKey(ignore: true) @@ -129,8 +117,7 @@ class _$ChatMetaModelImpl implements _ChatMetaModel { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => - __$$ChatMetaModelImplCopyWithImpl<_$ChatMetaModelImpl>(this, _$identity); + _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => __$$ChatMetaModelImplCopyWithImpl<_$ChatMetaModelImpl>(this, _$identity); @override Map toJson() { @@ -141,18 +128,15 @@ class _$ChatMetaModelImpl implements _ChatMetaModel { } abstract class _ChatMetaModel implements ChatMetaModel { - const factory _ChatMetaModel( - {@JsonKey(name: "last_page") required final int lastPage}) = - _$ChatMetaModelImpl; + const factory _ChatMetaModel({@JsonKey(name: "last_page") required final int lastPage}) = _$ChatMetaModelImpl; - factory _ChatMetaModel.fromJson(Map json) = - _$ChatMetaModelImpl.fromJson; + factory _ChatMetaModel.fromJson(Map json) = _$ChatMetaModelImpl.fromJson; @override @JsonKey(name: "last_page") int get lastPage; + @override @JsonKey(ignore: true) - _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_meta_model.g.dart b/lib/features/chat/models/chat_meta_model.g.dart index 7126e2d..bbd16d1 100644 --- a/lib/features/chat/models/chat_meta_model.g.dart +++ b/lib/features/chat/models/chat_meta_model.g.dart @@ -6,12 +6,10 @@ part of 'chat_meta_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatMetaModelImpl _$$ChatMetaModelImplFromJson(Map json) => - _$ChatMetaModelImpl( +_$ChatMetaModelImpl _$$ChatMetaModelImplFromJson(Map json) => _$ChatMetaModelImpl( lastPage: (json['last_page'] as num).toInt(), ); -Map _$$ChatMetaModelImplToJson(_$ChatMetaModelImpl instance) => - { +Map _$$ChatMetaModelImplToJson(_$ChatMetaModelImpl instance) => { 'last_page': instance.lastPage, }; diff --git a/lib/features/chat/models/chat_room_model.freezed.dart b/lib/features/chat/models/chat_room_model.freezed.dart index 5a0b6e6..2606623 100644 --- a/lib/features/chat/models/chat_room_model.freezed.dart +++ b/lib/features/chat/models/chat_room_model.freezed.dart @@ -21,39 +21,35 @@ ChatRoomModel _$ChatRoomModelFromJson(Map json) { /// @nodoc mixin _$ChatRoomModel { String get id => throw _privateConstructorUsedError; + @JsonKey(name: 'chat_room_setting') - ChatRoomSettingsModel get chatRoomSettings => - throw _privateConstructorUsedError; + ChatRoomSettingsModel get chatRoomSettings => throw _privateConstructorUsedError; + Map get users => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) - $ChatRoomModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $ChatRoomModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatRoomModelCopyWith<$Res> { - factory $ChatRoomModelCopyWith( - ChatRoomModel value, $Res Function(ChatRoomModel) then) = - _$ChatRoomModelCopyWithImpl<$Res, ChatRoomModel>; + factory $ChatRoomModelCopyWith(ChatRoomModel value, $Res Function(ChatRoomModel) then) = _$ChatRoomModelCopyWithImpl<$Res, ChatRoomModel>; + @useResult - $Res call( - {String id, - @JsonKey(name: 'chat_room_setting') - ChatRoomSettingsModel chatRoomSettings, - Map users}); + $Res call({String id, @JsonKey(name: 'chat_room_setting') ChatRoomSettingsModel chatRoomSettings, Map users}); $ChatRoomSettingsModelCopyWith<$Res> get chatRoomSettings; } /// @nodoc -class _$ChatRoomModelCopyWithImpl<$Res, $Val extends ChatRoomModel> - implements $ChatRoomModelCopyWith<$Res> { +class _$ChatRoomModelCopyWithImpl<$Res, $Val extends ChatRoomModel> implements $ChatRoomModelCopyWith<$Res> { _$ChatRoomModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -83,38 +79,27 @@ class _$ChatRoomModelCopyWithImpl<$Res, $Val extends ChatRoomModel> @override @pragma('vm:prefer-inline') $ChatRoomSettingsModelCopyWith<$Res> get chatRoomSettings { - return $ChatRoomSettingsModelCopyWith<$Res>(_value.chatRoomSettings, - (value) { + return $ChatRoomSettingsModelCopyWith<$Res>(_value.chatRoomSettings, (value) { return _then(_value.copyWith(chatRoomSettings: value) as $Val); }); } } /// @nodoc -abstract class _$$ChatRoomModelImplCopyWith<$Res> - implements $ChatRoomModelCopyWith<$Res> { - factory _$$ChatRoomModelImplCopyWith( - _$ChatRoomModelImpl value, $Res Function(_$ChatRoomModelImpl) then) = - __$$ChatRoomModelImplCopyWithImpl<$Res>; +abstract class _$$ChatRoomModelImplCopyWith<$Res> implements $ChatRoomModelCopyWith<$Res> { + factory _$$ChatRoomModelImplCopyWith(_$ChatRoomModelImpl value, $Res Function(_$ChatRoomModelImpl) then) = __$$ChatRoomModelImplCopyWithImpl<$Res>; + @override @useResult - $Res call( - {String id, - @JsonKey(name: 'chat_room_setting') - ChatRoomSettingsModel chatRoomSettings, - Map users}); + $Res call({String id, @JsonKey(name: 'chat_room_setting') ChatRoomSettingsModel chatRoomSettings, Map users}); @override $ChatRoomSettingsModelCopyWith<$Res> get chatRoomSettings; } /// @nodoc -class __$$ChatRoomModelImplCopyWithImpl<$Res> - extends _$ChatRoomModelCopyWithImpl<$Res, _$ChatRoomModelImpl> - implements _$$ChatRoomModelImplCopyWith<$Res> { - __$$ChatRoomModelImplCopyWithImpl( - _$ChatRoomModelImpl _value, $Res Function(_$ChatRoomModelImpl) _then) - : super(_value, _then); +class __$$ChatRoomModelImplCopyWithImpl<$Res> extends _$ChatRoomModelCopyWithImpl<$Res, _$ChatRoomModelImpl> implements _$$ChatRoomModelImplCopyWith<$Res> { + __$$ChatRoomModelImplCopyWithImpl(_$ChatRoomModelImpl _value, $Res Function(_$ChatRoomModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -144,13 +129,10 @@ class __$$ChatRoomModelImplCopyWithImpl<$Res> @JsonSerializable() class _$ChatRoomModelImpl implements _ChatRoomModel { const _$ChatRoomModelImpl( - {required this.id, - @JsonKey(name: 'chat_room_setting') required this.chatRoomSettings, - required final Map users}) + {required this.id, @JsonKey(name: 'chat_room_setting') required this.chatRoomSettings, required final Map users}) : _users = users; - factory _$ChatRoomModelImpl.fromJson(Map json) => - _$$ChatRoomModelImplFromJson(json); + factory _$ChatRoomModelImpl.fromJson(Map json) => _$$ChatRoomModelImplFromJson(json); @override final String id; @@ -158,6 +140,7 @@ class _$ChatRoomModelImpl implements _ChatRoomModel { @JsonKey(name: 'chat_room_setting') final ChatRoomSettingsModel chatRoomSettings; final Map _users; + @override Map get users { if (_users is EqualUnmodifiableMapView) return _users; @@ -176,21 +159,18 @@ class _$ChatRoomModelImpl implements _ChatRoomModel { (other.runtimeType == runtimeType && other is _$ChatRoomModelImpl && (identical(other.id, id) || other.id == id) && - (identical(other.chatRoomSettings, chatRoomSettings) || - other.chatRoomSettings == chatRoomSettings) && + (identical(other.chatRoomSettings, chatRoomSettings) || other.chatRoomSettings == chatRoomSettings) && const DeepCollectionEquality().equals(other._users, _users)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, chatRoomSettings, - const DeepCollectionEquality().hash(_users)); + int get hashCode => Object.hash(runtimeType, id, chatRoomSettings, const DeepCollectionEquality().hash(_users)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => - __$$ChatRoomModelImplCopyWithImpl<_$ChatRoomModelImpl>(this, _$identity); + _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => __$$ChatRoomModelImplCopyWithImpl<_$ChatRoomModelImpl>(this, _$identity); @override Map toJson() { @@ -203,22 +183,22 @@ class _$ChatRoomModelImpl implements _ChatRoomModel { abstract class _ChatRoomModel implements ChatRoomModel { const factory _ChatRoomModel( {required final String id, - @JsonKey(name: 'chat_room_setting') - required final ChatRoomSettingsModel chatRoomSettings, + @JsonKey(name: 'chat_room_setting') required final ChatRoomSettingsModel chatRoomSettings, required final Map users}) = _$ChatRoomModelImpl; - factory _ChatRoomModel.fromJson(Map json) = - _$ChatRoomModelImpl.fromJson; + factory _ChatRoomModel.fromJson(Map json) = _$ChatRoomModelImpl.fromJson; @override String get id; + @override @JsonKey(name: 'chat_room_setting') ChatRoomSettingsModel get chatRoomSettings; + @override Map get users; + @override @JsonKey(ignore: true) - _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_room_model.g.dart b/lib/features/chat/models/chat_room_model.g.dart index 68d3195..6230d4f 100644 --- a/lib/features/chat/models/chat_room_model.g.dart +++ b/lib/features/chat/models/chat_room_model.g.dart @@ -6,19 +6,15 @@ part of 'chat_room_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatRoomModelImpl _$$ChatRoomModelImplFromJson(Map json) => - _$ChatRoomModelImpl( +_$ChatRoomModelImpl _$$ChatRoomModelImplFromJson(Map json) => _$ChatRoomModelImpl( id: json['id'] as String, - chatRoomSettings: ChatRoomSettingsModel.fromJson( - json['chat_room_setting'] as Map), + chatRoomSettings: ChatRoomSettingsModel.fromJson(json['chat_room_setting'] as Map), users: (json['users'] as Map).map( - (k, e) => - MapEntry(k, ChatUserModel.fromJson(e as Map)), + (k, e) => MapEntry(k, ChatUserModel.fromJson(e as Map)), ), ); -Map _$$ChatRoomModelImplToJson(_$ChatRoomModelImpl instance) => - { +Map _$$ChatRoomModelImplToJson(_$ChatRoomModelImpl instance) => { 'id': instance.id, 'chat_room_setting': instance.chatRoomSettings, 'users': instance.users, diff --git a/lib/features/chat/models/chat_room_settings_model.freezed.dart b/lib/features/chat/models/chat_room_settings_model.freezed.dart index 4f21755..48a1145 100644 --- a/lib/features/chat/models/chat_room_settings_model.freezed.dart +++ b/lib/features/chat/models/chat_room_settings_model.freezed.dart @@ -14,33 +14,36 @@ 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'); -ChatRoomSettingsModel _$ChatRoomSettingsModelFromJson( - Map json) { +ChatRoomSettingsModel _$ChatRoomSettingsModelFromJson(Map json) { return _ChatRoomSettingsModel.fromJson(json); } /// @nodoc mixin _$ChatRoomSettingsModel { int get id => throw _privateConstructorUsedError; + @JsonKey(name: 'room_name') String get roomName => throw _privateConstructorUsedError; + String get state => throw _privateConstructorUsedError; + @JsonKey(name: 'access_level') String get accessLevel => throw _privateConstructorUsedError; + @JsonKey(name: 'updated_at') String get updatedAt => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) - $ChatRoomSettingsModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $ChatRoomSettingsModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatRoomSettingsModelCopyWith<$Res> { - factory $ChatRoomSettingsModelCopyWith(ChatRoomSettingsModel value, - $Res Function(ChatRoomSettingsModel) then) = + factory $ChatRoomSettingsModelCopyWith(ChatRoomSettingsModel value, $Res Function(ChatRoomSettingsModel) then) = _$ChatRoomSettingsModelCopyWithImpl<$Res, ChatRoomSettingsModel>; + @useResult $Res call( {int id, @@ -51,13 +54,12 @@ abstract class $ChatRoomSettingsModelCopyWith<$Res> { } /// @nodoc -class _$ChatRoomSettingsModelCopyWithImpl<$Res, - $Val extends ChatRoomSettingsModel> - implements $ChatRoomSettingsModelCopyWith<$Res> { +class _$ChatRoomSettingsModelCopyWithImpl<$Res, $Val extends ChatRoomSettingsModel> implements $ChatRoomSettingsModelCopyWith<$Res> { _$ChatRoomSettingsModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -96,12 +98,10 @@ class _$ChatRoomSettingsModelCopyWithImpl<$Res, } /// @nodoc -abstract class _$$ChatRoomSettingsModelImplCopyWith<$Res> - implements $ChatRoomSettingsModelCopyWith<$Res> { - factory _$$ChatRoomSettingsModelImplCopyWith( - _$ChatRoomSettingsModelImpl value, - $Res Function(_$ChatRoomSettingsModelImpl) then) = +abstract class _$$ChatRoomSettingsModelImplCopyWith<$Res> implements $ChatRoomSettingsModelCopyWith<$Res> { + factory _$$ChatRoomSettingsModelImplCopyWith(_$ChatRoomSettingsModelImpl value, $Res Function(_$ChatRoomSettingsModelImpl) then) = __$$ChatRoomSettingsModelImplCopyWithImpl<$Res>; + @override @useResult $Res call( @@ -113,13 +113,9 @@ abstract class _$$ChatRoomSettingsModelImplCopyWith<$Res> } /// @nodoc -class __$$ChatRoomSettingsModelImplCopyWithImpl<$Res> - extends _$ChatRoomSettingsModelCopyWithImpl<$Res, - _$ChatRoomSettingsModelImpl> +class __$$ChatRoomSettingsModelImplCopyWithImpl<$Res> extends _$ChatRoomSettingsModelCopyWithImpl<$Res, _$ChatRoomSettingsModelImpl> implements _$$ChatRoomSettingsModelImplCopyWith<$Res> { - __$$ChatRoomSettingsModelImplCopyWithImpl(_$ChatRoomSettingsModelImpl _value, - $Res Function(_$ChatRoomSettingsModelImpl) _then) - : super(_value, _then); + __$$ChatRoomSettingsModelImplCopyWithImpl(_$ChatRoomSettingsModelImpl _value, $Res Function(_$ChatRoomSettingsModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -165,8 +161,7 @@ class _$ChatRoomSettingsModelImpl implements _ChatRoomSettingsModel { @JsonKey(name: 'access_level') required this.accessLevel, @JsonKey(name: 'updated_at') required this.updatedAt}); - factory _$ChatRoomSettingsModelImpl.fromJson(Map json) => - _$$ChatRoomSettingsModelImplFromJson(json); + factory _$ChatRoomSettingsModelImpl.fromJson(Map json) => _$$ChatRoomSettingsModelImplFromJson(json); @override final int id; @@ -193,26 +188,21 @@ class _$ChatRoomSettingsModelImpl implements _ChatRoomSettingsModel { (other.runtimeType == runtimeType && other is _$ChatRoomSettingsModelImpl && (identical(other.id, id) || other.id == id) && - (identical(other.roomName, roomName) || - other.roomName == roomName) && + (identical(other.roomName, roomName) || other.roomName == roomName) && (identical(other.state, state) || other.state == state) && - (identical(other.accessLevel, accessLevel) || - other.accessLevel == accessLevel) && - (identical(other.updatedAt, updatedAt) || - other.updatedAt == updatedAt)); + (identical(other.accessLevel, accessLevel) || other.accessLevel == accessLevel) && + (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)); } @JsonKey(ignore: true) @override - int get hashCode => - Object.hash(runtimeType, id, roomName, state, accessLevel, updatedAt); + int get hashCode => Object.hash(runtimeType, id, roomName, state, accessLevel, updatedAt); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> - get copyWith => __$$ChatRoomSettingsModelImplCopyWithImpl< - _$ChatRoomSettingsModelImpl>(this, _$identity); + _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> get copyWith => + __$$ChatRoomSettingsModelImplCopyWithImpl<_$ChatRoomSettingsModelImpl>(this, _$identity); @override Map toJson() { @@ -224,31 +214,33 @@ class _$ChatRoomSettingsModelImpl implements _ChatRoomSettingsModel { abstract class _ChatRoomSettingsModel implements ChatRoomSettingsModel { const factory _ChatRoomSettingsModel( - {required final int id, - @JsonKey(name: 'room_name') required final String roomName, - required final String state, - @JsonKey(name: 'access_level') required final String accessLevel, - @JsonKey(name: 'updated_at') required final String updatedAt}) = - _$ChatRoomSettingsModelImpl; + {required final int id, + @JsonKey(name: 'room_name') required final String roomName, + required final String state, + @JsonKey(name: 'access_level') required final String accessLevel, + @JsonKey(name: 'updated_at') required final String updatedAt}) = _$ChatRoomSettingsModelImpl; - factory _ChatRoomSettingsModel.fromJson(Map json) = - _$ChatRoomSettingsModelImpl.fromJson; + factory _ChatRoomSettingsModel.fromJson(Map json) = _$ChatRoomSettingsModelImpl.fromJson; @override int get id; + @override @JsonKey(name: 'room_name') String get roomName; + @override String get state; + @override @JsonKey(name: 'access_level') String get accessLevel; + @override @JsonKey(name: 'updated_at') String get updatedAt; + @override @JsonKey(ignore: true) - _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> - get copyWith => throw _privateConstructorUsedError; + _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_room_settings_model.g.dart b/lib/features/chat/models/chat_room_settings_model.g.dart index 7b82433..1a2ef32 100644 --- a/lib/features/chat/models/chat_room_settings_model.g.dart +++ b/lib/features/chat/models/chat_room_settings_model.g.dart @@ -6,9 +6,7 @@ part of 'chat_room_settings_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatRoomSettingsModelImpl _$$ChatRoomSettingsModelImplFromJson( - Map json) => - _$ChatRoomSettingsModelImpl( +_$ChatRoomSettingsModelImpl _$$ChatRoomSettingsModelImplFromJson(Map json) => _$ChatRoomSettingsModelImpl( id: (json['id'] as num).toInt(), roomName: json['room_name'] as String, state: json['state'] as String, @@ -16,9 +14,7 @@ _$ChatRoomSettingsModelImpl _$$ChatRoomSettingsModelImplFromJson( updatedAt: json['updated_at'] as String, ); -Map _$$ChatRoomSettingsModelImplToJson( - _$ChatRoomSettingsModelImpl instance) => - { +Map _$$ChatRoomSettingsModelImplToJson(_$ChatRoomSettingsModelImpl instance) => { 'id': instance.id, 'room_name': instance.roomName, 'state': instance.state, diff --git a/lib/features/chat/models/chat_user_model.freezed.dart b/lib/features/chat/models/chat_user_model.freezed.dart index 095c09e..9077493 100644 --- a/lib/features/chat/models/chat_user_model.freezed.dart +++ b/lib/features/chat/models/chat_user_model.freezed.dart @@ -21,38 +21,36 @@ ChatUserModel _$ChatUserModelFromJson(Map json) { /// @nodoc mixin _$ChatUserModel { int get id => throw _privateConstructorUsedError; + String get name => throw _privateConstructorUsedError; + @JsonKey(name: 'profile_photo_path') String? get profilePhotoPath => throw _privateConstructorUsedError; + @JsonKey(name: 'profile_photo_url') String? get profilePhotoUrl => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) - $ChatUserModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $ChatUserModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatUserModelCopyWith<$Res> { - factory $ChatUserModelCopyWith( - ChatUserModel value, $Res Function(ChatUserModel) then) = - _$ChatUserModelCopyWithImpl<$Res, ChatUserModel>; + factory $ChatUserModelCopyWith(ChatUserModel value, $Res Function(ChatUserModel) then) = _$ChatUserModelCopyWithImpl<$Res, ChatUserModel>; + @useResult - $Res call( - {int id, - String name, - @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, - @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); + $Res call({int id, String name, @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); } /// @nodoc -class _$ChatUserModelCopyWithImpl<$Res, $Val extends ChatUserModel> - implements $ChatUserModelCopyWith<$Res> { +class _$ChatUserModelCopyWithImpl<$Res, $Val extends ChatUserModel> implements $ChatUserModelCopyWith<$Res> { _$ChatUserModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -86,27 +84,17 @@ class _$ChatUserModelCopyWithImpl<$Res, $Val extends ChatUserModel> } /// @nodoc -abstract class _$$ChatUserModelImplCopyWith<$Res> - implements $ChatUserModelCopyWith<$Res> { - factory _$$ChatUserModelImplCopyWith( - _$ChatUserModelImpl value, $Res Function(_$ChatUserModelImpl) then) = - __$$ChatUserModelImplCopyWithImpl<$Res>; +abstract class _$$ChatUserModelImplCopyWith<$Res> implements $ChatUserModelCopyWith<$Res> { + factory _$$ChatUserModelImplCopyWith(_$ChatUserModelImpl value, $Res Function(_$ChatUserModelImpl) then) = __$$ChatUserModelImplCopyWithImpl<$Res>; + @override @useResult - $Res call( - {int id, - String name, - @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, - @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); + $Res call({int id, String name, @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); } /// @nodoc -class __$$ChatUserModelImplCopyWithImpl<$Res> - extends _$ChatUserModelCopyWithImpl<$Res, _$ChatUserModelImpl> - implements _$$ChatUserModelImplCopyWith<$Res> { - __$$ChatUserModelImplCopyWithImpl( - _$ChatUserModelImpl _value, $Res Function(_$ChatUserModelImpl) _then) - : super(_value, _then); +class __$$ChatUserModelImplCopyWithImpl<$Res> extends _$ChatUserModelCopyWithImpl<$Res, _$ChatUserModelImpl> implements _$$ChatUserModelImplCopyWith<$Res> { + __$$ChatUserModelImplCopyWithImpl(_$ChatUserModelImpl _value, $Res Function(_$ChatUserModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -146,8 +134,7 @@ class _$ChatUserModelImpl implements _ChatUserModel { @JsonKey(name: 'profile_photo_path') this.profilePhotoPath, @JsonKey(name: 'profile_photo_url') this.profilePhotoUrl}); - factory _$ChatUserModelImpl.fromJson(Map json) => - _$$ChatUserModelImplFromJson(json); + factory _$ChatUserModelImpl.fromJson(Map json) => _$$ChatUserModelImplFromJson(json); @override final int id; @@ -172,22 +159,18 @@ class _$ChatUserModelImpl implements _ChatUserModel { other is _$ChatUserModelImpl && (identical(other.id, id) || other.id == id) && (identical(other.name, name) || other.name == name) && - (identical(other.profilePhotoPath, profilePhotoPath) || - other.profilePhotoPath == profilePhotoPath) && - (identical(other.profilePhotoUrl, profilePhotoUrl) || - other.profilePhotoUrl == profilePhotoUrl)); + (identical(other.profilePhotoPath, profilePhotoPath) || other.profilePhotoPath == profilePhotoPath) && + (identical(other.profilePhotoUrl, profilePhotoUrl) || other.profilePhotoUrl == profilePhotoUrl)); } @JsonKey(ignore: true) @override - int get hashCode => - Object.hash(runtimeType, id, name, profilePhotoPath, profilePhotoUrl); + int get hashCode => Object.hash(runtimeType, id, name, profilePhotoPath, profilePhotoUrl); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => - __$$ChatUserModelImplCopyWithImpl<_$ChatUserModelImpl>(this, _$identity); + _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => __$$ChatUserModelImplCopyWithImpl<_$ChatUserModelImpl>(this, _$identity); @override Map toJson() { @@ -199,27 +182,28 @@ class _$ChatUserModelImpl implements _ChatUserModel { abstract class _ChatUserModel implements ChatUserModel { const factory _ChatUserModel( - {required final int id, - required final String name, - @JsonKey(name: 'profile_photo_path') final String? profilePhotoPath, - @JsonKey(name: 'profile_photo_url') final String? profilePhotoUrl}) = - _$ChatUserModelImpl; + {required final int id, + required final String name, + @JsonKey(name: 'profile_photo_path') final String? profilePhotoPath, + @JsonKey(name: 'profile_photo_url') final String? profilePhotoUrl}) = _$ChatUserModelImpl; - factory _ChatUserModel.fromJson(Map json) = - _$ChatUserModelImpl.fromJson; + factory _ChatUserModel.fromJson(Map json) = _$ChatUserModelImpl.fromJson; @override int get id; + @override String get name; + @override @JsonKey(name: 'profile_photo_path') String? get profilePhotoPath; + @override @JsonKey(name: 'profile_photo_url') String? get profilePhotoUrl; + @override @JsonKey(ignore: true) - _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_user_model.g.dart b/lib/features/chat/models/chat_user_model.g.dart index 78e0f98..06fa92a 100644 --- a/lib/features/chat/models/chat_user_model.g.dart +++ b/lib/features/chat/models/chat_user_model.g.dart @@ -6,16 +6,14 @@ part of 'chat_user_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatUserModelImpl _$$ChatUserModelImplFromJson(Map json) => - _$ChatUserModelImpl( +_$ChatUserModelImpl _$$ChatUserModelImplFromJson(Map json) => _$ChatUserModelImpl( id: (json['id'] as num).toInt(), name: json['name'] as String, profilePhotoPath: json['profile_photo_path'] as String?, profilePhotoUrl: json['profile_photo_url'] as String?, ); -Map _$$ChatUserModelImplToJson(_$ChatUserModelImpl instance) => - { +Map _$$ChatUserModelImplToJson(_$ChatUserModelImpl instance) => { 'id': instance.id, 'name': instance.name, 'profile_photo_path': instance.profilePhotoPath, diff --git a/lib/features/chat/models/websocket_info_model.freezed.dart b/lib/features/chat/models/websocket_info_model.freezed.dart index cd383a2..002f2ec 100644 --- a/lib/features/chat/models/websocket_info_model.freezed.dart +++ b/lib/features/chat/models/websocket_info_model.freezed.dart @@ -21,39 +21,38 @@ WebsocketInfoModel _$WebsocketInfoModelFromJson(Map json) { /// @nodoc mixin _$WebsocketInfoModel { String get key => throw _privateConstructorUsedError; + String get host => throw _privateConstructorUsedError; + String get port => throw _privateConstructorUsedError; + String get cluster => throw _privateConstructorUsedError; + @JsonKey(name: 'user_id') int get userId => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) - $WebsocketInfoModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $WebsocketInfoModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $WebsocketInfoModelCopyWith<$Res> { - factory $WebsocketInfoModelCopyWith( - WebsocketInfoModel value, $Res Function(WebsocketInfoModel) then) = + factory $WebsocketInfoModelCopyWith(WebsocketInfoModel value, $Res Function(WebsocketInfoModel) then) = _$WebsocketInfoModelCopyWithImpl<$Res, WebsocketInfoModel>; + @useResult - $Res call( - {String key, - String host, - String port, - String cluster, - @JsonKey(name: 'user_id') int userId}); + $Res call({String key, String host, String port, String cluster, @JsonKey(name: 'user_id') int userId}); } /// @nodoc -class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel> - implements $WebsocketInfoModelCopyWith<$Res> { +class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel> implements $WebsocketInfoModelCopyWith<$Res> { _$WebsocketInfoModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -92,28 +91,19 @@ class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel> } /// @nodoc -abstract class _$$WebsocketInfoModelImplCopyWith<$Res> - implements $WebsocketInfoModelCopyWith<$Res> { - factory _$$WebsocketInfoModelImplCopyWith(_$WebsocketInfoModelImpl value, - $Res Function(_$WebsocketInfoModelImpl) then) = +abstract class _$$WebsocketInfoModelImplCopyWith<$Res> implements $WebsocketInfoModelCopyWith<$Res> { + factory _$$WebsocketInfoModelImplCopyWith(_$WebsocketInfoModelImpl value, $Res Function(_$WebsocketInfoModelImpl) then) = __$$WebsocketInfoModelImplCopyWithImpl<$Res>; + @override @useResult - $Res call( - {String key, - String host, - String port, - String cluster, - @JsonKey(name: 'user_id') int userId}); + $Res call({String key, String host, String port, String cluster, @JsonKey(name: 'user_id') int userId}); } /// @nodoc -class __$$WebsocketInfoModelImplCopyWithImpl<$Res> - extends _$WebsocketInfoModelCopyWithImpl<$Res, _$WebsocketInfoModelImpl> +class __$$WebsocketInfoModelImplCopyWithImpl<$Res> extends _$WebsocketInfoModelCopyWithImpl<$Res, _$WebsocketInfoModelImpl> implements _$$WebsocketInfoModelImplCopyWith<$Res> { - __$$WebsocketInfoModelImplCopyWithImpl(_$WebsocketInfoModelImpl _value, - $Res Function(_$WebsocketInfoModelImpl) _then) - : super(_value, _then); + __$$WebsocketInfoModelImplCopyWithImpl(_$WebsocketInfoModelImpl _value, $Res Function(_$WebsocketInfoModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -153,14 +143,9 @@ class __$$WebsocketInfoModelImplCopyWithImpl<$Res> @JsonSerializable() class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { const _$WebsocketInfoModelImpl( - {required this.key, - required this.host, - required this.port, - required this.cluster, - @JsonKey(name: 'user_id') required this.userId}); + {required this.key, required this.host, required this.port, required this.cluster, @JsonKey(name: 'user_id') required this.userId}); - factory _$WebsocketInfoModelImpl.fromJson(Map json) => - _$$WebsocketInfoModelImplFromJson(json); + factory _$WebsocketInfoModelImpl.fromJson(Map json) => _$$WebsocketInfoModelImplFromJson(json); @override final String key; @@ -193,15 +178,13 @@ class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { @JsonKey(ignore: true) @override - int get hashCode => - Object.hash(runtimeType, key, host, port, cluster, userId); + int get hashCode => Object.hash(runtimeType, key, host, port, cluster, userId); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith => - __$$WebsocketInfoModelImplCopyWithImpl<_$WebsocketInfoModelImpl>( - this, _$identity); + __$$WebsocketInfoModelImplCopyWithImpl<_$WebsocketInfoModelImpl>(this, _$identity); @override Map toJson() { @@ -213,29 +196,31 @@ class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { abstract class _WebsocketInfoModel implements WebsocketInfoModel { const factory _WebsocketInfoModel( - {required final String key, - required final String host, - required final String port, - required final String cluster, - @JsonKey(name: 'user_id') required final int userId}) = - _$WebsocketInfoModelImpl; + {required final String key, + required final String host, + required final String port, + required final String cluster, + @JsonKey(name: 'user_id') required final int userId}) = _$WebsocketInfoModelImpl; - factory _WebsocketInfoModel.fromJson(Map json) = - _$WebsocketInfoModelImpl.fromJson; + factory _WebsocketInfoModel.fromJson(Map json) = _$WebsocketInfoModelImpl.fromJson; @override String get key; + @override String get host; + @override String get port; + @override String get cluster; + @override @JsonKey(name: 'user_id') int get userId; + @override @JsonKey(ignore: true) - _$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/websocket_info_model.g.dart b/lib/features/chat/models/websocket_info_model.g.dart index b2bb124..91c386f 100644 --- a/lib/features/chat/models/websocket_info_model.g.dart +++ b/lib/features/chat/models/websocket_info_model.g.dart @@ -6,9 +6,7 @@ part of 'websocket_info_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson( - Map json) => - _$WebsocketInfoModelImpl( +_$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson(Map json) => _$WebsocketInfoModelImpl( key: json['key'] as String, host: json['host'] as String, port: json['port'] as String, @@ -16,9 +14,7 @@ _$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson( userId: (json['user_id'] as num).toInt(), ); -Map _$$WebsocketInfoModelImplToJson( - _$WebsocketInfoModelImpl instance) => - { +Map _$$WebsocketInfoModelImplToJson(_$WebsocketInfoModelImpl instance) => { 'key': instance.key, 'host': instance.host, 'port': instance.port, diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart index 43bf9df..0001c80 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart @@ -20,19 +20,16 @@ mixin _$ChatRoomState { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading) - loaded, + required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; + @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult? Function(String errorMessage)? error, }) => throw _privateConstructorUsedError; @@ -40,9 +37,7 @@ mixin _$ChatRoomState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) => @@ -76,36 +71,28 @@ mixin _$ChatRoomState { /// @nodoc abstract class $ChatRoomStateCopyWith<$Res> { - factory $ChatRoomStateCopyWith( - ChatRoomState value, $Res Function(ChatRoomState) then) = - _$ChatRoomStateCopyWithImpl<$Res, ChatRoomState>; + factory $ChatRoomStateCopyWith(ChatRoomState value, $Res Function(ChatRoomState) then) = _$ChatRoomStateCopyWithImpl<$Res, ChatRoomState>; } /// @nodoc -class _$ChatRoomStateCopyWithImpl<$Res, $Val extends ChatRoomState> - implements $ChatRoomStateCopyWith<$Res> { +class _$ChatRoomStateCopyWithImpl<$Res, $Val extends ChatRoomState> implements $ChatRoomStateCopyWith<$Res> { _$ChatRoomStateCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; } /// @nodoc abstract class _$$ChatRoomStateImplCopyWith<$Res> { - factory _$$ChatRoomStateImplCopyWith( - _$ChatRoomStateImpl value, $Res Function(_$ChatRoomStateImpl) then) = - __$$ChatRoomStateImplCopyWithImpl<$Res>; + factory _$$ChatRoomStateImplCopyWith(_$ChatRoomStateImpl value, $Res Function(_$ChatRoomStateImpl) then) = __$$ChatRoomStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$ChatRoomStateImplCopyWithImpl<$Res> - extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateImpl> - implements _$$ChatRoomStateImplCopyWith<$Res> { - __$$ChatRoomStateImplCopyWithImpl( - _$ChatRoomStateImpl _value, $Res Function(_$ChatRoomStateImpl) _then) - : super(_value, _then); +class __$$ChatRoomStateImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateImpl> implements _$$ChatRoomStateImplCopyWith<$Res> { + __$$ChatRoomStateImplCopyWithImpl(_$ChatRoomStateImpl _value, $Res Function(_$ChatRoomStateImpl) _then) : super(_value, _then); } /// @nodoc @@ -120,8 +107,7 @@ class _$ChatRoomStateImpl implements _ChatRoomState { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is _$ChatRoomStateImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateImpl); } @override @@ -132,9 +118,7 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading) - loaded, + required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, required TResult Function(String errorMessage) error, }) { return $default(); @@ -145,9 +129,7 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult? Function(String errorMessage)? error, }) { return $default?.call(); @@ -158,9 +140,7 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -214,18 +194,14 @@ abstract class _ChatRoomState implements ChatRoomState { /// @nodoc abstract class _$$ChatRoomStateLoadingImplCopyWith<$Res> { - factory _$$ChatRoomStateLoadingImplCopyWith(_$ChatRoomStateLoadingImpl value, - $Res Function(_$ChatRoomStateLoadingImpl) then) = + factory _$$ChatRoomStateLoadingImplCopyWith(_$ChatRoomStateLoadingImpl value, $Res Function(_$ChatRoomStateLoadingImpl) then) = __$$ChatRoomStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$ChatRoomStateLoadingImplCopyWithImpl<$Res> - extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadingImpl> +class __$$ChatRoomStateLoadingImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadingImpl> implements _$$ChatRoomStateLoadingImplCopyWith<$Res> { - __$$ChatRoomStateLoadingImplCopyWithImpl(_$ChatRoomStateLoadingImpl _value, - $Res Function(_$ChatRoomStateLoadingImpl) _then) - : super(_value, _then); + __$$ChatRoomStateLoadingImplCopyWithImpl(_$ChatRoomStateLoadingImpl _value, $Res Function(_$ChatRoomStateLoadingImpl) _then) : super(_value, _then); } /// @nodoc @@ -240,9 +216,7 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$ChatRoomStateLoadingImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateLoadingImpl); } @override @@ -253,9 +227,7 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading) - loaded, + required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, required TResult Function(String errorMessage) error, }) { return loading(); @@ -266,9 +238,7 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult? Function(String errorMessage)? error, }) { return loading?.call(); @@ -279,9 +249,7 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -335,26 +303,19 @@ abstract class ChatRoomStateLoading implements ChatRoomState { /// @nodoc abstract class _$$ChatRoomStateLoadedImplCopyWith<$Res> { - factory _$$ChatRoomStateLoadedImplCopyWith(_$ChatRoomStateLoadedImpl value, - $Res Function(_$ChatRoomStateLoadedImpl) then) = + factory _$$ChatRoomStateLoadedImplCopyWith(_$ChatRoomStateLoadedImpl value, $Res Function(_$ChatRoomStateLoadedImpl) then) = __$$ChatRoomStateLoadedImplCopyWithImpl<$Res>; + @useResult - $Res call( - {ChatRoomModel chatRoom, - List chatMessages, - bool isTyping, - bool isLoading}); + $Res call({ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading}); $ChatRoomModelCopyWith<$Res> get chatRoom; } /// @nodoc -class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> - extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadedImpl> +class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadedImpl> implements _$$ChatRoomStateLoadedImplCopyWith<$Res> { - __$$ChatRoomStateLoadedImplCopyWithImpl(_$ChatRoomStateLoadedImpl _value, - $Res Function(_$ChatRoomStateLoadedImpl) _then) - : super(_value, _then); + __$$ChatRoomStateLoadedImplCopyWithImpl(_$ChatRoomStateLoadedImpl _value, $Res Function(_$ChatRoomStateLoadedImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -396,16 +357,13 @@ class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> /// @nodoc class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { - const _$ChatRoomStateLoadedImpl( - {required this.chatRoom, - required final List chatMessages, - required this.isTyping, - required this.isLoading}) + const _$ChatRoomStateLoadedImpl({required this.chatRoom, required final List chatMessages, required this.isTyping, required this.isLoading}) : _chatMessages = chatMessages; @override final ChatRoomModel chatRoom; final List _chatMessages; + @override List get chatMessages { if (_chatMessages is EqualUnmodifiableListView) return _chatMessages; @@ -428,35 +386,27 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateLoadedImpl && - (identical(other.chatRoom, chatRoom) || - other.chatRoom == chatRoom) && - const DeepCollectionEquality() - .equals(other._chatMessages, _chatMessages) && - (identical(other.isTyping, isTyping) || - other.isTyping == isTyping) && - (identical(other.isLoading, isLoading) || - other.isLoading == isLoading)); + (identical(other.chatRoom, chatRoom) || other.chatRoom == chatRoom) && + const DeepCollectionEquality().equals(other._chatMessages, _chatMessages) && + (identical(other.isTyping, isTyping) || other.isTyping == isTyping) && + (identical(other.isLoading, isLoading) || other.isLoading == isLoading)); } @override - int get hashCode => Object.hash(runtimeType, chatRoom, - const DeepCollectionEquality().hash(_chatMessages), isTyping, isLoading); + int get hashCode => Object.hash(runtimeType, chatRoom, const DeepCollectionEquality().hash(_chatMessages), isTyping, isLoading); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$ChatRoomStateLoadedImplCopyWith<_$ChatRoomStateLoadedImpl> get copyWith => - __$$ChatRoomStateLoadedImplCopyWithImpl<_$ChatRoomStateLoadedImpl>( - this, _$identity); + __$$ChatRoomStateLoadedImplCopyWithImpl<_$ChatRoomStateLoadedImpl>(this, _$identity); @override @optionalTypeArgs TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading) - loaded, + required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, required TResult Function(String errorMessage) error, }) { return loaded(chatRoom, chatMessages, isTyping, isLoading); @@ -467,9 +417,7 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult? Function(String errorMessage)? error, }) { return loaded?.call(chatRoom, chatMessages, isTyping, isLoading); @@ -480,9 +428,7 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -538,30 +484,30 @@ abstract class ChatRoomStateLoaded implements ChatRoomState { required final bool isLoading}) = _$ChatRoomStateLoadedImpl; ChatRoomModel get chatRoom; + List get chatMessages; + bool get isTyping; + bool get isLoading; + @JsonKey(ignore: true) - _$$ChatRoomStateLoadedImplCopyWith<_$ChatRoomStateLoadedImpl> get copyWith => - throw _privateConstructorUsedError; + _$$ChatRoomStateLoadedImplCopyWith<_$ChatRoomStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$ChatRoomStateErrorImplCopyWith<$Res> { - factory _$$ChatRoomStateErrorImplCopyWith(_$ChatRoomStateErrorImpl value, - $Res Function(_$ChatRoomStateErrorImpl) then) = + factory _$$ChatRoomStateErrorImplCopyWith(_$ChatRoomStateErrorImpl value, $Res Function(_$ChatRoomStateErrorImpl) then) = __$$ChatRoomStateErrorImplCopyWithImpl<$Res>; + @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$ChatRoomStateErrorImplCopyWithImpl<$Res> - extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateErrorImpl> +class __$$ChatRoomStateErrorImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateErrorImpl> implements _$$ChatRoomStateErrorImplCopyWith<$Res> { - __$$ChatRoomStateErrorImplCopyWithImpl(_$ChatRoomStateErrorImpl _value, - $Res Function(_$ChatRoomStateErrorImpl) _then) - : super(_value, _then); + __$$ChatRoomStateErrorImplCopyWithImpl(_$ChatRoomStateErrorImpl _value, $Res Function(_$ChatRoomStateErrorImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -595,8 +541,7 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateErrorImpl && - (identical(other.errorMessage, errorMessage) || - other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); } @override @@ -606,17 +551,14 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { @override @pragma('vm:prefer-inline') _$$ChatRoomStateErrorImplCopyWith<_$ChatRoomStateErrorImpl> get copyWith => - __$$ChatRoomStateErrorImplCopyWithImpl<_$ChatRoomStateErrorImpl>( - this, _$identity); + __$$ChatRoomStateErrorImplCopyWithImpl<_$ChatRoomStateErrorImpl>(this, _$identity); @override @optionalTypeArgs TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading) - loaded, + required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, required TResult Function(String errorMessage) error, }) { return error(errorMessage); @@ -627,9 +569,7 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult? Function(String errorMessage)? error, }) { return error?.call(errorMessage); @@ -640,9 +580,7 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, - List chatMessages, bool isTyping, bool isLoading)? - loaded, + TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -691,11 +629,10 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { } abstract class ChatRoomStateError implements ChatRoomState { - const factory ChatRoomStateError({required final String errorMessage}) = - _$ChatRoomStateErrorImpl; + const factory ChatRoomStateError({required final String errorMessage}) = _$ChatRoomStateErrorImpl; String get errorMessage; + @JsonKey(ignore: true) - _$$ChatRoomStateErrorImplCopyWith<_$ChatRoomStateErrorImpl> get copyWith => - throw _privateConstructorUsedError; + _$$ChatRoomStateErrorImplCopyWith<_$ChatRoomStateErrorImpl> get copyWith => throw _privateConstructorUsedError; } 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 2eaff04..0985a2f 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 @@ -14,7 +14,6 @@ import 'package:intl/intl.dart'; import '/core/app_export.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. @@ -29,18 +28,20 @@ class ChatSelectBloc extends Bloc { List chats = []; for (int i = 0; i < chatRooms.length; i++) { String text = chatRooms[i]['last_message'] is List ? '' : chatRooms[i]['last_message']['data']; - if (chatRooms[i]['last_message'] is !List && chatRooms[i]['last_message']['is_author_message_auth_user'] != null) { + if (chatRooms[i]['last_message'] is! List && chatRooms[i]['last_message']['is_author_message_auth_user'] != null) { text = "Вы: " + text; } chats.add( ChatItemModel( id: chatRooms[i]['id'], username: chatRooms[i]['users']['to_chat_user']['name'], - dateText: chatRooms[i]['last_message'] is List ? '' : DateFormat('dd.MM').format( - DateTime.parse( - chatRooms[i]['last_message']['updated_at'], - ), - ), + dateText: chatRooms[i]['last_message'] is List + ? '' + : DateFormat('dd.MM').format( + DateTime.parse( + chatRooms[i]['last_message']['updated_at'], + ), + ), greetingText: text, ), ); diff --git a/lib/features/chat/presentation/pages/chat_select_screen/models/chat_select_model.dart b/lib/features/chat/presentation/pages/chat_select_screen/models/chat_select_model.dart index 8a0ae04..e87ffa2 100644 --- a/lib/features/chat/presentation/pages/chat_select_screen/models/chat_select_model.dart +++ b/lib/features/chat/presentation/pages/chat_select_screen/models/chat_select_model.dart @@ -8,6 +8,7 @@ import 'package:equatable/equatable.dart'; class ChatSelectModel extends Equatable { ChatSelectModel({this.chatList = const []}); + List chatList; ChatSelectModel copyWith({List? chatList}) { diff --git a/lib/features/chat/services/chat_service.g.dart b/lib/features/chat/services/chat_service.g.dart index 2f0674b..8d212c4 100644 --- a/lib/features/chat/services/chat_service.g.dart +++ b/lib/features/chat/services/chat_service.g.dart @@ -24,25 +24,23 @@ class _ChatService implements ChatService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>( - _setStreamType>(Options( + final _result = await _dio.fetch>(_setStreamType>(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/chat/show/${id}', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - var _value = _result.data!.map((k, dynamic v) => - MapEntry(k, ChatRoomModel.fromJson(v as Map))); + .compose( + _dio.options, + '/api/chat/show/${id}', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + var _value = _result.data!.map((k, dynamic v) => MapEntry(k, ChatRoomModel.fromJson(v as Map))); return _value; } @@ -98,23 +96,22 @@ class _ChatService implements ChatService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType(Options( + final _result = await _dio.fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/chat/show/${id}/messages?page=${page}', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/chat/show/${id}/messages?page=${page}', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = ChatMessagesModel.fromJson(_result.data!); return _value; } @@ -125,31 +122,28 @@ class _ChatService implements ChatService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType(Options( + final _result = await _dio.fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/profile/ws/params', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/profile/ws/params', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = WebsocketInfoModel.fromJson(_result.data!); return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && - !(requestOptions.responseType == ResponseType.bytes || - requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { diff --git a/lib/features/diary/models/meal.dart b/lib/features/diary/models/meal.dart index a268a47..dbf3d06 100644 --- a/lib/features/diary/models/meal.dart +++ b/lib/features/diary/models/meal.dart @@ -3,6 +3,7 @@ import './portion.dart'; import './photo.dart'; part 'meal.freezed.dart'; + part 'meal.g.dart'; @freezed diff --git a/lib/features/diary/models/meal.freezed.dart b/lib/features/diary/models/meal.freezed.dart index 2c249b0..3f7f068 100644 --- a/lib/features/diary/models/meal.freezed.dart +++ b/lib/features/diary/models/meal.freezed.dart @@ -21,14 +21,21 @@ Meal _$MealFromJson(Map json) { /// @nodoc mixin _$Meal { int get id => throw _privateConstructorUsedError; + String get time => throw _privateConstructorUsedError; + int get type => throw _privateConstructorUsedError; + int get satiety => throw _privateConstructorUsedError; + int get mood => throw _privateConstructorUsedError; + List get portions => throw _privateConstructorUsedError; + List get photos => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) $MealCopyWith get copyWith => throw _privateConstructorUsedError; } @@ -36,16 +43,16 @@ mixin _$Meal { /// @nodoc abstract class $MealCopyWith<$Res> { factory $MealCopyWith(Meal value, $Res Function(Meal) then) = - _$MealCopyWithImpl<$Res, Meal>; + _$MealCopyWithImpl<$Res, Meal>; + @useResult - $Res call( - {int id, - String time, - int type, - int satiety, - int mood, - List portions, - List photos}); + $Res call({int id, + String time, + int type, + int satiety, + int mood, + List portions, + List photos}); } /// @nodoc @@ -55,6 +62,7 @@ class _$MealCopyWithImpl<$Res, $Val extends Meal> // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -73,55 +81,53 @@ class _$MealCopyWithImpl<$Res, $Val extends Meal> id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, time: null == time ? _value.time : time // ignore: cast_nullable_to_non_nullable - as String, + as String, type: null == type ? _value.type : type // ignore: cast_nullable_to_non_nullable - as int, + as int, satiety: null == satiety ? _value.satiety : satiety // ignore: cast_nullable_to_non_nullable - as int, + as int, mood: null == mood ? _value.mood : mood // ignore: cast_nullable_to_non_nullable - as int, + as int, portions: null == portions ? _value.portions : portions // ignore: cast_nullable_to_non_nullable - as List, + as List, photos: null == photos ? _value.photos : photos // ignore: cast_nullable_to_non_nullable - as List, + as List, ) as $Val); } } /// @nodoc abstract class _$$MealImplCopyWith<$Res> implements $MealCopyWith<$Res> { - factory _$$MealImplCopyWith( - _$MealImpl value, $Res Function(_$MealImpl) then) = - __$$MealImplCopyWithImpl<$Res>; + factory _$$MealImplCopyWith(_$MealImpl value, $Res Function(_$MealImpl) then) = + __$$MealImplCopyWithImpl<$Res>; + @override @useResult - $Res call( - {int id, - String time, - int type, - int satiety, - int mood, - List portions, - List photos}); + $Res call({int id, + String time, + int type, + int satiety, + int mood, + List portions, + List photos}); } /// @nodoc -class __$$MealImplCopyWithImpl<$Res> - extends _$MealCopyWithImpl<$Res, _$MealImpl> +class __$$MealImplCopyWithImpl<$Res> extends _$MealCopyWithImpl<$Res, _$MealImpl> implements _$$MealImplCopyWith<$Res> { __$$MealImplCopyWithImpl(_$MealImpl _value, $Res Function(_$MealImpl) _then) : super(_value, _then); @@ -141,31 +147,31 @@ class __$$MealImplCopyWithImpl<$Res> id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, time: null == time ? _value.time : time // ignore: cast_nullable_to_non_nullable - as String, + as String, type: null == type ? _value.type : type // ignore: cast_nullable_to_non_nullable - as int, + as int, satiety: null == satiety ? _value.satiety : satiety // ignore: cast_nullable_to_non_nullable - as int, + as int, mood: null == mood ? _value.mood : mood // ignore: cast_nullable_to_non_nullable - as int, + as int, portions: null == portions ? _value._portions : portions // ignore: cast_nullable_to_non_nullable - as List, + as List, photos: null == photos ? _value._photos : photos // ignore: cast_nullable_to_non_nullable - as List, + as List, )); } } @@ -173,14 +179,13 @@ class __$$MealImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() class _$MealImpl implements _Meal { - const _$MealImpl( - {required this.id, - required this.time, - required this.type, - required this.satiety, - required this.mood, - required final List portions, - required final List photos}) + const _$MealImpl({required this.id, + required this.time, + required this.type, + required this.satiety, + required this.mood, + required final List portions, + required final List photos}) : _portions = portions, _photos = photos; @@ -198,6 +203,7 @@ class _$MealImpl implements _Meal { @override final int mood; final List _portions; + @override List get portions { if (_portions is EqualUnmodifiableListView) return _portions; @@ -206,6 +212,7 @@ class _$MealImpl implements _Meal { } final List _photos; + @override List get photos { if (_photos is EqualUnmodifiableListView) return _photos; @@ -234,15 +241,16 @@ class _$MealImpl implements _Meal { @JsonKey(ignore: true) @override - int get hashCode => Object.hash( - runtimeType, - id, - time, - type, - satiety, - mood, - const DeepCollectionEquality().hash(_portions), - const DeepCollectionEquality().hash(_photos)); + int get hashCode => + Object.hash( + runtimeType, + id, + time, + type, + satiety, + mood, + const DeepCollectionEquality().hash(_portions), + const DeepCollectionEquality().hash(_photos)); @JsonKey(ignore: true) @override @@ -259,31 +267,37 @@ class _$MealImpl implements _Meal { } abstract class _Meal implements Meal { - const factory _Meal( - {required final int id, - required final String time, - required final int type, - required final int satiety, - required final int mood, - required final List portions, - required final List photos}) = _$MealImpl; + const factory _Meal({required final int id, + required final String time, + required final int type, + required final int satiety, + required final int mood, + required final List portions, + required final List photos}) = _$MealImpl; factory _Meal.fromJson(Map json) = _$MealImpl.fromJson; @override int get id; + @override String get time; + @override int get type; + @override int get satiety; + @override int get mood; + @override List get portions; + @override List get photos; + @override @JsonKey(ignore: true) _$$MealImplCopyWith<_$MealImpl> get copyWith => diff --git a/lib/features/diary/models/meal.g.dart b/lib/features/diary/models/meal.g.dart index 5536ed9..d6c9adf 100644 --- a/lib/features/diary/models/meal.g.dart +++ b/lib/features/diary/models/meal.g.dart @@ -6,7 +6,8 @@ part of 'meal.dart'; // JsonSerializableGenerator // ************************************************************************** -_$MealImpl _$$MealImplFromJson(Map json) => _$MealImpl( +_$MealImpl _$$MealImplFromJson(Map json) => + _$MealImpl( id: (json['id'] as num).toInt(), time: json['time'] as String, type: (json['type'] as num).toInt(), diff --git a/lib/features/diary/models/photo.dart b/lib/features/diary/models/photo.dart index f25b8f6..d3e4f69 100644 --- a/lib/features/diary/models/photo.dart +++ b/lib/features/diary/models/photo.dart @@ -1,14 +1,14 @@ import 'package:freezed_annotation/freezed_annotation.dart'; part 'photo.freezed.dart'; + part 'photo.g.dart'; @freezed class Photo with _$Photo { const factory Photo({ required int id, - @JsonKey(name: 'original_name') - required String originalName, + @JsonKey(name: 'original_name') required String originalName, required String path, }) = _Photo; diff --git a/lib/features/diary/models/photo.freezed.dart b/lib/features/diary/models/photo.freezed.dart index 2d9c70b..b58eceb 100644 --- a/lib/features/diary/models/photo.freezed.dart +++ b/lib/features/diary/models/photo.freezed.dart @@ -21,11 +21,14 @@ Photo _$PhotoFromJson(Map json) { /// @nodoc mixin _$Photo { int get id => throw _privateConstructorUsedError; + @JsonKey(name: 'original_name') String get originalName => throw _privateConstructorUsedError; + String get path => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) $PhotoCopyWith get copyWith => throw _privateConstructorUsedError; } @@ -33,12 +36,12 @@ mixin _$Photo { /// @nodoc abstract class $PhotoCopyWith<$Res> { factory $PhotoCopyWith(Photo value, $Res Function(Photo) then) = - _$PhotoCopyWithImpl<$Res, Photo>; + _$PhotoCopyWithImpl<$Res, Photo>; + @useResult - $Res call( - {int id, - @JsonKey(name: 'original_name') String originalName, - String path}); + $Res call({int id, + @JsonKey(name: 'original_name') String originalName, + String path}); } /// @nodoc @@ -48,6 +51,7 @@ class _$PhotoCopyWithImpl<$Res, $Val extends Photo> // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -62,38 +66,35 @@ class _$PhotoCopyWithImpl<$Res, $Val extends Photo> id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, originalName: null == originalName ? _value.originalName : originalName // ignore: cast_nullable_to_non_nullable - as String, + as String, path: null == path ? _value.path : path // ignore: cast_nullable_to_non_nullable - as String, + as String, ) as $Val); } } /// @nodoc abstract class _$$PhotoImplCopyWith<$Res> implements $PhotoCopyWith<$Res> { - factory _$$PhotoImplCopyWith( - _$PhotoImpl value, $Res Function(_$PhotoImpl) then) = - __$$PhotoImplCopyWithImpl<$Res>; + factory _$$PhotoImplCopyWith(_$PhotoImpl value, $Res Function(_$PhotoImpl) then) = + __$$PhotoImplCopyWithImpl<$Res>; + @override @useResult - $Res call( - {int id, - @JsonKey(name: 'original_name') String originalName, - String path}); + $Res call({int id, + @JsonKey(name: 'original_name') String originalName, + String path}); } /// @nodoc -class __$$PhotoImplCopyWithImpl<$Res> - extends _$PhotoCopyWithImpl<$Res, _$PhotoImpl> +class __$$PhotoImplCopyWithImpl<$Res> extends _$PhotoCopyWithImpl<$Res, _$PhotoImpl> implements _$$PhotoImplCopyWith<$Res> { - __$$PhotoImplCopyWithImpl( - _$PhotoImpl _value, $Res Function(_$PhotoImpl) _then) + __$$PhotoImplCopyWithImpl(_$PhotoImpl _value, $Res Function(_$PhotoImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -107,15 +108,15 @@ class __$$PhotoImplCopyWithImpl<$Res> id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, originalName: null == originalName ? _value.originalName : originalName // ignore: cast_nullable_to_non_nullable - as String, + as String, path: null == path ? _value.path : path // ignore: cast_nullable_to_non_nullable - as String, + as String, )); } } @@ -123,10 +124,9 @@ class __$$PhotoImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() class _$PhotoImpl implements _Photo { - const _$PhotoImpl( - {required this.id, - @JsonKey(name: 'original_name') required this.originalName, - required this.path}); + const _$PhotoImpl({required this.id, + @JsonKey(name: 'original_name') required this.originalName, + required this.path}); factory _$PhotoImpl.fromJson(Map json) => _$$PhotoImplFromJson(json); @@ -174,20 +174,22 @@ class _$PhotoImpl implements _Photo { } abstract class _Photo implements Photo { - const factory _Photo( - {required final int id, - @JsonKey(name: 'original_name') required final String originalName, - required final String path}) = _$PhotoImpl; + const factory _Photo({required final int id, + @JsonKey(name: 'original_name') required final String originalName, + required final String path}) = _$PhotoImpl; factory _Photo.fromJson(Map json) = _$PhotoImpl.fromJson; @override int get id; + @override @JsonKey(name: 'original_name') String get originalName; + @override String get path; + @override @JsonKey(ignore: true) _$$PhotoImplCopyWith<_$PhotoImpl> get copyWith => diff --git a/lib/features/diary/models/photo.g.dart b/lib/features/diary/models/photo.g.dart index cacf65a..19711bb 100644 --- a/lib/features/diary/models/photo.g.dart +++ b/lib/features/diary/models/photo.g.dart @@ -6,7 +6,8 @@ part of 'photo.dart'; // JsonSerializableGenerator // ************************************************************************** -_$PhotoImpl _$$PhotoImplFromJson(Map json) => _$PhotoImpl( +_$PhotoImpl _$$PhotoImplFromJson(Map json) => + _$PhotoImpl( id: (json['id'] as num).toInt(), originalName: json['original_name'] as String, path: json['path'] as String, diff --git a/lib/features/diary/models/portion.dart b/lib/features/diary/models/portion.dart index ec4ab1d..51ec5bb 100644 --- a/lib/features/diary/models/portion.dart +++ b/lib/features/diary/models/portion.dart @@ -1,6 +1,7 @@ import 'package:freezed_annotation/freezed_annotation.dart'; part 'portion.freezed.dart'; + part 'portion.g.dart'; @freezed diff --git a/lib/features/diary/models/portion.freezed.dart b/lib/features/diary/models/portion.freezed.dart index a7a35a2..b909af6 100644 --- a/lib/features/diary/models/portion.freezed.dart +++ b/lib/features/diary/models/portion.freezed.dart @@ -21,11 +21,15 @@ Portion _$PortionFromJson(Map json) { /// @nodoc mixin _$Portion { int get id => throw _privateConstructorUsedError; + String get product_name => throw _privateConstructorUsedError; + int get quantity => throw _privateConstructorUsedError; + String get portion => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) $PortionCopyWith get copyWith => throw _privateConstructorUsedError; } @@ -33,7 +37,8 @@ mixin _$Portion { /// @nodoc abstract class $PortionCopyWith<$Res> { factory $PortionCopyWith(Portion value, $Res Function(Portion) then) = - _$PortionCopyWithImpl<$Res, Portion>; + _$PortionCopyWithImpl<$Res, Portion>; + @useResult $Res call({int id, String product_name, int quantity, String portion}); } @@ -45,6 +50,7 @@ class _$PortionCopyWithImpl<$Res, $Val extends Portion> // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -60,39 +66,37 @@ class _$PortionCopyWithImpl<$Res, $Val extends Portion> id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, product_name: null == product_name ? _value.product_name : product_name // ignore: cast_nullable_to_non_nullable - as String, + as String, quantity: null == quantity ? _value.quantity : quantity // ignore: cast_nullable_to_non_nullable - as int, + as int, portion: null == portion ? _value.portion : portion // ignore: cast_nullable_to_non_nullable - as String, + as String, ) as $Val); } } /// @nodoc abstract class _$$PortionImplCopyWith<$Res> implements $PortionCopyWith<$Res> { - factory _$$PortionImplCopyWith( - _$PortionImpl value, $Res Function(_$PortionImpl) then) = - __$$PortionImplCopyWithImpl<$Res>; + factory _$$PortionImplCopyWith(_$PortionImpl value, $Res Function(_$PortionImpl) then) = + __$$PortionImplCopyWithImpl<$Res>; + @override @useResult $Res call({int id, String product_name, int quantity, String portion}); } /// @nodoc -class __$$PortionImplCopyWithImpl<$Res> - extends _$PortionCopyWithImpl<$Res, _$PortionImpl> +class __$$PortionImplCopyWithImpl<$Res> extends _$PortionCopyWithImpl<$Res, _$PortionImpl> implements _$$PortionImplCopyWith<$Res> { - __$$PortionImplCopyWithImpl( - _$PortionImpl _value, $Res Function(_$PortionImpl) _then) + __$$PortionImplCopyWithImpl(_$PortionImpl _value, $Res Function(_$PortionImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -107,19 +111,19 @@ class __$$PortionImplCopyWithImpl<$Res> id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, product_name: null == product_name ? _value.product_name : product_name // ignore: cast_nullable_to_non_nullable - as String, + as String, quantity: null == quantity ? _value.quantity : quantity // ignore: cast_nullable_to_non_nullable - as int, + as int, portion: null == portion ? _value.portion : portion // ignore: cast_nullable_to_non_nullable - as String, + as String, )); } } @@ -127,11 +131,10 @@ class __$$PortionImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() class _$PortionImpl implements _Portion { - const _$PortionImpl( - {required this.id, - required this.product_name, - required this.quantity, - required this.portion}); + const _$PortionImpl({required this.id, + required this.product_name, + required this.quantity, + required this.portion}); factory _$PortionImpl.fromJson(Map json) => _$$PortionImplFromJson(json); @@ -183,22 +186,25 @@ class _$PortionImpl implements _Portion { } abstract class _Portion implements Portion { - const factory _Portion( - {required final int id, - required final String product_name, - required final int quantity, - required final String portion}) = _$PortionImpl; + const factory _Portion({required final int id, + required final String product_name, + required final int quantity, + required final String portion}) = _$PortionImpl; factory _Portion.fromJson(Map json) = _$PortionImpl.fromJson; @override int get id; + @override String get product_name; + @override int get quantity; + @override String get portion; + @override @JsonKey(ignore: true) _$$PortionImplCopyWith<_$PortionImpl> get copyWith => diff --git a/lib/features/diary/models/product.dart b/lib/features/diary/models/product.dart index a11896d..d054257 100644 --- a/lib/features/diary/models/product.dart +++ b/lib/features/diary/models/product.dart @@ -1,6 +1,7 @@ import 'package:freezed_annotation/freezed_annotation.dart'; part 'product.freezed.dart'; + part 'product.g.dart'; @freezed diff --git a/lib/features/diary/models/product.freezed.dart b/lib/features/diary/models/product.freezed.dart index d30ada3..d4c87df 100644 --- a/lib/features/diary/models/product.freezed.dart +++ b/lib/features/diary/models/product.freezed.dart @@ -21,9 +21,11 @@ Product _$ProductFromJson(Map json) { /// @nodoc mixin _$Product { int get id => throw _privateConstructorUsedError; + String get name => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) $ProductCopyWith get copyWith => throw _privateConstructorUsedError; } @@ -31,7 +33,8 @@ mixin _$Product { /// @nodoc abstract class $ProductCopyWith<$Res> { factory $ProductCopyWith(Product value, $Res Function(Product) then) = - _$ProductCopyWithImpl<$Res, Product>; + _$ProductCopyWithImpl<$Res, Product>; + @useResult $Res call({int id, String name}); } @@ -43,6 +46,7 @@ class _$ProductCopyWithImpl<$Res, $Val extends Product> // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -56,31 +60,29 @@ class _$ProductCopyWithImpl<$Res, $Val extends Product> id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, name: null == name ? _value.name : name // ignore: cast_nullable_to_non_nullable - as String, + as String, ) as $Val); } } /// @nodoc abstract class _$$ProductImplCopyWith<$Res> implements $ProductCopyWith<$Res> { - factory _$$ProductImplCopyWith( - _$ProductImpl value, $Res Function(_$ProductImpl) then) = - __$$ProductImplCopyWithImpl<$Res>; + factory _$$ProductImplCopyWith(_$ProductImpl value, $Res Function(_$ProductImpl) then) = + __$$ProductImplCopyWithImpl<$Res>; + @override @useResult $Res call({int id, String name}); } /// @nodoc -class __$$ProductImplCopyWithImpl<$Res> - extends _$ProductCopyWithImpl<$Res, _$ProductImpl> +class __$$ProductImplCopyWithImpl<$Res> extends _$ProductCopyWithImpl<$Res, _$ProductImpl> implements _$$ProductImplCopyWith<$Res> { - __$$ProductImplCopyWithImpl( - _$ProductImpl _value, $Res Function(_$ProductImpl) _then) + __$$ProductImplCopyWithImpl(_$ProductImpl _value, $Res Function(_$ProductImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -93,11 +95,11 @@ class __$$ProductImplCopyWithImpl<$Res> id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, name: null == name ? _value.name : name // ignore: cast_nullable_to_non_nullable - as String, + as String, )); } } @@ -149,14 +151,16 @@ class _$ProductImpl implements _Product { abstract class _Product implements Product { const factory _Product({required final int id, required final String name}) = - _$ProductImpl; + _$ProductImpl; factory _Product.fromJson(Map json) = _$ProductImpl.fromJson; @override int get id; + @override String get name; + @override @JsonKey(ignore: true) _$$ProductImplCopyWith<_$ProductImpl> get copyWith => diff --git a/lib/features/feed/models/feed_blog_post_model.freezed.dart b/lib/features/feed/models/feed_blog_post_model.freezed.dart index 4d753a1..425591a 100644 --- a/lib/features/feed/models/feed_blog_post_model.freezed.dart +++ b/lib/features/feed/models/feed_blog_post_model.freezed.dart @@ -21,28 +21,34 @@ FeedBlogPostModel _$FeedBlogPostModelFromJson(Map json) { /// @nodoc mixin _$FeedBlogPostModel { int get id => throw _privateConstructorUsedError; + String get state => throw _privateConstructorUsedError; + String get image => throw _privateConstructorUsedError; + String get description => throw _privateConstructorUsedError; + @JsonKey(name: "youtube_url") String get youtubeUrl => throw _privateConstructorUsedError; + @JsonKey(name: "created_at") DateTime get createdAt => throw _privateConstructorUsedError; + @JsonKey(name: "updated_at") DateTime get updatedAt => throw _privateConstructorUsedError; + String get title => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) - $FeedBlogPostModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $FeedBlogPostModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $FeedBlogPostModelCopyWith<$Res> { - factory $FeedBlogPostModelCopyWith( - FeedBlogPostModel value, $Res Function(FeedBlogPostModel) then) = - _$FeedBlogPostModelCopyWithImpl<$Res, FeedBlogPostModel>; + factory $FeedBlogPostModelCopyWith(FeedBlogPostModel value, $Res Function(FeedBlogPostModel) then) = _$FeedBlogPostModelCopyWithImpl<$Res, FeedBlogPostModel>; + @useResult $Res call( {int id, @@ -56,12 +62,12 @@ abstract class $FeedBlogPostModelCopyWith<$Res> { } /// @nodoc -class _$FeedBlogPostModelCopyWithImpl<$Res, $Val extends FeedBlogPostModel> - implements $FeedBlogPostModelCopyWith<$Res> { +class _$FeedBlogPostModelCopyWithImpl<$Res, $Val extends FeedBlogPostModel> implements $FeedBlogPostModelCopyWith<$Res> { _$FeedBlogPostModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -115,11 +121,10 @@ class _$FeedBlogPostModelCopyWithImpl<$Res, $Val extends FeedBlogPostModel> } /// @nodoc -abstract class _$$FeedBlogPostModelImplCopyWith<$Res> - implements $FeedBlogPostModelCopyWith<$Res> { - factory _$$FeedBlogPostModelImplCopyWith(_$FeedBlogPostModelImpl value, - $Res Function(_$FeedBlogPostModelImpl) then) = +abstract class _$$FeedBlogPostModelImplCopyWith<$Res> implements $FeedBlogPostModelCopyWith<$Res> { + factory _$$FeedBlogPostModelImplCopyWith(_$FeedBlogPostModelImpl value, $Res Function(_$FeedBlogPostModelImpl) then) = __$$FeedBlogPostModelImplCopyWithImpl<$Res>; + @override @useResult $Res call( @@ -134,12 +139,9 @@ abstract class _$$FeedBlogPostModelImplCopyWith<$Res> } /// @nodoc -class __$$FeedBlogPostModelImplCopyWithImpl<$Res> - extends _$FeedBlogPostModelCopyWithImpl<$Res, _$FeedBlogPostModelImpl> +class __$$FeedBlogPostModelImplCopyWithImpl<$Res> extends _$FeedBlogPostModelCopyWithImpl<$Res, _$FeedBlogPostModelImpl> implements _$$FeedBlogPostModelImplCopyWith<$Res> { - __$$FeedBlogPostModelImplCopyWithImpl(_$FeedBlogPostModelImpl _value, - $Res Function(_$FeedBlogPostModelImpl) _then) - : super(_value, _then); + __$$FeedBlogPostModelImplCopyWithImpl(_$FeedBlogPostModelImpl _value, $Res Function(_$FeedBlogPostModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -203,8 +205,7 @@ class _$FeedBlogPostModelImpl implements _FeedBlogPostModel { @JsonKey(name: "updated_at") required this.updatedAt, required this.title}); - factory _$FeedBlogPostModelImpl.fromJson(Map json) => - _$$FeedBlogPostModelImplFromJson(json); + factory _$FeedBlogPostModelImpl.fromJson(Map json) => _$$FeedBlogPostModelImplFromJson(json); @override final int id; @@ -239,28 +240,21 @@ class _$FeedBlogPostModelImpl implements _FeedBlogPostModel { (identical(other.id, id) || other.id == id) && (identical(other.state, state) || other.state == state) && (identical(other.image, image) || other.image == image) && - (identical(other.description, description) || - other.description == description) && - (identical(other.youtubeUrl, youtubeUrl) || - other.youtubeUrl == youtubeUrl) && - (identical(other.createdAt, createdAt) || - other.createdAt == createdAt) && - (identical(other.updatedAt, updatedAt) || - other.updatedAt == updatedAt) && + (identical(other.description, description) || other.description == description) && + (identical(other.youtubeUrl, youtubeUrl) || other.youtubeUrl == youtubeUrl) && + (identical(other.createdAt, createdAt) || other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt) && (identical(other.title, title) || other.title == title)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, state, image, description, - youtubeUrl, createdAt, updatedAt, title); + int get hashCode => Object.hash(runtimeType, id, state, image, description, youtubeUrl, createdAt, updatedAt, title); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => - __$$FeedBlogPostModelImplCopyWithImpl<_$FeedBlogPostModelImpl>( - this, _$identity); + _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => __$$FeedBlogPostModelImplCopyWithImpl<_$FeedBlogPostModelImpl>(this, _$identity); @override Map toJson() { @@ -281,30 +275,36 @@ abstract class _FeedBlogPostModel implements FeedBlogPostModel { @JsonKey(name: "updated_at") required final DateTime updatedAt, required final String title}) = _$FeedBlogPostModelImpl; - factory _FeedBlogPostModel.fromJson(Map json) = - _$FeedBlogPostModelImpl.fromJson; + factory _FeedBlogPostModel.fromJson(Map json) = _$FeedBlogPostModelImpl.fromJson; @override int get id; + @override String get state; + @override String get image; + @override String get description; + @override @JsonKey(name: "youtube_url") String get youtubeUrl; + @override @JsonKey(name: "created_at") DateTime get createdAt; + @override @JsonKey(name: "updated_at") DateTime get updatedAt; + @override String get title; + @override @JsonKey(ignore: true) - _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/feed/models/feed_blog_post_model.g.dart b/lib/features/feed/models/feed_blog_post_model.g.dart index 93cc70f..e680864 100644 --- a/lib/features/feed/models/feed_blog_post_model.g.dart +++ b/lib/features/feed/models/feed_blog_post_model.g.dart @@ -6,9 +6,7 @@ part of 'feed_blog_post_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$FeedBlogPostModelImpl _$$FeedBlogPostModelImplFromJson( - Map json) => - _$FeedBlogPostModelImpl( +_$FeedBlogPostModelImpl _$$FeedBlogPostModelImplFromJson(Map json) => _$FeedBlogPostModelImpl( id: (json['id'] as num).toInt(), state: json['state'] as String, image: json['image'] as String, @@ -19,9 +17,7 @@ _$FeedBlogPostModelImpl _$$FeedBlogPostModelImplFromJson( title: json['title'] as String, ); -Map _$$FeedBlogPostModelImplToJson( - _$FeedBlogPostModelImpl instance) => - { +Map _$$FeedBlogPostModelImplToJson(_$FeedBlogPostModelImpl instance) => { 'id': instance.id, 'state': instance.state, 'image': instance.image, diff --git a/lib/features/feed/models/feed_blog_post_settings_model.dart b/lib/features/feed/models/feed_blog_post_settings_model.dart index 8296a8b..a74f2d6 100644 --- a/lib/features/feed/models/feed_blog_post_settings_model.dart +++ b/lib/features/feed/models/feed_blog_post_settings_model.dart @@ -2,6 +2,7 @@ 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 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 index 7fd8a12..7947d80 100644 --- a/lib/features/feed/models/feed_blog_post_settings_model.freezed.dart +++ b/lib/features/feed/models/feed_blog_post_settings_model.freezed.dart @@ -14,40 +14,37 @@ 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) { +FeedBlogPostSettingsModel _$FeedBlogPostSettingsModelFromJson(Map json) { return _FeedBlogPostSettingsModel.fromJson(json); } /// @nodoc mixin _$FeedBlogPostSettingsModel { @JsonKey(name: 'data') - List get feedBlogPostList => - throw _privateConstructorUsedError; + List get feedBlogPostList => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) - $FeedBlogPostSettingsModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $FeedBlogPostSettingsModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $FeedBlogPostSettingsModelCopyWith<$Res> { - factory $FeedBlogPostSettingsModelCopyWith(FeedBlogPostSettingsModel value, - $Res Function(FeedBlogPostSettingsModel) then) = + 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> { +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; @@ -66,25 +63,19 @@ class _$FeedBlogPostSettingsModelCopyWithImpl<$Res, } /// @nodoc -abstract class _$$FeedBlogPostSettingsModelImplCopyWith<$Res> - implements $FeedBlogPostSettingsModelCopyWith<$Res> { - factory _$$FeedBlogPostSettingsModelImplCopyWith( - _$FeedBlogPostSettingsModelImpl value, - $Res Function(_$FeedBlogPostSettingsModelImpl) then) = +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> +class __$$FeedBlogPostSettingsModelImplCopyWithImpl<$Res> extends _$FeedBlogPostSettingsModelCopyWithImpl<$Res, _$FeedBlogPostSettingsModelImpl> implements _$$FeedBlogPostSettingsModelImplCopyWith<$Res> { - __$$FeedBlogPostSettingsModelImplCopyWithImpl( - _$FeedBlogPostSettingsModelImpl _value, - $Res Function(_$FeedBlogPostSettingsModelImpl) _then) + __$$FeedBlogPostSettingsModelImplCopyWithImpl(_$FeedBlogPostSettingsModelImpl _value, $Res Function(_$FeedBlogPostSettingsModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -104,20 +95,17 @@ class __$$FeedBlogPostSettingsModelImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() class _$FeedBlogPostSettingsModelImpl implements _FeedBlogPostSettingsModel { - const _$FeedBlogPostSettingsModelImpl( - {@JsonKey(name: 'data') - required final List feedBlogPostList}) + const _$FeedBlogPostSettingsModelImpl({@JsonKey(name: 'data') required final List feedBlogPostList}) : _feedBlogPostList = feedBlogPostList; - factory _$FeedBlogPostSettingsModelImpl.fromJson(Map json) => - _$$FeedBlogPostSettingsModelImplFromJson(json); + factory _$FeedBlogPostSettingsModelImpl.fromJson(Map json) => _$$FeedBlogPostSettingsModelImplFromJson(json); final List _feedBlogPostList; + @override @JsonKey(name: 'data') List get feedBlogPostList { - if (_feedBlogPostList is EqualUnmodifiableListView) - return _feedBlogPostList; + if (_feedBlogPostList is EqualUnmodifiableListView) return _feedBlogPostList; // ignore: implicit_dynamic_type return EqualUnmodifiableListView(_feedBlogPostList); } @@ -132,21 +120,18 @@ class _$FeedBlogPostSettingsModelImpl implements _FeedBlogPostSettingsModel { return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedBlogPostSettingsModelImpl && - const DeepCollectionEquality() - .equals(other._feedBlogPostList, _feedBlogPostList)); + const DeepCollectionEquality().equals(other._feedBlogPostList, _feedBlogPostList)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash( - runtimeType, const DeepCollectionEquality().hash(_feedBlogPostList)); + 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); + _$$FeedBlogPostSettingsModelImplCopyWith<_$FeedBlogPostSettingsModelImpl> get copyWith => + __$$FeedBlogPostSettingsModelImplCopyWithImpl<_$FeedBlogPostSettingsModelImpl>(this, _$identity); @override Map toJson() { @@ -157,19 +142,15 @@ class _$FeedBlogPostSettingsModelImpl implements _FeedBlogPostSettingsModel { } abstract class _FeedBlogPostSettingsModel implements FeedBlogPostSettingsModel { - const factory _FeedBlogPostSettingsModel( - {@JsonKey(name: 'data') - required final List feedBlogPostList}) = - _$FeedBlogPostSettingsModelImpl; + const factory _FeedBlogPostSettingsModel({@JsonKey(name: 'data') required final List feedBlogPostList}) = _$FeedBlogPostSettingsModelImpl; - factory _FeedBlogPostSettingsModel.fromJson(Map json) = - _$FeedBlogPostSettingsModelImpl.fromJson; + factory _FeedBlogPostSettingsModel.fromJson(Map json) = _$FeedBlogPostSettingsModelImpl.fromJson; @override @JsonKey(name: 'data') List get feedBlogPostList; + @override @JsonKey(ignore: true) - _$$FeedBlogPostSettingsModelImplCopyWith<_$FeedBlogPostSettingsModelImpl> - get copyWith => throw _privateConstructorUsedError; + _$$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 index 3f48be1..90c6b0e 100644 --- a/lib/features/feed/models/feed_blog_post_settings_model.g.dart +++ b/lib/features/feed/models/feed_blog_post_settings_model.g.dart @@ -6,16 +6,14 @@ part of 'feed_blog_post_settings_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$FeedBlogPostSettingsModelImpl _$$FeedBlogPostSettingsModelImplFromJson( - Map json) => +_$FeedBlogPostSettingsModelImpl _$$FeedBlogPostSettingsModelImplFromJson(Map json) => _$FeedBlogPostSettingsModelImpl( feedBlogPostList: (json['data'] as List) .map((e) => FeedBlogPostModel.fromJson(e as Map)) .toList(), ); -Map _$$FeedBlogPostSettingsModelImplToJson( - _$FeedBlogPostSettingsModelImpl instance) => +Map _$$FeedBlogPostSettingsModelImplToJson(_$FeedBlogPostSettingsModelImpl instance) => { 'data': instance.feedBlogPostList, }; diff --git a/lib/features/feed/models/recipes_model.freezed.dart b/lib/features/feed/models/recipes_model.freezed.dart index cb55e50..9557c03 100644 --- a/lib/features/feed/models/recipes_model.freezed.dart +++ b/lib/features/feed/models/recipes_model.freezed.dart @@ -21,34 +21,48 @@ Recipes _$RecipesFromJson(Map json) { /// @nodoc mixin _$Recipes { int get id => throw _privateConstructorUsedError; + String get image => throw _privateConstructorUsedError; + String get state => throw _privateConstructorUsedError; + @JsonKey(name: "cooking_time") int get cookingTime => throw _privateConstructorUsedError; + List get ingredients => throw _privateConstructorUsedError; + String get description => throw _privateConstructorUsedError; + List get steps => throw _privateConstructorUsedError; + @JsonKey(name: "video_url") String get videoUrl => throw _privateConstructorUsedError; + @JsonKey(name: "created_at") DateTime get createdAt => throw _privateConstructorUsedError; + @JsonKey(name: "updated_at") DateTime get updatedAt => throw _privateConstructorUsedError; + String get title => throw _privateConstructorUsedError; + String get type => throw _privateConstructorUsedError; + String get slug => throw _privateConstructorUsedError; + @JsonKey(name: "comments_count") int get commentsCount => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) $RecipesCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $RecipesCopyWith<$Res> { - factory $RecipesCopyWith(Recipes value, $Res Function(Recipes) then) = - _$RecipesCopyWithImpl<$Res, Recipes>; + factory $RecipesCopyWith(Recipes value, $Res Function(Recipes) then) = _$RecipesCopyWithImpl<$Res, Recipes>; + @useResult $Res call( {int id, @@ -68,12 +82,12 @@ abstract class $RecipesCopyWith<$Res> { } /// @nodoc -class _$RecipesCopyWithImpl<$Res, $Val extends Recipes> - implements $RecipesCopyWith<$Res> { +class _$RecipesCopyWithImpl<$Res, $Val extends Recipes> implements $RecipesCopyWith<$Res> { _$RecipesCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -158,9 +172,8 @@ class _$RecipesCopyWithImpl<$Res, $Val extends Recipes> /// @nodoc abstract class _$$RecipesImplCopyWith<$Res> implements $RecipesCopyWith<$Res> { - factory _$$RecipesImplCopyWith( - _$RecipesImpl value, $Res Function(_$RecipesImpl) then) = - __$$RecipesImplCopyWithImpl<$Res>; + factory _$$RecipesImplCopyWith(_$RecipesImpl value, $Res Function(_$RecipesImpl) then) = __$$RecipesImplCopyWithImpl<$Res>; + @override @useResult $Res call( @@ -181,12 +194,8 @@ abstract class _$$RecipesImplCopyWith<$Res> implements $RecipesCopyWith<$Res> { } /// @nodoc -class __$$RecipesImplCopyWithImpl<$Res> - extends _$RecipesCopyWithImpl<$Res, _$RecipesImpl> - implements _$$RecipesImplCopyWith<$Res> { - __$$RecipesImplCopyWithImpl( - _$RecipesImpl _value, $Res Function(_$RecipesImpl) _then) - : super(_value, _then); +class __$$RecipesImplCopyWithImpl<$Res> extends _$RecipesCopyWithImpl<$Res, _$RecipesImpl> implements _$$RecipesImplCopyWith<$Res> { + __$$RecipesImplCopyWithImpl(_$RecipesImpl _value, $Res Function(_$RecipesImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -288,8 +297,7 @@ class _$RecipesImpl implements _Recipes { : _ingredients = ingredients, _steps = steps; - factory _$RecipesImpl.fromJson(Map json) => - _$$RecipesImplFromJson(json); + factory _$RecipesImpl.fromJson(Map json) => _$$RecipesImplFromJson(json); @override final int id; @@ -301,6 +309,7 @@ class _$RecipesImpl implements _Recipes { @JsonKey(name: "cooking_time") final int cookingTime; final List _ingredients; + @override List get ingredients { if (_ingredients is EqualUnmodifiableListView) return _ingredients; @@ -311,6 +320,7 @@ class _$RecipesImpl implements _Recipes { @override final String description; final List _steps; + @override List get steps { if (_steps is EqualUnmodifiableListView) return _steps; @@ -350,50 +360,28 @@ class _$RecipesImpl implements _Recipes { (identical(other.id, id) || other.id == id) && (identical(other.image, image) || other.image == image) && (identical(other.state, state) || other.state == state) && - (identical(other.cookingTime, cookingTime) || - other.cookingTime == cookingTime) && - const DeepCollectionEquality() - .equals(other._ingredients, _ingredients) && - (identical(other.description, description) || - other.description == description) && + (identical(other.cookingTime, cookingTime) || other.cookingTime == cookingTime) && + const DeepCollectionEquality().equals(other._ingredients, _ingredients) && + (identical(other.description, description) || other.description == description) && const DeepCollectionEquality().equals(other._steps, _steps) && - (identical(other.videoUrl, videoUrl) || - other.videoUrl == videoUrl) && - (identical(other.createdAt, createdAt) || - other.createdAt == createdAt) && - (identical(other.updatedAt, updatedAt) || - other.updatedAt == updatedAt) && + (identical(other.videoUrl, videoUrl) || other.videoUrl == videoUrl) && + (identical(other.createdAt, createdAt) || other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt) && (identical(other.title, title) || other.title == title) && (identical(other.type, type) || other.type == type) && (identical(other.slug, slug) || other.slug == slug) && - (identical(other.commentsCount, commentsCount) || - other.commentsCount == commentsCount)); + (identical(other.commentsCount, commentsCount) || other.commentsCount == commentsCount)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash( - runtimeType, - id, - image, - state, - cookingTime, - const DeepCollectionEquality().hash(_ingredients), - description, - const DeepCollectionEquality().hash(_steps), - videoUrl, - createdAt, - updatedAt, - title, - type, - slug, - commentsCount); + int get hashCode => Object.hash(runtimeType, id, image, state, cookingTime, const DeepCollectionEquality().hash(_ingredients), description, + const DeepCollectionEquality().hash(_steps), videoUrl, createdAt, updatedAt, title, type, slug, commentsCount); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$RecipesImplCopyWith<_$RecipesImpl> get copyWith => - __$$RecipesImplCopyWithImpl<_$RecipesImpl>(this, _$identity); + _$$RecipesImplCopyWith<_$RecipesImpl> get copyWith => __$$RecipesImplCopyWithImpl<_$RecipesImpl>(this, _$identity); @override Map toJson() { @@ -405,61 +393,73 @@ class _$RecipesImpl implements _Recipes { abstract class _Recipes implements Recipes { const factory _Recipes( - {required final int id, - required final String image, - required final String state, - @JsonKey(name: "cooking_time") required final int cookingTime, - required final List ingredients, - required final String description, - required final List steps, - @JsonKey(name: "video_url") required final String videoUrl, - @JsonKey(name: "created_at") required final DateTime createdAt, - @JsonKey(name: "updated_at") required final DateTime updatedAt, - required final String title, - required final String type, - required final String slug, - @JsonKey(name: "comments_count") required final int commentsCount}) = - _$RecipesImpl; + {required final int id, + required final String image, + required final String state, + @JsonKey(name: "cooking_time") required final int cookingTime, + required final List ingredients, + required final String description, + required final List steps, + @JsonKey(name: "video_url") required final String videoUrl, + @JsonKey(name: "created_at") required final DateTime createdAt, + @JsonKey(name: "updated_at") required final DateTime updatedAt, + required final String title, + required final String type, + required final String slug, + @JsonKey(name: "comments_count") required final int commentsCount}) = _$RecipesImpl; factory _Recipes.fromJson(Map json) = _$RecipesImpl.fromJson; @override int get id; + @override String get image; + @override String get state; + @override @JsonKey(name: "cooking_time") int get cookingTime; + @override List get ingredients; + @override String get description; + @override List get steps; + @override @JsonKey(name: "video_url") String get videoUrl; + @override @JsonKey(name: "created_at") DateTime get createdAt; + @override @JsonKey(name: "updated_at") DateTime get updatedAt; + @override String get title; + @override String get type; + @override String get slug; + @override @JsonKey(name: "comments_count") int get commentsCount; + @override @JsonKey(ignore: true) - _$$RecipesImplCopyWith<_$RecipesImpl> get copyWith => - throw _privateConstructorUsedError; + _$$RecipesImplCopyWith<_$RecipesImpl> get copyWith => throw _privateConstructorUsedError; } Ingredient _$IngredientFromJson(Map json) { @@ -469,31 +469,32 @@ Ingredient _$IngredientFromJson(Map json) { /// @nodoc mixin _$Ingredient { String get name => throw _privateConstructorUsedError; + String? get unit => throw _privateConstructorUsedError; + String get portion => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) - $IngredientCopyWith get copyWith => - throw _privateConstructorUsedError; + $IngredientCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $IngredientCopyWith<$Res> { - factory $IngredientCopyWith( - Ingredient value, $Res Function(Ingredient) then) = - _$IngredientCopyWithImpl<$Res, Ingredient>; + factory $IngredientCopyWith(Ingredient value, $Res Function(Ingredient) then) = _$IngredientCopyWithImpl<$Res, Ingredient>; + @useResult $Res call({String name, String? unit, String portion}); } /// @nodoc -class _$IngredientCopyWithImpl<$Res, $Val extends Ingredient> - implements $IngredientCopyWith<$Res> { +class _$IngredientCopyWithImpl<$Res, $Val extends Ingredient> implements $IngredientCopyWith<$Res> { _$IngredientCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -522,23 +523,17 @@ class _$IngredientCopyWithImpl<$Res, $Val extends Ingredient> } /// @nodoc -abstract class _$$IngredientImplCopyWith<$Res> - implements $IngredientCopyWith<$Res> { - factory _$$IngredientImplCopyWith( - _$IngredientImpl value, $Res Function(_$IngredientImpl) then) = - __$$IngredientImplCopyWithImpl<$Res>; +abstract class _$$IngredientImplCopyWith<$Res> implements $IngredientCopyWith<$Res> { + factory _$$IngredientImplCopyWith(_$IngredientImpl value, $Res Function(_$IngredientImpl) then) = __$$IngredientImplCopyWithImpl<$Res>; + @override @useResult $Res call({String name, String? unit, String portion}); } /// @nodoc -class __$$IngredientImplCopyWithImpl<$Res> - extends _$IngredientCopyWithImpl<$Res, _$IngredientImpl> - implements _$$IngredientImplCopyWith<$Res> { - __$$IngredientImplCopyWithImpl( - _$IngredientImpl _value, $Res Function(_$IngredientImpl) _then) - : super(_value, _then); +class __$$IngredientImplCopyWithImpl<$Res> extends _$IngredientCopyWithImpl<$Res, _$IngredientImpl> implements _$$IngredientImplCopyWith<$Res> { + __$$IngredientImplCopyWithImpl(_$IngredientImpl _value, $Res Function(_$IngredientImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -567,11 +562,9 @@ class __$$IngredientImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() class _$IngredientImpl implements _Ingredient { - const _$IngredientImpl( - {required this.name, this.unit, required this.portion}); + const _$IngredientImpl({required this.name, this.unit, required this.portion}); - factory _$IngredientImpl.fromJson(Map json) => - _$$IngredientImplFromJson(json); + factory _$IngredientImpl.fromJson(Map json) => _$$IngredientImplFromJson(json); @override final String name; @@ -602,8 +595,7 @@ class _$IngredientImpl implements _Ingredient { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$IngredientImplCopyWith<_$IngredientImpl> get copyWith => - __$$IngredientImplCopyWithImpl<_$IngredientImpl>(this, _$identity); + _$$IngredientImplCopyWith<_$IngredientImpl> get copyWith => __$$IngredientImplCopyWithImpl<_$IngredientImpl>(this, _$identity); @override Map toJson() { @@ -614,24 +606,22 @@ class _$IngredientImpl implements _Ingredient { } abstract class _Ingredient implements Ingredient { - const factory _Ingredient( - {required final String name, - final String? unit, - required final String portion}) = _$IngredientImpl; + const factory _Ingredient({required final String name, final String? unit, required final String portion}) = _$IngredientImpl; - factory _Ingredient.fromJson(Map json) = - _$IngredientImpl.fromJson; + factory _Ingredient.fromJson(Map json) = _$IngredientImpl.fromJson; @override String get name; + @override String? get unit; + @override String get portion; + @override @JsonKey(ignore: true) - _$$IngredientImplCopyWith<_$IngredientImpl> get copyWith => - throw _privateConstructorUsedError; + _$$IngredientImplCopyWith<_$IngredientImpl> get copyWith => throw _privateConstructorUsedError; } Step _$StepFromJson(Map json) { @@ -641,28 +631,30 @@ Step _$StepFromJson(Map json) { /// @nodoc mixin _$Step { String get image => throw _privateConstructorUsedError; + String get description => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) $StepCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $StepCopyWith<$Res> { - factory $StepCopyWith(Step value, $Res Function(Step) then) = - _$StepCopyWithImpl<$Res, Step>; + factory $StepCopyWith(Step value, $Res Function(Step) then) = _$StepCopyWithImpl<$Res, Step>; + @useResult $Res call({String image, String description}); } /// @nodoc -class _$StepCopyWithImpl<$Res, $Val extends Step> - implements $StepCopyWith<$Res> { +class _$StepCopyWithImpl<$Res, $Val extends Step> implements $StepCopyWith<$Res> { _$StepCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -687,20 +679,16 @@ class _$StepCopyWithImpl<$Res, $Val extends Step> /// @nodoc abstract class _$$StepImplCopyWith<$Res> implements $StepCopyWith<$Res> { - factory _$$StepImplCopyWith( - _$StepImpl value, $Res Function(_$StepImpl) then) = - __$$StepImplCopyWithImpl<$Res>; + factory _$$StepImplCopyWith(_$StepImpl value, $Res Function(_$StepImpl) then) = __$$StepImplCopyWithImpl<$Res>; + @override @useResult $Res call({String image, String description}); } /// @nodoc -class __$$StepImplCopyWithImpl<$Res> - extends _$StepCopyWithImpl<$Res, _$StepImpl> - implements _$$StepImplCopyWith<$Res> { - __$$StepImplCopyWithImpl(_$StepImpl _value, $Res Function(_$StepImpl) _then) - : super(_value, _then); +class __$$StepImplCopyWithImpl<$Res> extends _$StepCopyWithImpl<$Res, _$StepImpl> implements _$$StepImplCopyWith<$Res> { + __$$StepImplCopyWithImpl(_$StepImpl _value, $Res Function(_$StepImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -726,8 +714,7 @@ class __$$StepImplCopyWithImpl<$Res> class _$StepImpl implements _Step { const _$StepImpl({required this.image, required this.description}); - factory _$StepImpl.fromJson(Map json) => - _$$StepImplFromJson(json); + factory _$StepImpl.fromJson(Map json) => _$$StepImplFromJson(json); @override final String image; @@ -745,8 +732,7 @@ class _$StepImpl implements _Step { (other.runtimeType == runtimeType && other is _$StepImpl && (identical(other.image, image) || other.image == image) && - (identical(other.description, description) || - other.description == description)); + (identical(other.description, description) || other.description == description)); } @JsonKey(ignore: true) @@ -756,8 +742,7 @@ class _$StepImpl implements _Step { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$StepImplCopyWith<_$StepImpl> get copyWith => - __$$StepImplCopyWithImpl<_$StepImpl>(this, _$identity); + _$$StepImplCopyWith<_$StepImpl> get copyWith => __$$StepImplCopyWithImpl<_$StepImpl>(this, _$identity); @override Map toJson() { @@ -768,18 +753,17 @@ class _$StepImpl implements _Step { } abstract class _Step implements Step { - const factory _Step( - {required final String image, - required final String description}) = _$StepImpl; + const factory _Step({required final String image, required final String description}) = _$StepImpl; factory _Step.fromJson(Map json) = _$StepImpl.fromJson; @override String get image; + @override String get description; + @override @JsonKey(ignore: true) - _$$StepImplCopyWith<_$StepImpl> get copyWith => - throw _privateConstructorUsedError; + _$$StepImplCopyWith<_$StepImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/feed/models/recipes_model.g.dart b/lib/features/feed/models/recipes_model.g.dart index 74ecedf..e905d77 100644 --- a/lib/features/feed/models/recipes_model.g.dart +++ b/lib/features/feed/models/recipes_model.g.dart @@ -6,19 +6,14 @@ part of 'recipes_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$RecipesImpl _$$RecipesImplFromJson(Map json) => - _$RecipesImpl( +_$RecipesImpl _$$RecipesImplFromJson(Map json) => _$RecipesImpl( id: (json['id'] as num).toInt(), image: json['image'] as String, state: json['state'] as String, cookingTime: (json['cooking_time'] as num).toInt(), - ingredients: (json['ingredients'] as List) - .map((e) => Ingredient.fromJson(e as Map)) - .toList(), + ingredients: (json['ingredients'] as List).map((e) => Ingredient.fromJson(e as Map)).toList(), description: json['description'] as String, - steps: (json['steps'] as List) - .map((e) => Step.fromJson(e as Map)) - .toList(), + steps: (json['steps'] as List).map((e) => Step.fromJson(e as Map)).toList(), videoUrl: json['video_url'] as String, createdAt: DateTime.parse(json['created_at'] as String), updatedAt: DateTime.parse(json['updated_at'] as String), @@ -28,8 +23,7 @@ _$RecipesImpl _$$RecipesImplFromJson(Map json) => commentsCount: (json['comments_count'] as num).toInt(), ); -Map _$$RecipesImplToJson(_$RecipesImpl instance) => - { +Map _$$RecipesImplToJson(_$RecipesImpl instance) => { 'id': instance.id, 'image': instance.image, 'state': instance.state, @@ -46,15 +40,13 @@ Map _$$RecipesImplToJson(_$RecipesImpl instance) => 'comments_count': instance.commentsCount, }; -_$IngredientImpl _$$IngredientImplFromJson(Map json) => - _$IngredientImpl( +_$IngredientImpl _$$IngredientImplFromJson(Map json) => _$IngredientImpl( name: json['name'] as String, unit: json['unit'] as String?, portion: json['portion'] as String, ); -Map _$$IngredientImplToJson(_$IngredientImpl instance) => - { +Map _$$IngredientImplToJson(_$IngredientImpl instance) => { 'name': instance.name, 'unit': instance.unit, 'portion': instance.portion, @@ -65,8 +57,7 @@ _$StepImpl _$$StepImplFromJson(Map json) => _$StepImpl( description: json['description'] as String, ); -Map _$$StepImplToJson(_$StepImpl instance) => - { +Map _$$StepImplToJson(_$StepImpl instance) => { 'image': instance.image, 'description': instance.description, }; diff --git a/lib/features/feed/models/recipes_pagination_model.dart b/lib/features/feed/models/recipes_pagination_model.dart index fb27b88..316cf81 100644 --- a/lib/features/feed/models/recipes_pagination_model.dart +++ b/lib/features/feed/models/recipes_pagination_model.dart @@ -2,14 +2,12 @@ import 'package:eatvio_app/features/feed/models/recipes_model.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'recipes_pagination_model.freezed.dart'; - part 'recipes_pagination_model.g.dart'; @freezed class RecipesPagination with _$RecipesPagination { const factory RecipesPagination({ - @JsonKey(name: 'data') - required List recipesList, + @JsonKey(name: 'data') required List recipesList, @JsonKey(name: "current_page") required int currentPage, @JsonKey(name: "first_page_url") required String firstPageUrl, required int from, diff --git a/lib/features/feed/models/recipes_pagination_model.freezed.dart b/lib/features/feed/models/recipes_pagination_model.freezed.dart index 272422c..a79dcf0 100644 --- a/lib/features/feed/models/recipes_pagination_model.freezed.dart +++ b/lib/features/feed/models/recipes_pagination_model.freezed.dart @@ -22,36 +22,46 @@ RecipesPagination _$RecipesPaginationFromJson(Map json) { mixin _$RecipesPagination { @JsonKey(name: 'data') List get recipesList => throw _privateConstructorUsedError; + @JsonKey(name: "current_page") int get currentPage => throw _privateConstructorUsedError; + @JsonKey(name: "first_page_url") String get firstPageUrl => throw _privateConstructorUsedError; + int get from => throw _privateConstructorUsedError; + @JsonKey(name: "last_page") int get lastPage => throw _privateConstructorUsedError; + @JsonKey(name: "last_page_url") String get lastPageUrl => throw _privateConstructorUsedError; + @JsonKey(name: "next_page_url") String get nextPageUrl => throw _privateConstructorUsedError; + String get path => throw _privateConstructorUsedError; + @JsonKey(name: "per_page") int get perPage => throw _privateConstructorUsedError; + @JsonKey(name: "prev_page_url") dynamic get prevPageUrl => throw _privateConstructorUsedError; + int get to => throw _privateConstructorUsedError; + int get total => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) - $RecipesPaginationCopyWith get copyWith => - throw _privateConstructorUsedError; + $RecipesPaginationCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $RecipesPaginationCopyWith<$Res> { - factory $RecipesPaginationCopyWith( - RecipesPagination value, $Res Function(RecipesPagination) then) = - _$RecipesPaginationCopyWithImpl<$Res, RecipesPagination>; + factory $RecipesPaginationCopyWith(RecipesPagination value, $Res Function(RecipesPagination) then) = _$RecipesPaginationCopyWithImpl<$Res, RecipesPagination>; + @useResult $Res call( {@JsonKey(name: 'data') List recipesList, @@ -69,12 +79,12 @@ abstract class $RecipesPaginationCopyWith<$Res> { } /// @nodoc -class _$RecipesPaginationCopyWithImpl<$Res, $Val extends RecipesPagination> - implements $RecipesPaginationCopyWith<$Res> { +class _$RecipesPaginationCopyWithImpl<$Res, $Val extends RecipesPagination> implements $RecipesPaginationCopyWith<$Res> { _$RecipesPaginationCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -148,11 +158,10 @@ class _$RecipesPaginationCopyWithImpl<$Res, $Val extends RecipesPagination> } /// @nodoc -abstract class _$$RecipesPaginationImplCopyWith<$Res> - implements $RecipesPaginationCopyWith<$Res> { - factory _$$RecipesPaginationImplCopyWith(_$RecipesPaginationImpl value, - $Res Function(_$RecipesPaginationImpl) then) = +abstract class _$$RecipesPaginationImplCopyWith<$Res> implements $RecipesPaginationCopyWith<$Res> { + factory _$$RecipesPaginationImplCopyWith(_$RecipesPaginationImpl value, $Res Function(_$RecipesPaginationImpl) then) = __$$RecipesPaginationImplCopyWithImpl<$Res>; + @override @useResult $Res call( @@ -171,12 +180,9 @@ abstract class _$$RecipesPaginationImplCopyWith<$Res> } /// @nodoc -class __$$RecipesPaginationImplCopyWithImpl<$Res> - extends _$RecipesPaginationCopyWithImpl<$Res, _$RecipesPaginationImpl> +class __$$RecipesPaginationImplCopyWithImpl<$Res> extends _$RecipesPaginationCopyWithImpl<$Res, _$RecipesPaginationImpl> implements _$$RecipesPaginationImplCopyWith<$Res> { - __$$RecipesPaginationImplCopyWithImpl(_$RecipesPaginationImpl _value, - $Res Function(_$RecipesPaginationImpl) _then) - : super(_value, _then); + __$$RecipesPaginationImplCopyWithImpl(_$RecipesPaginationImpl _value, $Res Function(_$RecipesPaginationImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -265,10 +271,10 @@ class _$RecipesPaginationImpl implements _RecipesPagination { required this.total}) : _recipesList = recipesList; - factory _$RecipesPaginationImpl.fromJson(Map json) => - _$$RecipesPaginationImplFromJson(json); + factory _$RecipesPaginationImpl.fromJson(Map json) => _$$RecipesPaginationImplFromJson(json); final List _recipesList; + @override @JsonKey(name: 'data') List get recipesList { @@ -317,50 +323,29 @@ class _$RecipesPaginationImpl implements _RecipesPagination { return identical(this, other) || (other.runtimeType == runtimeType && other is _$RecipesPaginationImpl && - const DeepCollectionEquality() - .equals(other._recipesList, _recipesList) && - (identical(other.currentPage, currentPage) || - other.currentPage == currentPage) && - (identical(other.firstPageUrl, firstPageUrl) || - other.firstPageUrl == firstPageUrl) && + const DeepCollectionEquality().equals(other._recipesList, _recipesList) && + (identical(other.currentPage, currentPage) || other.currentPage == currentPage) && + (identical(other.firstPageUrl, firstPageUrl) || other.firstPageUrl == firstPageUrl) && (identical(other.from, from) || other.from == from) && - (identical(other.lastPage, lastPage) || - other.lastPage == lastPage) && - (identical(other.lastPageUrl, lastPageUrl) || - other.lastPageUrl == lastPageUrl) && - (identical(other.nextPageUrl, nextPageUrl) || - other.nextPageUrl == nextPageUrl) && + (identical(other.lastPage, lastPage) || other.lastPage == lastPage) && + (identical(other.lastPageUrl, lastPageUrl) || other.lastPageUrl == lastPageUrl) && + (identical(other.nextPageUrl, nextPageUrl) || other.nextPageUrl == nextPageUrl) && (identical(other.path, path) || other.path == path) && (identical(other.perPage, perPage) || other.perPage == perPage) && - const DeepCollectionEquality() - .equals(other.prevPageUrl, prevPageUrl) && + const DeepCollectionEquality().equals(other.prevPageUrl, prevPageUrl) && (identical(other.to, to) || other.to == to) && (identical(other.total, total) || other.total == total)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash( - runtimeType, - const DeepCollectionEquality().hash(_recipesList), - currentPage, - firstPageUrl, - from, - lastPage, - lastPageUrl, - nextPageUrl, - path, - perPage, - const DeepCollectionEquality().hash(prevPageUrl), - to, - total); + int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_recipesList), currentPage, firstPageUrl, from, lastPage, lastPageUrl, + nextPageUrl, path, perPage, const DeepCollectionEquality().hash(prevPageUrl), to, total); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$RecipesPaginationImplCopyWith<_$RecipesPaginationImpl> get copyWith => - __$$RecipesPaginationImplCopyWithImpl<_$RecipesPaginationImpl>( - this, _$identity); + _$$RecipesPaginationImplCopyWith<_$RecipesPaginationImpl> get copyWith => __$$RecipesPaginationImplCopyWithImpl<_$RecipesPaginationImpl>(this, _$identity); @override Map toJson() { @@ -385,43 +370,53 @@ abstract class _RecipesPagination implements RecipesPagination { required final int to, required final int total}) = _$RecipesPaginationImpl; - factory _RecipesPagination.fromJson(Map json) = - _$RecipesPaginationImpl.fromJson; + factory _RecipesPagination.fromJson(Map json) = _$RecipesPaginationImpl.fromJson; @override @JsonKey(name: 'data') List get recipesList; + @override @JsonKey(name: "current_page") int get currentPage; + @override @JsonKey(name: "first_page_url") String get firstPageUrl; + @override int get from; + @override @JsonKey(name: "last_page") int get lastPage; + @override @JsonKey(name: "last_page_url") String get lastPageUrl; + @override @JsonKey(name: "next_page_url") String get nextPageUrl; + @override String get path; + @override @JsonKey(name: "per_page") int get perPage; + @override @JsonKey(name: "prev_page_url") dynamic get prevPageUrl; + @override int get to; + @override int get total; + @override @JsonKey(ignore: true) - _$$RecipesPaginationImplCopyWith<_$RecipesPaginationImpl> get copyWith => - throw _privateConstructorUsedError; + _$$RecipesPaginationImplCopyWith<_$RecipesPaginationImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/feed/models/recipes_pagination_model.g.dart b/lib/features/feed/models/recipes_pagination_model.g.dart index d1e483f..fd36d17 100644 --- a/lib/features/feed/models/recipes_pagination_model.g.dart +++ b/lib/features/feed/models/recipes_pagination_model.g.dart @@ -6,12 +6,8 @@ part of 'recipes_pagination_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$RecipesPaginationImpl _$$RecipesPaginationImplFromJson( - Map json) => - _$RecipesPaginationImpl( - recipesList: (json['data'] as List) - .map((e) => Recipes.fromJson(e as Map)) - .toList(), +_$RecipesPaginationImpl _$$RecipesPaginationImplFromJson(Map json) => _$RecipesPaginationImpl( + recipesList: (json['data'] as List).map((e) => Recipes.fromJson(e as Map)).toList(), currentPage: (json['current_page'] as num).toInt(), firstPageUrl: json['first_page_url'] as String, from: (json['from'] as num).toInt(), @@ -25,9 +21,7 @@ _$RecipesPaginationImpl _$$RecipesPaginationImplFromJson( total: (json['total'] as num).toInt(), ); -Map _$$RecipesPaginationImplToJson( - _$RecipesPaginationImpl instance) => - { +Map _$$RecipesPaginationImplToJson(_$RecipesPaginationImpl instance) => { 'data': instance.recipesList, 'current_page': instance.currentPage, 'first_page_url': instance.firstPageUrl, diff --git a/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart b/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart index ab3385f..1bb34c3 100644 --- a/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart +++ b/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart @@ -24,6 +24,7 @@ mixin _$FeedState { required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; + @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { @@ -70,35 +71,28 @@ mixin _$FeedState { /// @nodoc abstract class $FeedStateCopyWith<$Res> { - factory $FeedStateCopyWith(FeedState value, $Res Function(FeedState) then) = - _$FeedStateCopyWithImpl<$Res, FeedState>; + factory $FeedStateCopyWith(FeedState value, $Res Function(FeedState) then) = _$FeedStateCopyWithImpl<$Res, FeedState>; } /// @nodoc -class _$FeedStateCopyWithImpl<$Res, $Val extends FeedState> - implements $FeedStateCopyWith<$Res> { +class _$FeedStateCopyWithImpl<$Res, $Val extends FeedState> implements $FeedStateCopyWith<$Res> { _$FeedStateCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; } /// @nodoc abstract class _$$FeedStateImplCopyWith<$Res> { - factory _$$FeedStateImplCopyWith( - _$FeedStateImpl value, $Res Function(_$FeedStateImpl) then) = - __$$FeedStateImplCopyWithImpl<$Res>; + factory _$$FeedStateImplCopyWith(_$FeedStateImpl value, $Res Function(_$FeedStateImpl) then) = __$$FeedStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$FeedStateImplCopyWithImpl<$Res> - extends _$FeedStateCopyWithImpl<$Res, _$FeedStateImpl> - implements _$$FeedStateImplCopyWith<$Res> { - __$$FeedStateImplCopyWithImpl( - _$FeedStateImpl _value, $Res Function(_$FeedStateImpl) _then) - : super(_value, _then); +class __$$FeedStateImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateImpl> implements _$$FeedStateImplCopyWith<$Res> { + __$$FeedStateImplCopyWithImpl(_$FeedStateImpl _value, $Res Function(_$FeedStateImpl) _then) : super(_value, _then); } /// @nodoc @@ -113,8 +107,7 @@ class _$FeedStateImpl implements _FeedState { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is _$FeedStateImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateImpl); } @override @@ -201,18 +194,14 @@ abstract class _FeedState implements FeedState { /// @nodoc abstract class _$$FeedStateLoadingImplCopyWith<$Res> { - factory _$$FeedStateLoadingImplCopyWith(_$FeedStateLoadingImpl value, - $Res Function(_$FeedStateLoadingImpl) then) = + factory _$$FeedStateLoadingImplCopyWith(_$FeedStateLoadingImpl value, $Res Function(_$FeedStateLoadingImpl) then) = __$$FeedStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$FeedStateLoadingImplCopyWithImpl<$Res> - extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadingImpl> +class __$$FeedStateLoadingImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadingImpl> implements _$$FeedStateLoadingImplCopyWith<$Res> { - __$$FeedStateLoadingImplCopyWithImpl(_$FeedStateLoadingImpl _value, - $Res Function(_$FeedStateLoadingImpl) _then) - : super(_value, _then); + __$$FeedStateLoadingImplCopyWithImpl(_$FeedStateLoadingImpl _value, $Res Function(_$FeedStateLoadingImpl) _then) : super(_value, _then); } /// @nodoc @@ -227,8 +216,7 @@ class _$FeedStateLoadingImpl implements FeedStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is _$FeedStateLoadingImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateLoadingImpl); } @override @@ -315,20 +303,15 @@ abstract class FeedStateLoading implements FeedState { /// @nodoc abstract class _$$FeedStateLoadedImplCopyWith<$Res> { - factory _$$FeedStateLoadedImplCopyWith(_$FeedStateLoadedImpl value, - $Res Function(_$FeedStateLoadedImpl) then) = - __$$FeedStateLoadedImplCopyWithImpl<$Res>; + factory _$$FeedStateLoadedImplCopyWith(_$FeedStateLoadedImpl value, $Res Function(_$FeedStateLoadedImpl) then) = __$$FeedStateLoadedImplCopyWithImpl<$Res>; + @useResult $Res call({List feedBlogPostList}); } /// @nodoc -class __$$FeedStateLoadedImplCopyWithImpl<$Res> - extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadedImpl> - implements _$$FeedStateLoadedImplCopyWith<$Res> { - __$$FeedStateLoadedImplCopyWithImpl( - _$FeedStateLoadedImpl _value, $Res Function(_$FeedStateLoadedImpl) _then) - : super(_value, _then); +class __$$FeedStateLoadedImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadedImpl> implements _$$FeedStateLoadedImplCopyWith<$Res> { + __$$FeedStateLoadedImplCopyWithImpl(_$FeedStateLoadedImpl _value, $Res Function(_$FeedStateLoadedImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -347,15 +330,13 @@ class __$$FeedStateLoadedImplCopyWithImpl<$Res> /// @nodoc class _$FeedStateLoadedImpl implements FeedStateLoaded { - const _$FeedStateLoadedImpl( - {required final List feedBlogPostList}) - : _feedBlogPostList = feedBlogPostList; + const _$FeedStateLoadedImpl({required final List feedBlogPostList}) : _feedBlogPostList = feedBlogPostList; final List _feedBlogPostList; + @override List get feedBlogPostList { - if (_feedBlogPostList is EqualUnmodifiableListView) - return _feedBlogPostList; + if (_feedBlogPostList is EqualUnmodifiableListView) return _feedBlogPostList; // ignore: implicit_dynamic_type return EqualUnmodifiableListView(_feedBlogPostList); } @@ -370,20 +351,16 @@ class _$FeedStateLoadedImpl implements FeedStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateLoadedImpl && - const DeepCollectionEquality() - .equals(other._feedBlogPostList, _feedBlogPostList)); + const DeepCollectionEquality().equals(other._feedBlogPostList, _feedBlogPostList)); } @override - int get hashCode => Object.hash( - runtimeType, const DeepCollectionEquality().hash(_feedBlogPostList)); + int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_feedBlogPostList)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => - __$$FeedStateLoadedImplCopyWithImpl<_$FeedStateLoadedImpl>( - this, _$identity); + _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => __$$FeedStateLoadedImplCopyWithImpl<_$FeedStateLoadedImpl>(this, _$identity); @override @optionalTypeArgs @@ -461,32 +438,25 @@ class _$FeedStateLoadedImpl implements FeedStateLoaded { } abstract class FeedStateLoaded implements FeedState { - const factory FeedStateLoaded( - {required final List feedBlogPostList}) = - _$FeedStateLoadedImpl; + const factory FeedStateLoaded({required final List feedBlogPostList}) = _$FeedStateLoadedImpl; List get feedBlogPostList; + @JsonKey(ignore: true) - _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => - throw _privateConstructorUsedError; + _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$FeedStateErrorImplCopyWith<$Res> { - factory _$$FeedStateErrorImplCopyWith(_$FeedStateErrorImpl value, - $Res Function(_$FeedStateErrorImpl) then) = - __$$FeedStateErrorImplCopyWithImpl<$Res>; + factory _$$FeedStateErrorImplCopyWith(_$FeedStateErrorImpl value, $Res Function(_$FeedStateErrorImpl) then) = __$$FeedStateErrorImplCopyWithImpl<$Res>; + @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$FeedStateErrorImplCopyWithImpl<$Res> - extends _$FeedStateCopyWithImpl<$Res, _$FeedStateErrorImpl> - implements _$$FeedStateErrorImplCopyWith<$Res> { - __$$FeedStateErrorImplCopyWithImpl( - _$FeedStateErrorImpl _value, $Res Function(_$FeedStateErrorImpl) _then) - : super(_value, _then); +class __$$FeedStateErrorImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateErrorImpl> implements _$$FeedStateErrorImplCopyWith<$Res> { + __$$FeedStateErrorImplCopyWithImpl(_$FeedStateErrorImpl _value, $Res Function(_$FeedStateErrorImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -520,8 +490,7 @@ class _$FeedStateErrorImpl implements FeedStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateErrorImpl && - (identical(other.errorMessage, errorMessage) || - other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); } @override @@ -530,9 +499,7 @@ class _$FeedStateErrorImpl implements FeedStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => - __$$FeedStateErrorImplCopyWithImpl<_$FeedStateErrorImpl>( - this, _$identity); + _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => __$$FeedStateErrorImplCopyWithImpl<_$FeedStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -610,11 +577,10 @@ class _$FeedStateErrorImpl implements FeedStateError { } abstract class FeedStateError implements FeedState { - const factory FeedStateError({required final String errorMessage}) = - _$FeedStateErrorImpl; + const factory FeedStateError({required final String errorMessage}) = _$FeedStateErrorImpl; String get errorMessage; + @JsonKey(ignore: true) - _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => - throw _privateConstructorUsedError; + _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart b/lib/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart index 8d8aeb2..8cd8a52 100644 --- a/lib/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart +++ b/lib/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart @@ -15,4 +15,4 @@ class RecipesCubit extends Cubit { emit(RecipesState.error(errorMessage: e.toString())); } } -} \ No newline at end of file +} diff --git a/lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.freezed.dart b/lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.freezed.dart index e8aa88e..928221e 100644 --- a/lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.freezed.dart +++ b/lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.freezed.dart @@ -24,6 +24,7 @@ mixin _$RecipesState { required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; + @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { @@ -70,36 +71,28 @@ mixin _$RecipesState { /// @nodoc abstract class $RecipesStateCopyWith<$Res> { - factory $RecipesStateCopyWith( - RecipesState value, $Res Function(RecipesState) then) = - _$RecipesStateCopyWithImpl<$Res, RecipesState>; + factory $RecipesStateCopyWith(RecipesState value, $Res Function(RecipesState) then) = _$RecipesStateCopyWithImpl<$Res, RecipesState>; } /// @nodoc -class _$RecipesStateCopyWithImpl<$Res, $Val extends RecipesState> - implements $RecipesStateCopyWith<$Res> { +class _$RecipesStateCopyWithImpl<$Res, $Val extends RecipesState> implements $RecipesStateCopyWith<$Res> { _$RecipesStateCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; } /// @nodoc abstract class _$$RecipesStateImplCopyWith<$Res> { - factory _$$RecipesStateImplCopyWith( - _$RecipesStateImpl value, $Res Function(_$RecipesStateImpl) then) = - __$$RecipesStateImplCopyWithImpl<$Res>; + factory _$$RecipesStateImplCopyWith(_$RecipesStateImpl value, $Res Function(_$RecipesStateImpl) then) = __$$RecipesStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$RecipesStateImplCopyWithImpl<$Res> - extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateImpl> - implements _$$RecipesStateImplCopyWith<$Res> { - __$$RecipesStateImplCopyWithImpl( - _$RecipesStateImpl _value, $Res Function(_$RecipesStateImpl) _then) - : super(_value, _then); +class __$$RecipesStateImplCopyWithImpl<$Res> extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateImpl> implements _$$RecipesStateImplCopyWith<$Res> { + __$$RecipesStateImplCopyWithImpl(_$RecipesStateImpl _value, $Res Function(_$RecipesStateImpl) _then) : super(_value, _then); } /// @nodoc @@ -114,8 +107,7 @@ class _$RecipesStateImpl implements _RecipesState { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is _$RecipesStateImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$RecipesStateImpl); } @override @@ -202,18 +194,14 @@ abstract class _RecipesState implements RecipesState { /// @nodoc abstract class _$$RecipesStateLoadingImplCopyWith<$Res> { - factory _$$RecipesStateLoadingImplCopyWith(_$RecipesStateLoadingImpl value, - $Res Function(_$RecipesStateLoadingImpl) then) = + factory _$$RecipesStateLoadingImplCopyWith(_$RecipesStateLoadingImpl value, $Res Function(_$RecipesStateLoadingImpl) then) = __$$RecipesStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$RecipesStateLoadingImplCopyWithImpl<$Res> - extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateLoadingImpl> +class __$$RecipesStateLoadingImplCopyWithImpl<$Res> extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateLoadingImpl> implements _$$RecipesStateLoadingImplCopyWith<$Res> { - __$$RecipesStateLoadingImplCopyWithImpl(_$RecipesStateLoadingImpl _value, - $Res Function(_$RecipesStateLoadingImpl) _then) - : super(_value, _then); + __$$RecipesStateLoadingImplCopyWithImpl(_$RecipesStateLoadingImpl _value, $Res Function(_$RecipesStateLoadingImpl) _then) : super(_value, _then); } /// @nodoc @@ -228,9 +216,7 @@ class _$RecipesStateLoadingImpl implements RecipesStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$RecipesStateLoadingImpl); + return identical(this, other) || (other.runtimeType == runtimeType && other is _$RecipesStateLoadingImpl); } @override @@ -317,20 +303,17 @@ abstract class RecipesStateLoading implements RecipesState { /// @nodoc abstract class _$$RecipesStateLoadedImplCopyWith<$Res> { - factory _$$RecipesStateLoadedImplCopyWith(_$RecipesStateLoadedImpl value, - $Res Function(_$RecipesStateLoadedImpl) then) = + factory _$$RecipesStateLoadedImplCopyWith(_$RecipesStateLoadedImpl value, $Res Function(_$RecipesStateLoadedImpl) then) = __$$RecipesStateLoadedImplCopyWithImpl<$Res>; + @useResult $Res call({List recipesList}); } /// @nodoc -class __$$RecipesStateLoadedImplCopyWithImpl<$Res> - extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateLoadedImpl> +class __$$RecipesStateLoadedImplCopyWithImpl<$Res> extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateLoadedImpl> implements _$$RecipesStateLoadedImplCopyWith<$Res> { - __$$RecipesStateLoadedImplCopyWithImpl(_$RecipesStateLoadedImpl _value, - $Res Function(_$RecipesStateLoadedImpl) _then) - : super(_value, _then); + __$$RecipesStateLoadedImplCopyWithImpl(_$RecipesStateLoadedImpl _value, $Res Function(_$RecipesStateLoadedImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -349,10 +332,10 @@ class __$$RecipesStateLoadedImplCopyWithImpl<$Res> /// @nodoc class _$RecipesStateLoadedImpl implements RecipesStateLoaded { - const _$RecipesStateLoadedImpl({required final List recipesList}) - : _recipesList = recipesList; + const _$RecipesStateLoadedImpl({required final List recipesList}) : _recipesList = recipesList; final List _recipesList; + @override List get recipesList { if (_recipesList is EqualUnmodifiableListView) return _recipesList; @@ -368,22 +351,17 @@ class _$RecipesStateLoadedImpl implements RecipesStateLoaded { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$RecipesStateLoadedImpl && - const DeepCollectionEquality() - .equals(other._recipesList, _recipesList)); + (other.runtimeType == runtimeType && other is _$RecipesStateLoadedImpl && const DeepCollectionEquality().equals(other._recipesList, _recipesList)); } @override - int get hashCode => Object.hash( - runtimeType, const DeepCollectionEquality().hash(_recipesList)); + int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_recipesList)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$RecipesStateLoadedImplCopyWith<_$RecipesStateLoadedImpl> get copyWith => - __$$RecipesStateLoadedImplCopyWithImpl<_$RecipesStateLoadedImpl>( - this, _$identity); + __$$RecipesStateLoadedImplCopyWithImpl<_$RecipesStateLoadedImpl>(this, _$identity); @override @optionalTypeArgs @@ -461,31 +439,27 @@ class _$RecipesStateLoadedImpl implements RecipesStateLoaded { } abstract class RecipesStateLoaded implements RecipesState { - const factory RecipesStateLoaded({required final List recipesList}) = - _$RecipesStateLoadedImpl; + const factory RecipesStateLoaded({required final List recipesList}) = _$RecipesStateLoadedImpl; List get recipesList; + @JsonKey(ignore: true) - _$$RecipesStateLoadedImplCopyWith<_$RecipesStateLoadedImpl> get copyWith => - throw _privateConstructorUsedError; + _$$RecipesStateLoadedImplCopyWith<_$RecipesStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$RecipesStateErrorImplCopyWith<$Res> { - factory _$$RecipesStateErrorImplCopyWith(_$RecipesStateErrorImpl value, - $Res Function(_$RecipesStateErrorImpl) then) = + factory _$$RecipesStateErrorImplCopyWith(_$RecipesStateErrorImpl value, $Res Function(_$RecipesStateErrorImpl) then) = __$$RecipesStateErrorImplCopyWithImpl<$Res>; + @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$RecipesStateErrorImplCopyWithImpl<$Res> - extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateErrorImpl> +class __$$RecipesStateErrorImplCopyWithImpl<$Res> extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateErrorImpl> implements _$$RecipesStateErrorImplCopyWith<$Res> { - __$$RecipesStateErrorImplCopyWithImpl(_$RecipesStateErrorImpl _value, - $Res Function(_$RecipesStateErrorImpl) _then) - : super(_value, _then); + __$$RecipesStateErrorImplCopyWithImpl(_$RecipesStateErrorImpl _value, $Res Function(_$RecipesStateErrorImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -519,8 +493,7 @@ class _$RecipesStateErrorImpl implements RecipesStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$RecipesStateErrorImpl && - (identical(other.errorMessage, errorMessage) || - other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); } @override @@ -529,9 +502,7 @@ class _$RecipesStateErrorImpl implements RecipesStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$RecipesStateErrorImplCopyWith<_$RecipesStateErrorImpl> get copyWith => - __$$RecipesStateErrorImplCopyWithImpl<_$RecipesStateErrorImpl>( - this, _$identity); + _$$RecipesStateErrorImplCopyWith<_$RecipesStateErrorImpl> get copyWith => __$$RecipesStateErrorImplCopyWithImpl<_$RecipesStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -609,11 +580,10 @@ class _$RecipesStateErrorImpl implements RecipesStateError { } abstract class RecipesStateError implements RecipesState { - const factory RecipesStateError({required final String errorMessage}) = - _$RecipesStateErrorImpl; + const factory RecipesStateError({required final String errorMessage}) = _$RecipesStateErrorImpl; String get errorMessage; + @JsonKey(ignore: true) - _$$RecipesStateErrorImplCopyWith<_$RecipesStateErrorImpl> get copyWith => - throw _privateConstructorUsedError; + _$$RecipesStateErrorImplCopyWith<_$RecipesStateErrorImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/feed/presentation/widgets/blog_post_widget.dart b/lib/features/feed/presentation/widgets/blog_post_widget.dart index 1139fe0..ee629c3 100644 --- a/lib/features/feed/presentation/widgets/blog_post_widget.dart +++ b/lib/features/feed/presentation/widgets/blog_post_widget.dart @@ -20,10 +20,11 @@ class _BlogPostWidgetState extends State { Widget build(BuildContext context) { return InkWell( borderRadius: BorderRadius.circular(12), - onTap: () => GoRouter.of(context).pushNamed( - 'blogPostScreen', - extra: widget.feedBlogPostModel.id.toString(), - ), + onTap: () => + GoRouter.of(context).pushNamed( + 'blogPostScreen', + extra: widget.feedBlogPostModel.id.toString(), + ), child: Ink( decoration: BoxDecoration( borderRadius: BorderRadius.circular(12), diff --git a/lib/features/feed/presentation/widgets/recipes_widget.dart b/lib/features/feed/presentation/widgets/recipes_widget.dart index 233e45b..751612f 100644 --- a/lib/features/feed/presentation/widgets/recipes_widget.dart +++ b/lib/features/feed/presentation/widgets/recipes_widget.dart @@ -4,6 +4,7 @@ import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; import 'package:eatvio_app/features/feed/models/recipes_model.dart'; import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; class RecipesWidget extends StatefulWidget { final Recipes recipes; @@ -19,7 +20,7 @@ class _RecipesWidgetState extends State { Widget build(BuildContext context) { return InkWell( borderRadius: BorderRadius.circular(12), - onTap: () {}, + onTap: () => GoRouter.of(context).pushNamed('aboutRecipesScreen', extra: widget.recipes), child: Ink( decoration: BoxDecoration( borderRadius: BorderRadius.circular(12), @@ -30,7 +31,6 @@ class _RecipesWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Stack( - alignment: Alignment.bottomLeft, children: [ ClipRRect( borderRadius: BorderRadius.vertical(top: Radius.circular(12)), @@ -52,64 +52,78 @@ class _RecipesWidgetState extends State { ), ), ), - Padding( - padding: const EdgeInsets.all(8.0), - child: Row( + Positioned( + left: 8, + bottom: 8, + child: Wrap( + runSpacing: 8, children: [ - Container( - padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4), - decoration: BoxDecoration( - color: Colors.white54, - borderRadius: BorderRadius.circular(16), - ), - child: Row( - children: [ - Icon( - Icons.visibility_rounded, - size: 20, - color: Colors.black, - ), - SizedBox(width: 4), - Text( - '0', - style: TextStyle( - fontSize: 14, - color: Colors.black, - fontWeight: FontWeight.w400, - ), - ), - ], - ), - ), + _iconButton(Icons.fastfood, '139.9 ккал'), SizedBox(width: 8), - Container( - padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4), - decoration: BoxDecoration( - color: Colors.white54, - borderRadius: BorderRadius.circular(16), - ), - child: Row( - children: [ - Icon( - Icons.favorite_border_rounded, - size: 20, - color: Colors.black, - ), - SizedBox(width: 4), - Text( - '0', - style: TextStyle( - fontSize: 14, - color: Colors.black, - fontWeight: FontWeight.w400, - ), - ), - ], - ), - ), + _iconButton(Icons.timer_rounded, widget.recipes.cookingTime.toString() + ' минут'), + SizedBox(width: 8), + _iconButton(Icons.fast_forward_rounded, widget.recipes.steps.length.toString() + ' этапов'), ], ), ), + Positioned( + left: 8, + top: 8, + child: Container( + padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.8), + borderRadius: BorderRadius.circular(16), + ), + child: Row( + children: [ + Icon( + Icons.favorite_rounded, + size: 16, + color: Colors.black, + ), + SizedBox(width: 4), + Text( + '0', + style: TextStyle( + fontSize: 12, + color: Colors.black, + fontWeight: FontWeight.w400, + ), + ), + ], + ), + ), + ), + Positioned( + right: 8, + top: 8, + child: Container( + padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.8), + borderRadius: BorderRadius.circular(16), + ), + child: Row( + children: [ + Icon( + Icons.visibility_rounded, + size: 16, + color: Colors.black, + ), + SizedBox(width: 4), + Text( + '0', + style: TextStyle( + fontSize: 12, + color: Colors.black, + fontWeight: FontWeight.w400, + ), + ), + ], + ), + ), + ), ], ), SizedBox(height: 12), @@ -134,20 +148,6 @@ class _RecipesWidgetState extends State { ), ), SizedBox(height: 12), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 12), - child: Wrap( - runSpacing: 8, - children: [ - _iconButton(Icons.fastfood, '139.9 ккал'), - SizedBox(width: 8), - _iconButton(Icons.timer_rounded, widget.recipes.cookingTime.toString() + ' минут'), - SizedBox(width: 8), - _iconButton(Icons.fast_forward_rounded, widget.recipes.steps.length.toString() + ' этапов'), - ], - ), - ), - SizedBox(height: 8), ], ), ), @@ -155,10 +155,10 @@ class _RecipesWidgetState extends State { } _iconButton(IconData icon, [String? text]) { - return Ink( + return Container( padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4), decoration: BoxDecoration( - color: appTheme.gray100, + color: Colors.white.withOpacity(0.8), borderRadius: BorderRadius.circular(16), ), height: 32, @@ -167,16 +167,16 @@ class _RecipesWidgetState extends State { children: [ Icon( icon, - size: 20, - color: appTheme.gray600, + size: 16, + color: Colors.black, ), if (text != null) SizedBox(width: 8), if (text != null) Text( text, style: TextStyle( - fontSize: 14, - color: appTheme.gray600, + fontSize: 12, + color: Colors.black, fontWeight: FontWeight.w500, ), ), diff --git a/lib/features/feed/services/feed_service.g.dart b/lib/features/feed/services/feed_service.g.dart index fbccc93..a8d9ec0 100644 --- a/lib/features/feed/services/feed_service.g.dart +++ b/lib/features/feed/services/feed_service.g.dart @@ -24,23 +24,22 @@ class _FeedService implements FeedService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>( - _setStreamType(Options( + final _result = await _dio.fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/blogPosts/index', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/blogPosts/index', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = FeedBlogPostSettingsModel.fromJson(_result.data!); return _value; } @@ -51,31 +50,28 @@ class _FeedService implements FeedService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType(Options( + final _result = await _dio.fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/recipes/index', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/recipes/index', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = RecipesPagination.fromJson(_result.data!); return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && - !(requestOptions.responseType == ResponseType.bytes || - requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { diff --git a/lib/features/recipes/presentation/pages/about_recipes_screen.dart b/lib/features/recipes/presentation/pages/about_recipes_screen.dart index e69de29..aa83ef2 100644 --- a/lib/features/recipes/presentation/pages/about_recipes_screen.dart +++ b/lib/features/recipes/presentation/pages/about_recipes_screen.dart @@ -0,0 +1,49 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:eatvio_app/core/app_export.dart'; +import 'package:eatvio_app/features/feed/models/recipes_model.dart' as step; +import 'package:eatvio_app/features/feed/models/recipes_model.dart'; +import 'package:flutter/material.dart'; + +class AboutRecipesScreen extends StatelessWidget { + final Recipes recipes; + + const AboutRecipesScreen({super.key, required this.recipes}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(), + body: SingleChildScrollView( + padding: EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(recipes.title), + Row( + children: [ + Text(recipes.cookingTime.toString() + ' минут'), + SizedBox(width: 16), + Text(recipes.steps.length.toString() + ' этапов'), + ], + ), + Text(recipes.videoUrl), + CachedNetworkImage(imageUrl: baseUrl + '/storage/' + recipes.image), + Text(recipes.ingredients.toString()), + Text('Пошаговый рецепт'), + for (int i = 0; i < recipes.steps.length; i++) ...[_step(recipes.steps[i])], + ], + ), + ), + ); + } + + _step(step.Step step) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(step.description), + if (step.image.length > 1) CachedNetworkImage(imageUrl: baseUrl + '/storage/' + step.image), + ], + ); + } +} diff --git a/lib/features/registration/models/location_model.freezed.dart b/lib/features/registration/models/location_model.freezed.dart index f640ca2..852b5f2 100644 --- a/lib/features/registration/models/location_model.freezed.dart +++ b/lib/features/registration/models/location_model.freezed.dart @@ -21,33 +21,31 @@ LocationModel _$LocationModelFromJson(Map json) { /// @nodoc mixin _$LocationModel { List get locations => throw _privateConstructorUsedError; + @JsonKey(name: 'response_body') String get responseBody => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) - $LocationModelCopyWith get copyWith => - throw _privateConstructorUsedError; + $LocationModelCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $LocationModelCopyWith<$Res> { - factory $LocationModelCopyWith( - LocationModel value, $Res Function(LocationModel) then) = - _$LocationModelCopyWithImpl<$Res, LocationModel>; + factory $LocationModelCopyWith(LocationModel value, $Res Function(LocationModel) then) = _$LocationModelCopyWithImpl<$Res, LocationModel>; + @useResult - $Res call( - {List locations, - @JsonKey(name: 'response_body') String responseBody}); + $Res call({List locations, @JsonKey(name: 'response_body') String responseBody}); } /// @nodoc -class _$LocationModelCopyWithImpl<$Res, $Val extends LocationModel> - implements $LocationModelCopyWith<$Res> { +class _$LocationModelCopyWithImpl<$Res, $Val extends LocationModel> implements $LocationModelCopyWith<$Res> { _$LocationModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; + // ignore: unused_field final $Res Function($Val) _then; @@ -71,25 +69,17 @@ class _$LocationModelCopyWithImpl<$Res, $Val extends LocationModel> } /// @nodoc -abstract class _$$LocationModelImplCopyWith<$Res> - implements $LocationModelCopyWith<$Res> { - factory _$$LocationModelImplCopyWith( - _$LocationModelImpl value, $Res Function(_$LocationModelImpl) then) = - __$$LocationModelImplCopyWithImpl<$Res>; +abstract class _$$LocationModelImplCopyWith<$Res> implements $LocationModelCopyWith<$Res> { + factory _$$LocationModelImplCopyWith(_$LocationModelImpl value, $Res Function(_$LocationModelImpl) then) = __$$LocationModelImplCopyWithImpl<$Res>; + @override @useResult - $Res call( - {List locations, - @JsonKey(name: 'response_body') String responseBody}); + $Res call({List locations, @JsonKey(name: 'response_body') String responseBody}); } /// @nodoc -class __$$LocationModelImplCopyWithImpl<$Res> - extends _$LocationModelCopyWithImpl<$Res, _$LocationModelImpl> - implements _$$LocationModelImplCopyWith<$Res> { - __$$LocationModelImplCopyWithImpl( - _$LocationModelImpl _value, $Res Function(_$LocationModelImpl) _then) - : super(_value, _then); +class __$$LocationModelImplCopyWithImpl<$Res> extends _$LocationModelCopyWithImpl<$Res, _$LocationModelImpl> implements _$$LocationModelImplCopyWith<$Res> { + __$$LocationModelImplCopyWithImpl(_$LocationModelImpl _value, $Res Function(_$LocationModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -113,15 +103,12 @@ class __$$LocationModelImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() class _$LocationModelImpl implements _LocationModel { - const _$LocationModelImpl( - {required final List locations, - @JsonKey(name: 'response_body') required this.responseBody}) - : _locations = locations; + const _$LocationModelImpl({required final List locations, @JsonKey(name: 'response_body') required this.responseBody}) : _locations = locations; - factory _$LocationModelImpl.fromJson(Map json) => - _$$LocationModelImplFromJson(json); + factory _$LocationModelImpl.fromJson(Map json) => _$$LocationModelImplFromJson(json); final List _locations; + @override List get locations { if (_locations is EqualUnmodifiableListView) return _locations; @@ -143,22 +130,18 @@ class _$LocationModelImpl implements _LocationModel { return identical(this, other) || (other.runtimeType == runtimeType && other is _$LocationModelImpl && - const DeepCollectionEquality() - .equals(other._locations, _locations) && - (identical(other.responseBody, responseBody) || - other.responseBody == responseBody)); + const DeepCollectionEquality().equals(other._locations, _locations) && + (identical(other.responseBody, responseBody) || other.responseBody == responseBody)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, - const DeepCollectionEquality().hash(_locations), responseBody); + int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_locations), responseBody); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$LocationModelImplCopyWith<_$LocationModelImpl> get copyWith => - __$$LocationModelImplCopyWithImpl<_$LocationModelImpl>(this, _$identity); + _$$LocationModelImplCopyWith<_$LocationModelImpl> get copyWith => __$$LocationModelImplCopyWithImpl<_$LocationModelImpl>(this, _$identity); @override Map toJson() { @@ -169,21 +152,19 @@ class _$LocationModelImpl implements _LocationModel { } abstract class _LocationModel implements LocationModel { - const factory _LocationModel( - {required final List locations, - @JsonKey(name: 'response_body') required final String responseBody}) = + const factory _LocationModel({required final List locations, @JsonKey(name: 'response_body') required final String responseBody}) = _$LocationModelImpl; - factory _LocationModel.fromJson(Map json) = - _$LocationModelImpl.fromJson; + factory _LocationModel.fromJson(Map json) = _$LocationModelImpl.fromJson; @override List get locations; + @override @JsonKey(name: 'response_body') String get responseBody; + @override @JsonKey(ignore: true) - _$$LocationModelImplCopyWith<_$LocationModelImpl> get copyWith => - throw _privateConstructorUsedError; + _$$LocationModelImplCopyWith<_$LocationModelImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/registration/models/location_model.g.dart b/lib/features/registration/models/location_model.g.dart index 449630a..da69ba9 100644 --- a/lib/features/registration/models/location_model.g.dart +++ b/lib/features/registration/models/location_model.g.dart @@ -6,15 +6,12 @@ part of 'location_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$LocationModelImpl _$$LocationModelImplFromJson(Map json) => - _$LocationModelImpl( - locations: - (json['locations'] as List).map((e) => e as String).toList(), +_$LocationModelImpl _$$LocationModelImplFromJson(Map json) => _$LocationModelImpl( + locations: (json['locations'] as List).map((e) => e as String).toList(), responseBody: json['response_body'] as String, ); -Map _$$LocationModelImplToJson(_$LocationModelImpl instance) => - { +Map _$$LocationModelImplToJson(_$LocationModelImpl instance) => { 'locations': instance.locations, 'response_body': instance.responseBody, }; 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 index dcb4923..63ae2c0 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_state.freezed.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_state.freezed.dart @@ -19,15 +19,13 @@ mixin _$RegistrationState { UserRegistrationSheet get sheet => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $RegistrationStateCopyWith get copyWith => - throw _privateConstructorUsedError; + $RegistrationStateCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $RegistrationStateCopyWith<$Res> { - factory $RegistrationStateCopyWith( - RegistrationState value, $Res Function(RegistrationState) then) = - _$RegistrationStateCopyWithImpl<$Res, RegistrationState>; + factory $RegistrationStateCopyWith(RegistrationState value, $Res Function(RegistrationState) then) = _$RegistrationStateCopyWithImpl<$Res, RegistrationState>; + @useResult $Res call({UserRegistrationSheet sheet}); @@ -35,12 +33,12 @@ abstract class $RegistrationStateCopyWith<$Res> { } /// @nodoc -class _$RegistrationStateCopyWithImpl<$Res, $Val extends RegistrationState> - implements $RegistrationStateCopyWith<$Res> { +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; @@ -67,11 +65,10 @@ class _$RegistrationStateCopyWithImpl<$Res, $Val extends RegistrationState> } /// @nodoc -abstract class _$$RegistrationStateImplCopyWith<$Res> - implements $RegistrationStateCopyWith<$Res> { - factory _$$RegistrationStateImplCopyWith(_$RegistrationStateImpl value, - $Res Function(_$RegistrationStateImpl) then) = +abstract class _$$RegistrationStateImplCopyWith<$Res> implements $RegistrationStateCopyWith<$Res> { + factory _$$RegistrationStateImplCopyWith(_$RegistrationStateImpl value, $Res Function(_$RegistrationStateImpl) then) = __$$RegistrationStateImplCopyWithImpl<$Res>; + @override @useResult $Res call({UserRegistrationSheet sheet}); @@ -81,12 +78,9 @@ abstract class _$$RegistrationStateImplCopyWith<$Res> } /// @nodoc -class __$$RegistrationStateImplCopyWithImpl<$Res> - extends _$RegistrationStateCopyWithImpl<$Res, _$RegistrationStateImpl> +class __$$RegistrationStateImplCopyWithImpl<$Res> extends _$RegistrationStateCopyWithImpl<$Res, _$RegistrationStateImpl> implements _$$RegistrationStateImplCopyWith<$Res> { - __$$RegistrationStateImplCopyWithImpl(_$RegistrationStateImpl _value, - $Res Function(_$RegistrationStateImpl) _then) - : super(_value, _then); + __$$RegistrationStateImplCopyWithImpl(_$RegistrationStateImpl _value, $Res Function(_$RegistrationStateImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -118,9 +112,7 @@ class _$RegistrationStateImpl implements _RegistrationState { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && - other is _$RegistrationStateImpl && - (identical(other.sheet, sheet) || other.sheet == sheet)); + (other.runtimeType == runtimeType && other is _$RegistrationStateImpl && (identical(other.sheet, sheet) || other.sheet == sheet)); } @override @@ -129,19 +121,16 @@ class _$RegistrationStateImpl implements _RegistrationState { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => - __$$RegistrationStateImplCopyWithImpl<_$RegistrationStateImpl>( - this, _$identity); + _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => __$$RegistrationStateImplCopyWithImpl<_$RegistrationStateImpl>(this, _$identity); } abstract class _RegistrationState implements RegistrationState { - const factory _RegistrationState( - {required final UserRegistrationSheet sheet}) = _$RegistrationStateImpl; + const factory _RegistrationState({required final UserRegistrationSheet sheet}) = _$RegistrationStateImpl; @override UserRegistrationSheet get sheet; + @override @JsonKey(ignore: true) - _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => - throw _privateConstructorUsedError; + _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/registration/presentation/pages/credentials_screen.dart b/lib/features/registration/presentation/pages/credentials_screen.dart index dc9d548..25b0a2a 100644 --- a/lib/features/registration/presentation/pages/credentials_screen.dart +++ b/lib/features/registration/presentation/pages/credentials_screen.dart @@ -41,6 +41,7 @@ class _CredentialsScreenState extends State { CustomTextFormField( controller: emailController, textInputType: TextInputType.emailAddress, + keyboardType: TextInputType.emailAddress, hintText: 'Введите email', textInputAction: TextInputAction.next, onChanged: (newValue) { diff --git a/lib/features/registration/services/registration_service.g.dart b/lib/features/registration/services/registration_service.g.dart index 9820fd3..d37f0f3 100644 --- a/lib/features/registration/services/registration_service.g.dart +++ b/lib/features/registration/services/registration_service.g.dart @@ -19,30 +19,28 @@ class _RegistrationService implements RegistrationService { String? baseUrl; @override - Future> register( - {required Map sheet}) async { + Future> register({required Map sheet}) async { final _extra = {}; final queryParameters = {}; final _headers = {}; final _data = {}; _data.addAll(sheet); - final _result = await _dio.fetch>( - _setStreamType>(Options( + 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, - )))); + .compose( + _dio.options, + '/api/register', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = _result.data!.cast(); return _value; } @@ -53,23 +51,22 @@ class _RegistrationService implements RegistrationService { final queryParameters = {r'user_address': query}; final _headers = {}; const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType(Options( + final _result = await _dio.fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/location_by_address', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/location_by_address', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = LocationModel.fromJson(_result.data!); return _value; } @@ -86,31 +83,28 @@ class _RegistrationService implements RegistrationService { }; final _headers = {}; const Map? _data = null; - final _result = await _dio - .fetch>(_setStreamType(Options( + final _result = await _dio.fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/location_by_coordinate', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/location_by_coordinate', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = LocationModel.fromJson(_result.data!); return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && - !(requestOptions.responseType == ResponseType.bytes || - requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { diff --git a/lib/localization/app_localization.dart b/lib/localization/app_localization.dart index 0c0b256..b477c9a 100644 --- a/lib/localization/app_localization.dart +++ b/lib/localization/app_localization.dart @@ -13,6 +13,7 @@ class AppLocalization { static final Map> _localizedValues = { 'ru': ru, }; + /*static final Map> __localizedValues = { 'en': enUs };*/ @@ -33,6 +34,7 @@ class AppLocalization { } static List languages() => _localizedValues.keys.toList(); + String getString(String text) => _localizedValues[locale.languageCode]![text] ?? text; } diff --git a/lib/locator_service.dart b/lib/locator_service.dart index 5947a11..5ca320f 100644 --- a/lib/locator_service.dart +++ b/lib/locator_service.dart @@ -12,13 +12,13 @@ import 'package:eatvio_app/features/calendar/services/calendar_service.dart'; import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_cubit.dart'; import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; import 'package:eatvio_app/features/chat/services/chat_service.dart'; +import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.dart'; +import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; +import 'package:eatvio_app/features/diary/services/diary_service.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart'; import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; import 'package:eatvio_app/features/feed/services/feed_service.dart'; -import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.dart'; -import 'package:eatvio_app/features/diary/repositories/diary_repository.dart'; -import 'package:eatvio_app/features/diary/services/diary_service.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'; diff --git a/lib/main.dart b/lib/main.dart index 03f769a..fdc96e6 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -6,21 +6,22 @@ import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/noti import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_cubit.dart'; 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/diary/presentation/bloc/diary_bloc.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/recipes_cubit/recipes_cubit.dart'; +import 'package:eatvio_app/locator_service.dart' as di; import 'package:eatvio_app/locator_service.dart'; -import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.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'; 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:keyboard_dismisser/keyboard_dismisser.dart'; -import 'package:eatvio_app/locator_service.dart' as di; import 'package:intl/date_symbol_data_local.dart'; +import 'package:keyboard_dismisser/keyboard_dismisser.dart'; +import 'package:path_provider/path_provider.dart'; + +import 'core/app_export.dart'; var globalMessengerKey = GlobalKey(); diff --git a/lib/presentation/auth/auth_screen/auth_screen.dart b/lib/presentation/auth/auth_screen/auth_screen.dart index adf6cf5..5f11a97 100644 --- a/lib/presentation/auth/auth_screen/auth_screen.dart +++ b/lib/presentation/auth/auth_screen/auth_screen.dart @@ -55,6 +55,7 @@ class _AuthScreenState extends State { return CustomTextFormField( controller: emailController, textInputAction: TextInputAction.next, + keyboardType: TextInputType.emailAddress, textInputType: TextInputType.emailAddress, hintText: 'Введите email', ); diff --git a/lib/presentation/auth/auth_screen/bloc/auth_state.dart b/lib/presentation/auth/auth_screen/bloc/auth_state.dart index 504180f..86e8e3b 100644 --- a/lib/presentation/auth/auth_screen/bloc/auth_state.dart +++ b/lib/presentation/auth/auth_screen/bloc/auth_state.dart @@ -22,6 +22,7 @@ class AuthState extends Equatable { passwordController, authModelObj, ]; + AuthState copyWith({ TextEditingController? emailController, TextEditingController? passwordController, 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 6b42e38..e063a43 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 @@ -14,6 +14,7 @@ class DietCreateState extends Equatable { @override List get props => [dietModelObj]; + DietCreateState copyWith({DietCreateModel? dietModelObj}) { return DietCreateState( dietModelObj: dietModelObj ?? this.dietModelObj, @@ -31,12 +32,14 @@ class DietCreateLoadedState extends DietCreateState { DietCreateModel? dietModelObj; TextEditingController? name; TextEditingController? details; + @override List get props => [ dietModelObj, name, details, ]; + DietCreateLoadedState copyWith({ DietCreateModel? dietModelObj, TextEditingController? name, diff --git a/lib/presentation/diets/diet_select_screen/bloc/diet_select_event.dart b/lib/presentation/diets/diet_select_screen/bloc/diet_select_event.dart index 9137295..75a889b 100644 --- a/lib/presentation/diets/diet_select_screen/bloc/diet_select_event.dart +++ b/lib/presentation/diets/diet_select_screen/bloc/diet_select_event.dart @@ -17,7 +17,9 @@ class DietSelectInitialEvent extends DietSelectEvent { class UploadAvatar extends DietSelectEvent { UploadAvatar(this.image); + final XFile image; + @override List get props => [image]; } 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 85b7d5a..6401481 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 @@ -21,11 +21,13 @@ class DietSelectLoadedState extends DietSelectState { DietSelectModel? myProfileModelObj; List? posts; + @override List get props => [ myProfileModelObj, posts, ]; + DietSelectLoadedState copyWith({ DietSelectModel? myProfileModelObj, List? posts, diff --git a/lib/presentation/diets/diet_show_screen/bloc/diet_show_event.dart b/lib/presentation/diets/diet_show_screen/bloc/diet_show_event.dart index 6a131d5..c79eaf3 100644 --- a/lib/presentation/diets/diet_show_screen/bloc/diet_show_event.dart +++ b/lib/presentation/diets/diet_show_screen/bloc/diet_show_event.dart @@ -17,7 +17,9 @@ class DietInitialEvent extends DietEvent { class DeleteEntry extends DietEvent { DeleteEntry(this.id); + final int id; + @override List get props => [id]; } 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 d587263..32070c1 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 @@ -14,6 +14,7 @@ class DietState extends Equatable { @override List get props => [dietModelObj]; + DietState copyWith({DietModel? dietModelObj}) { return DietState( dietModelObj: dietModelObj ?? this.dietModelObj, @@ -26,8 +27,10 @@ class DietLoadedState extends DietState { DietModel? dietModelObj; Map? diet; + @override List get props => [dietModelObj, diet]; + DietLoadedState copyWith({DietModel? dietModelObj, Map? diet}) { return DietLoadedState( dietModelObj: dietModelObj ?? this.dietModelObj, 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 184938a..798b771 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,4 +1,5 @@ import 'dart:async'; + import 'package:dio/dio.dart'; import 'package:eatvio_app/app_router.dart'; import 'package:eatvio_app/locator_service.dart'; @@ -12,7 +13,6 @@ import 'package:image_picker/image_picker.dart'; import '/core/app_export.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. 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 d78db89..3fa6f7b 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 @@ -14,6 +14,7 @@ class BlogPostEditState extends Equatable { @override List get props => [blog_postModelObj]; + BlogPostEditState copyWith({BlogPostEditModel? blog_postModelObj}) { return BlogPostEditState( blog_postModelObj: blog_postModelObj ?? this.blog_postModelObj, @@ -35,8 +36,10 @@ class BlogPostEditLoadedState extends BlogPostEditState { TextEditingController? title; TextEditingController? description; TextEditingController? youtubeURL; + @override List get props => [blog_postModelObj, blog_post, title, description, youtubeURL]; + BlogPostEditLoadedState copyWith({ BlogPostEditModel? blog_postModelObj, Map? blog_post, 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 73e9c6a..106b3b5 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 @@ -5,7 +5,9 @@ import 'package:equatable/equatable.dart'; class BlogPostModel extends Equatable { final String blog_postID; + BlogPostModel({required this.blog_postID, this.comments = const []}); + List comments; BlogPostModel copyWith({String? blog_postID, List? comments}) { diff --git a/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_event.dart b/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_event.dart index f3fb4dd..29cabd5 100644 --- a/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_event.dart +++ b/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_event.dart @@ -17,14 +17,18 @@ class GlossaryInitialEvent extends GlossaryEvent { class DeleteEntry extends GlossaryEvent { DeleteEntry(this.id); + final int id; + @override List get props => [id]; } class ChangeProductGroup extends GlossaryEvent { ChangeProductGroup(this.id); + final int id; + @override List get props => [id]; } 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 42119a8..a3d819f 100644 --- a/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_state.dart +++ b/lib/presentation/glossary/glossary_screen/bloc/glossary_screen_state.dart @@ -14,6 +14,7 @@ class GlossaryState extends Equatable { @override List get props => [glossaryModelObj]; + GlossaryState copyWith({GlossaryModel? glossaryModelObj}) { return GlossaryState( glossaryModelObj: glossaryModelObj ?? this.glossaryModelObj, @@ -33,8 +34,10 @@ class GlossaryLoadedState extends GlossaryState { String? token; List? productGroups; List? productList; + @override List get props => [glossaryModelObj, productGroups, productList, token]; + GlossaryLoadedState copyWith({ GlossaryModel? glossaryModelObj, String? token, diff --git a/lib/presentation/glossary/glossary_screen/models/glossary_screen_model.dart b/lib/presentation/glossary/glossary_screen/models/glossary_screen_model.dart index d19bbb5..1077bd6 100644 --- a/lib/presentation/glossary/glossary_screen/models/glossary_screen_model.dart +++ b/lib/presentation/glossary/glossary_screen/models/glossary_screen_model.dart @@ -7,6 +7,7 @@ import 'package:equatable/equatable.dart'; class GlossaryModel extends Equatable { GlossaryModel(); + GlossaryModel copyWith() { return GlossaryModel(); } 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 4e98812..f248565 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 @@ -14,6 +14,7 @@ class PlanCreateState extends Equatable { @override List get props => [planModelObj]; + PlanCreateState copyWith({PlanCreateModel? planModelObj}) { return PlanCreateState( planModelObj: planModelObj ?? this.planModelObj, @@ -31,12 +32,14 @@ class PlanCreateLoadedState extends PlanCreateState { PlanCreateModel? planModelObj; TextEditingController? name; TextEditingController? details; + @override List get props => [ planModelObj, name, details, ]; + PlanCreateLoadedState copyWith({ PlanCreateModel? planModelObj, TextEditingController? name, 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 e3cf6b8..57e0a3a 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 @@ -14,6 +14,7 @@ class PlanEditState extends Equatable { @override List get props => [planModelObj]; + PlanEditState copyWith({PlanEditModel? planModelObj}) { return PlanEditState( planModelObj: planModelObj ?? this.planModelObj, @@ -35,8 +36,10 @@ class PlanEditLoadedState extends PlanEditState { TextEditingController? name; TextEditingController? details; TextEditingController? duration; + @override List get props => [planModelObj, plan, name, details, duration]; + PlanEditLoadedState copyWith({ PlanEditModel? planModelObj, Map? plan, diff --git a/lib/presentation/plans/plan_select_screen/bloc/plan_select_event.dart b/lib/presentation/plans/plan_select_screen/bloc/plan_select_event.dart index 5cb4b41..1cae632 100644 --- a/lib/presentation/plans/plan_select_screen/bloc/plan_select_event.dart +++ b/lib/presentation/plans/plan_select_screen/bloc/plan_select_event.dart @@ -17,7 +17,9 @@ class PlanSelectInitialEvent extends PlanSelectEvent { class UploadAvatar extends PlanSelectEvent { UploadAvatar(this.image); + final XFile image; + @override List get props => [image]; } 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 2c8561b..b5245be 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 @@ -21,11 +21,13 @@ class PlanSelectLoadedState extends PlanSelectState { PlanSelectModel? myProfileModelObj; List? posts; + @override List get props => [ myProfileModelObj, posts, ]; + PlanSelectLoadedState copyWith({ PlanSelectModel? myProfileModelObj, List? posts, diff --git a/lib/presentation/plans/plan_show_screen/bloc/plan_show_event.dart b/lib/presentation/plans/plan_show_screen/bloc/plan_show_event.dart index fc83e02..6572e25 100644 --- a/lib/presentation/plans/plan_show_screen/bloc/plan_show_event.dart +++ b/lib/presentation/plans/plan_show_screen/bloc/plan_show_event.dart @@ -17,7 +17,9 @@ class PlanInitialEvent extends PlanEvent { class DeleteEntry extends PlanEvent { DeleteEntry(this.id); + final int id; + @override List get props => [id]; } 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 5052710..127be04 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 @@ -14,6 +14,7 @@ class PlanState extends Equatable { @override List get props => [planModelObj]; + PlanState copyWith({PlanModel? planModelObj}) { return PlanState( planModelObj: planModelObj ?? this.planModelObj, @@ -26,8 +27,10 @@ class PlanLoadedState extends PlanState { PlanModel? planModelObj; Map? plan; + @override List get props => [planModelObj, plan]; + PlanLoadedState copyWith({PlanModel? planModelObj, Map? plan}) { return PlanLoadedState( planModelObj: planModelObj ?? this.planModelObj, diff --git a/lib/presentation/profile/my_profile_screen/bloc/my_profile_event.dart b/lib/presentation/profile/my_profile_screen/bloc/my_profile_event.dart index ca76f24..e682252 100644 --- a/lib/presentation/profile/my_profile_screen/bloc/my_profile_event.dart +++ b/lib/presentation/profile/my_profile_screen/bloc/my_profile_event.dart @@ -17,7 +17,9 @@ class MyProfileInitialEvent extends MyProfileEvent { class UploadAvatar extends MyProfileEvent { UploadAvatar(this.image); + final XFile image; + @override List get props => [image]; } 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 85c254d..002d6f0 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 @@ -90,6 +90,7 @@ class MyProfileLoadedState extends MyProfileState { String? selectedActivity; String? hypoFormController; String? hyperFormController; + @override List get props => [ myProfileModelObj, @@ -127,6 +128,7 @@ class MyProfileLoadedState extends MyProfileState { hypoFormController, hyperFormController, ]; + MyProfileLoadedState copyWith({ MyProfileModel? myProfileModelObj, Map? user, diff --git a/lib/presentation/recipe/recipe_create_screen/bloc/recipe_create_event.dart b/lib/presentation/recipe/recipe_create_screen/bloc/recipe_create_event.dart index 085045d..85d8ee4 100644 --- a/lib/presentation/recipe/recipe_create_screen/bloc/recipe_create_event.dart +++ b/lib/presentation/recipe/recipe_create_screen/bloc/recipe_create_event.dart @@ -22,19 +22,23 @@ class CreateRecipe extends RecipeCreateEvent { class AddStep extends RecipeCreateEvent { AddStep(); + @override List get props => []; } class RemoveStep extends RecipeCreateEvent { RemoveStep(this.id); + final int id; + @override List get props => [id]; } class ReloadScreen extends RecipeCreateEvent { ReloadScreen(); + @override List get props => []; } 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 d58773a..d2e1b2b 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 @@ -14,6 +14,7 @@ class RecipeCreateState extends Equatable { @override List get props => [recipeModelObj]; + RecipeCreateState copyWith({RecipeCreateModel? recipeModelObj}) { return RecipeCreateState( recipeModelObj: recipeModelObj ?? this.recipeModelObj, @@ -41,6 +42,7 @@ class RecipeCreateLoadedState extends RecipeCreateState { TextEditingController? tags; List? steps; List? stepDescriptions; + @override List get props => [ recipeModelObj, @@ -52,6 +54,7 @@ class RecipeCreateLoadedState extends RecipeCreateState { tags, stepDescriptions, ]; + RecipeCreateLoadedState copyWith({ RecipeCreateModel? recipeModelObj, String? token, diff --git a/lib/presentation/recipe/recipe_edit_screen/bloc/recipe_edit_event.dart b/lib/presentation/recipe/recipe_edit_screen/bloc/recipe_edit_event.dart index c6d49d3..b4bdd5f 100644 --- a/lib/presentation/recipe/recipe_edit_screen/bloc/recipe_edit_event.dart +++ b/lib/presentation/recipe/recipe_edit_screen/bloc/recipe_edit_event.dart @@ -22,19 +22,23 @@ class EditRecipe extends RecipeEditEvent { class AddStep extends RecipeEditEvent { AddStep(); + @override List get props => []; } class RemoveStep extends RecipeEditEvent { RemoveStep(this.id); + final int id; + @override List get props => [id]; } class ReloadScreen extends RecipeEditEvent { ReloadScreen(); + @override List get props => []; } 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 57df9f2..c01ffc4 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 @@ -14,6 +14,7 @@ class RecipeEditState extends Equatable { @override List get props => [recipeModelObj]; + RecipeEditState copyWith({RecipeEditModel? recipeModelObj}) { return RecipeEditState( recipeModelObj: recipeModelObj ?? this.recipeModelObj, @@ -45,8 +46,10 @@ class RecipeEditLoadedState extends RecipeEditState { List? steps; List? tags; List? stepDescriptions; + @override List get props => [recipeModelObj, recipe, title, description, video_url]; + RecipeEditLoadedState copyWith({ RecipeEditModel? recipeModelObj, Map? recipe, diff --git a/lib/presentation/recipe/recipe_select_screen/bloc/recipe_select_event.dart b/lib/presentation/recipe/recipe_select_screen/bloc/recipe_select_event.dart index 460c79c..416e1f2 100644 --- a/lib/presentation/recipe/recipe_select_screen/bloc/recipe_select_event.dart +++ b/lib/presentation/recipe/recipe_select_screen/bloc/recipe_select_event.dart @@ -17,7 +17,9 @@ class RecipeSelectInitialEvent extends RecipeSelectEvent { class UploadAvatar extends RecipeSelectEvent { UploadAvatar(this.image); + final XFile image; + @override List get props => [image]; } 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 d320f90..02b6a79 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 @@ -21,11 +21,13 @@ class RecipeSelectLoadedState extends RecipeSelectState { RecipeSelectModel? myProfileModelObj; List? posts; + @override List get props => [ myProfileModelObj, posts, ]; + RecipeSelectLoadedState copyWith({ RecipeSelectModel? myProfileModelObj, List? posts, diff --git a/lib/presentation/recipe/recipe_show_screen/bloc/recipe_show_event.dart b/lib/presentation/recipe/recipe_show_screen/bloc/recipe_show_event.dart index 7510c3a..f2e71b7 100644 --- a/lib/presentation/recipe/recipe_show_screen/bloc/recipe_show_event.dart +++ b/lib/presentation/recipe/recipe_show_screen/bloc/recipe_show_event.dart @@ -17,14 +17,18 @@ class RecipeInitialEvent extends RecipeEvent { class DeleteEntry extends RecipeEvent { DeleteEntry(this.id); + final int id; + @override List get props => [id]; } class CreateComment extends RecipeEvent { CreateComment(this.body); + final String body; + @override List get props => [body]; } 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 335ac20..0b7b2e8 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 @@ -14,6 +14,7 @@ class RecipeState extends Equatable { @override List get props => [recipeModelObj]; + RecipeState copyWith({RecipeModel? recipeModelObj}) { return RecipeState( recipeModelObj: recipeModelObj ?? this.recipeModelObj, @@ -41,6 +42,7 @@ class RecipeLoadedState extends RecipeState { List? steps; List? tags; String? token; + @override List get props => [ recipeModelObj, @@ -51,6 +53,7 @@ class RecipeLoadedState extends RecipeState { commentController, steps, ]; + RecipeLoadedState copyWith({ RecipeModel? recipeModelObj, Map? recipe, diff --git a/lib/presentation/users/subscribers_screen/bloc/subscribers_state.dart b/lib/presentation/users/subscribers_screen/bloc/subscribers_state.dart index f934270..2b34e5b 100644 --- a/lib/presentation/users/subscribers_screen/bloc/subscribers_state.dart +++ b/lib/presentation/users/subscribers_screen/bloc/subscribers_state.dart @@ -21,11 +21,13 @@ class SubscribersLoadedState extends SubscribersState { SubscribersModel? myProfileModelObj; dynamic subscribers; + @override List get props => [ myProfileModelObj, subscribers, ]; + SubscribersLoadedState copyWith({ SubscribersModel? myProfileModelObj, dynamic subscribers, diff --git a/lib/theme/app_decoration.dart b/lib/theme/app_decoration.dart index 9ba1b22..c84477e 100644 --- a/lib/theme/app_decoration.dart +++ b/lib/theme/app_decoration.dart @@ -15,6 +15,7 @@ class AppDecoration { width: 1.h, ), ); + static BoxDecoration get outlinePrimary => BoxDecoration( color: theme.colorScheme.onPrimary, border: Border.all( @@ -22,27 +23,35 @@ class AppDecoration { width: 1.h, ), ); + static BoxDecoration get fillDeepOrange => BoxDecoration( color: appTheme.deepOrange900.withOpacity(0.8), ); + static BoxDecoration get fillGray => BoxDecoration( color: appTheme.gray50, ); + static BoxDecoration get fillGray100 => BoxDecoration( color: appTheme.gray100, ); + static BoxDecoration get fillGray60002 => BoxDecoration( color: appTheme.gray60002, ); + static BoxDecoration get fillGreenA => BoxDecoration( color: appTheme.greenA700.withOpacity(0.8), ); + static BoxDecoration get fillPrimary => BoxDecoration( color: theme.colorScheme.primary, ); + static BoxDecoration get fillWhiteA => BoxDecoration( color: appTheme.whiteA700, ); + static BoxDecoration get outlineBlueGray => BoxDecoration( border: Border.all( color: appTheme.blueGray800, @@ -78,6 +87,7 @@ class BorderRadiusStyle { ), ], ); + static BoxDecoration get outlineBlueGray => BoxDecoration( border: Border.all( color: appTheme.blueGray800, @@ -85,13 +95,16 @@ class BorderRadiusStyle { strokeAlign: strokeAlignOutside, ), ); + // Circle borders static BorderRadius get circleBorder17 => BorderRadius.circular( 17.h, ); + static BorderRadius get circleBorder20 => BorderRadius.circular( 20.h, ); + static BorderRadius get circleBorder62 => BorderRadius.circular( 62.h, ); @@ -100,9 +113,11 @@ class BorderRadiusStyle { static BorderRadius get customBorderBL8 => BorderRadius.only( bottomLeft: Radius.circular(8.h), ); + static BorderRadius get customBorderTL5 => BorderRadius.vertical( top: Radius.circular(5.h), ); + static BorderRadius get customBorderTL51 => BorderRadius.only( topLeft: Radius.circular(5.h), bottomRight: Radius.circular(5.h), @@ -112,9 +127,11 @@ class BorderRadiusStyle { static BorderRadius get roundedBorder12 => BorderRadius.circular( 12.h, ); + static BorderRadius get roundedBorder5 => BorderRadius.circular( 5.h, ); + static BorderRadius get roundedBorder8 => BorderRadius.circular( 8.h, ); diff --git a/lib/theme/bloc/theme_state.dart b/lib/theme/bloc/theme_state.dart index 2f93fff..191bcfe 100644 --- a/lib/theme/bloc/theme_state.dart +++ b/lib/theme/bloc/theme_state.dart @@ -8,6 +8,7 @@ class ThemeState extends Equatable { @override List get props => [themeType]; + ThemeState copyWith({String? themeType}) { return ThemeState(themeType: themeType ?? this.themeType); } diff --git a/lib/theme/custom_button_style.dart b/lib/theme/custom_button_style.dart index 60204f5..bcd021c 100644 --- a/lib/theme/custom_button_style.dart +++ b/lib/theme/custom_button_style.dart @@ -14,6 +14,7 @@ class CustomButtonStyles { borderRadius: BorderRadius.circular(15.h), ), ); + // text button style static ButtonStyle get none => ButtonStyle( backgroundColor: WidgetStateProperty.all(Colors.transparent), diff --git a/lib/widgets/custom_drop_down.dart b/lib/widgets/custom_drop_down.dart index fc166b2..96367d6 100644 --- a/lib/widgets/custom_drop_down.dart +++ b/lib/widgets/custom_drop_down.dart @@ -85,20 +85,22 @@ class CustomDropDown extends StatelessWidget { autofocus: autofocus!, value: value, isExpanded: true, - style: textStyle ?? TextStyle( - fontSize: 16, - fontWeight: FontWeight.w400, - ), + style: textStyle ?? + TextStyle( + fontSize: 16, + fontWeight: FontWeight.w400, + ), items: items?.map((SelectionPopupModel item) { return DropdownMenuItem( value: item, child: Text( item.title, - style: hintStyle ?? TextStyle( - fontSize: 16, - fontWeight: FontWeight.w400, - color: Colors.black, - ), + style: hintStyle ?? + TextStyle( + fontSize: 16, + fontWeight: FontWeight.w400, + color: Colors.black, + ), ), ); }).toList(), @@ -115,11 +117,12 @@ class CustomDropDown extends StatelessWidget { InputDecoration _buildInputDecoration(BuildContext context) { return InputDecoration( hintText: hintText ?? "", - hintStyle: hintStyle ?? TextStyle( - fontSize: 16, - fontWeight: FontWeight.w400, - color: Colors.grey.shade400, - ), + hintStyle: hintStyle ?? + TextStyle( + fontSize: 16, + fontWeight: FontWeight.w400, + color: Colors.grey.shade400, + ), prefixIcon: prefix, prefixIconConstraints: prefixConstraints, suffixIcon: suffix, diff --git a/lib/widgets/custom_edit_drop_down.dart b/lib/widgets/custom_edit_drop_down.dart index 7f56bbd..26b4283 100644 --- a/lib/widgets/custom_edit_drop_down.dart +++ b/lib/widgets/custom_edit_drop_down.dart @@ -25,8 +25,8 @@ class CustomDropDown extends StatelessWidget { this.onChanged, this.defaultValue, }) : super( - key: key, - ); + key: key, + ); final Alignment? alignment; @@ -72,9 +72,9 @@ class CustomDropDown extends StatelessWidget { Widget build(BuildContext context) { return alignment != null ? Align( - alignment: alignment ?? Alignment.center, - child: _buildDropDownWidget(context), - ) + alignment: alignment ?? Alignment.center, + child: _buildDropDownWidget(context), + ) : _buildDropDownWidget(context); } @@ -85,14 +85,20 @@ class CustomDropDown extends StatelessWidget { focusNode: focusNode ?? FocusNode(), icon: icon, autofocus: autofocus!, - style: textStyle ?? Theme.of(context).textTheme.titleMedium, + style: textStyle ?? Theme + .of(context) + .textTheme + .titleMedium, items: items?.map((SelectionPopupModel item) { return DropdownMenuItem( value: item, child: Text( item.title, overflow: TextOverflow.ellipsis, - style: hintStyle ?? Theme.of(context).textTheme.titleMedium, + style: hintStyle ?? Theme + .of(context) + .textTheme + .titleMedium, ), ); }).toList(), @@ -111,7 +117,10 @@ class CustomDropDown extends StatelessWidget { InputDecoration _buildInputDecoration(BuildContext context) { return InputDecoration( hintText: hintText ?? "", - hintStyle: hintStyle ?? Theme.of(context).textTheme.titleMedium, + hintStyle: hintStyle ?? Theme + .of(context) + .textTheme + .titleMedium, prefixIcon: prefix, prefixIconConstraints: prefixConstraints, suffixIcon: suffix, @@ -123,7 +132,10 @@ class CustomDropDown extends StatelessWidget { top: 6, bottom: 6, ), - fillColor: fillColor ?? Theme.of(context).colorScheme.onPrimary, + fillColor: fillColor ?? Theme + .of(context) + .colorScheme + .onPrimary, filled: filled, border: borderDecoration ?? OutlineInputBorder( diff --git a/lib/widgets/custom_expandable_list.dart b/lib/widgets/custom_expandable_list.dart index a98dd33..167c68e 100644 --- a/lib/widgets/custom_expandable_list.dart +++ b/lib/widgets/custom_expandable_list.dart @@ -247,12 +247,16 @@ class _ExpandableListState extends State { value: value, child: SizedBox( // Используем SizedBox для ограничения ширины элемента списка - width: MediaQuery.of(context).size.width * 0.8, // Устанавливаем желаемую ширину элемента списка + width: MediaQuery + .of(context) + .size + .width * 0.8, // Устанавливаем желаемую ширину элемента списка child: Text(value), ), ); }).toList(), - isExpanded: true, // Расширяем список на всю доступную ширину + isExpanded: true, + // Расширяем список на всю доступную ширину decoration: InputDecoration(labelText: 'Активность'), ), Row( @@ -391,11 +395,9 @@ class _ExpandableListState extends State { return baseUrl + '/api/profile/update'; } - Future _sendHttpRequest( - Map profileData, - String apiUrl, - String? token, - ) { + Future _sendHttpRequest(Map profileData, + String apiUrl, + String? token,) { return http.post( Uri.parse(apiUrl), body: json.encode(profileData), @@ -420,16 +422,17 @@ class _ExpandableListState extends State { void _showErrorDialog(String errorMessage) { showDialog( context: context, - builder: (context) => AlertDialog( - title: Text('Ошибка'), - content: Text(errorMessage), - actions: [ - TextButton( - onPressed: onTapOk(context), - child: Text('OK'), + builder: (context) => + AlertDialog( + title: Text('Ошибка'), + content: Text(errorMessage), + actions: [ + TextButton( + onPressed: onTapOk(context), + child: Text('OK'), + ), + ], ), - ], - ), ); } diff --git a/lib/widgets/custom_hyper_switch.dart b/lib/widgets/custom_hyper_switch.dart index edad8ec..3d28d05 100644 --- a/lib/widgets/custom_hyper_switch.dart +++ b/lib/widgets/custom_hyper_switch.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; class HyperSwitch extends StatefulWidget { final String title; final MyProfileLoadedState? state; + HyperSwitch(this.title, this.state); @override diff --git a/lib/widgets/custom_hypo_switch.dart b/lib/widgets/custom_hypo_switch.dart index 2e0c511..9504e5f 100644 --- a/lib/widgets/custom_hypo_switch.dart +++ b/lib/widgets/custom_hypo_switch.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; class HypoSwitch extends StatefulWidget { final String title; final MyProfileLoadedState? state; + HypoSwitch(this.title, this.state); @override diff --git a/lib/widgets/custom_language_drop_down.dart b/lib/widgets/custom_language_drop_down.dart index 7f0e3e0..f04a703 100644 --- a/lib/widgets/custom_language_drop_down.dart +++ b/lib/widgets/custom_language_drop_down.dart @@ -13,7 +13,8 @@ class _LanguageDropdownState extends State { return DropdownButton( value: selectedLanguage, onChanged: selectLanguage(), - isDense: false, // Установите isDense в false + isDense: false, + // Установите isDense в false selectedItemBuilder: getList(), items: ['Русский'].map((String language) { return DropdownMenuItem( diff --git a/lib/widgets/custom_outlined_button.dart b/lib/widgets/custom_outlined_button.dart index 38a7704..4b17491 100644 --- a/lib/widgets/custom_outlined_button.dart +++ b/lib/widgets/custom_outlined_button.dart @@ -89,7 +89,7 @@ class CustomOutlinedButton extends BaseButton { } } - /*_buildAppBarbuildOutlinedButtonWidget() { +/*_buildAppBarbuildOutlinedButtonWidget() { return Container( height: this.height ?? 30.v, width: this.width ?? double.maxFinite, diff --git a/lib/widgets/custom_text_form_field.dart b/lib/widgets/custom_text_form_field.dart index 11aa7d4..a2b6c74 100644 --- a/lib/widgets/custom_text_form_field.dart +++ b/lib/widgets/custom_text_form_field.dart @@ -11,8 +11,8 @@ class CustomTextFormField extends StatelessWidget { this.autofocus = false, this.textStyle, this.obscureText = false, - this.textInputAction = TextInputAction.next, - this.textInputType = TextInputType.text, + this.textInputAction, + this.textInputType, this.maxLines, this.hintText, this.hintStyle, -- 2.49.1 From 3ba48289b0b7b3f688f5546957c55a56d5eecee2 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Fri, 2 Aug 2024 17:52:06 +0300 Subject: [PATCH 099/110] feat(recipes): add recipes screen --- .../feed/presentation/pages/feed_screen.dart | 4 - .../widgets/blog_post_widget.dart | 9 +- .../pages/about_recipes_screen.dart | 98 ++++++++++++++++--- 3 files changed, 88 insertions(+), 23 deletions(-) diff --git a/lib/features/feed/presentation/pages/feed_screen.dart b/lib/features/feed/presentation/pages/feed_screen.dart index cb6c714..5cfa100 100644 --- a/lib/features/feed/presentation/pages/feed_screen.dart +++ b/lib/features/feed/presentation/pages/feed_screen.dart @@ -7,7 +7,6 @@ import 'package:eatvio_app/features/feed/presentation/widgets/recipes_widget.dar import 'package:eatvio_app/theme/theme_helper.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; @@ -29,9 +28,6 @@ class _FeedScreenState extends State { appBar: AppBar( backgroundColor: Colors.white, toolbarHeight: 0, - systemOverlayStyle: SystemUiOverlayStyle( - statusBarColor: Colors.white, - ), ), backgroundColor: Colors.grey.shade200, body: NestedScrollView( diff --git a/lib/features/feed/presentation/widgets/blog_post_widget.dart b/lib/features/feed/presentation/widgets/blog_post_widget.dart index ee629c3..1139fe0 100644 --- a/lib/features/feed/presentation/widgets/blog_post_widget.dart +++ b/lib/features/feed/presentation/widgets/blog_post_widget.dart @@ -20,11 +20,10 @@ class _BlogPostWidgetState extends State { Widget build(BuildContext context) { return InkWell( borderRadius: BorderRadius.circular(12), - onTap: () => - GoRouter.of(context).pushNamed( - 'blogPostScreen', - extra: widget.feedBlogPostModel.id.toString(), - ), + onTap: () => GoRouter.of(context).pushNamed( + 'blogPostScreen', + extra: widget.feedBlogPostModel.id.toString(), + ), child: Ink( decoration: BoxDecoration( borderRadius: BorderRadius.circular(12), diff --git a/lib/features/recipes/presentation/pages/about_recipes_screen.dart b/lib/features/recipes/presentation/pages/about_recipes_screen.dart index aa83ef2..27d69e3 100644 --- a/lib/features/recipes/presentation/pages/about_recipes_screen.dart +++ b/lib/features/recipes/presentation/pages/about_recipes_screen.dart @@ -14,35 +14,105 @@ class AboutRecipesScreen extends StatelessWidget { return Scaffold( appBar: AppBar(), body: SingleChildScrollView( - padding: EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(recipes.title), - Row( - children: [ - Text(recipes.cookingTime.toString() + ' минут'), - SizedBox(width: 16), - Text(recipes.steps.length.toString() + ' этапов'), - ], + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + recipes.title, + style: TextStyle( + color: Colors.black, + fontSize: 24, + fontWeight: FontWeight.w500, + height: 1, + ), + ), ), - Text(recipes.videoUrl), - CachedNetworkImage(imageUrl: baseUrl + '/storage/' + recipes.image), + SizedBox(height: 12), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + children: [ + Icon(Icons.timer_outlined), + SizedBox(width: 4), + Text( + recipes.cookingTime.toString() + ' минут', + style: TextStyle( + color: Colors.black, + fontSize: 12, + fontWeight: FontWeight.w400, + height: 1, + ), + ), + SizedBox(width: 16), + Icon(Icons.fast_forward_outlined), + SizedBox(width: 4), + Text( + recipes.steps.length.toString() + ' этапов', + style: TextStyle( + color: Colors.black, + fontSize: 12, + fontWeight: FontWeight.w400, + height: 1, + ), + ), + ], + ), + ), + SizedBox(height: 12), + CachedNetworkImage( + imageUrl: baseUrl + '/storage/' + recipes.image, + ), + SizedBox(height: 12), Text(recipes.ingredients.toString()), Text('Пошаговый рецепт'), - for (int i = 0; i < recipes.steps.length; i++) ...[_step(recipes.steps[i])], + ListView.separated( + shrinkWrap: true, + physics: NeverScrollableScrollPhysics(), + itemBuilder: (context, index) => + _step(recipes.steps[index], index + 1), + separatorBuilder: (context, index) => SizedBox(height: 16), + itemCount: recipes.steps.length, + ), ], ), ), ); } - _step(step.Step step) { + _step(step.Step step, int stepNubmer) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(step.description), - if (step.image.length > 1) CachedNetworkImage(imageUrl: baseUrl + '/storage/' + step.image), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + 'Шаг ' + stepNubmer.toString(), + style: TextStyle( + color: Colors.black54, + fontSize: 14, + fontWeight: FontWeight.w400, + height: 1, + ), + ), + ), + SizedBox(height: 12), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + step.description, + style: TextStyle( + color: Colors.black, + fontSize: 14, + fontWeight: FontWeight.w400, + height: 1.2, + ), + ), + ), + SizedBox(height: 8), + if (step.image.length > 1) + CachedNetworkImage(imageUrl: baseUrl + '/storage/' + step.image), ], ); } -- 2.49.1 From 5d13358fbc322e7ea7a7101dde2cfbfce8230c01 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 2 Aug 2024 18:08:28 +0300 Subject: [PATCH 100/110] feat(diary): Diary ID is passed on calendar click, new layouts for calendar, fixed nutrition chart --- lib/app_router.dart | 15 +- .../calendar/models/calendar_entry_model.dart | 20 ++ .../presentation/pages/calendar_screen.dart | 221 ++++++++++++------ .../diary/presentation/bloc/diary_bloc.dart | 58 +++-- .../presentation/pages/diary_screen.dart | 24 +- 5 files changed, 230 insertions(+), 108 deletions(-) create mode 100644 lib/features/calendar/models/calendar_entry_model.dart diff --git a/lib/app_router.dart b/lib/app_router.dart index 5eb1d0c..0b89f71 100644 --- a/lib/app_router.dart +++ b/lib/app_router.dart @@ -68,10 +68,14 @@ class AppRouter { builder: (context, state) => FeedScreenNew(), ), GoRoute( - path: '/diary-screen', - name: 'diaryScreen', - builder: (context, state) => DiaryScreen(), - ), + path: '/diary-screen', + name: 'diaryScreen', + builder: (context, state) { + if (state.extra != null) + return DiaryScreen(diaryID: state.extra as String); + else + return DiaryScreen(diaryID: '0'); + }), GoRoute( path: '/chat-select-screen', name: 'chatSelectScreen', @@ -87,7 +91,8 @@ class AppRouter { GoRoute( path: '/blog-post-screen', name: 'blogPostScreen', - builder: (context, state) => BlogPostScreen(blogPostID: state.extra as String), + builder: (context, state) => + BlogPostScreen(blogPostID: state.extra as String), ), GoRoute( path: '/blog-post-edit-screen', diff --git a/lib/features/calendar/models/calendar_entry_model.dart b/lib/features/calendar/models/calendar_entry_model.dart new file mode 100644 index 0000000..d9fa704 --- /dev/null +++ b/lib/features/calendar/models/calendar_entry_model.dart @@ -0,0 +1,20 @@ +import 'package:eatvio_app/core/app_export.dart'; + +/// This class is used in the [userprofile_item_widget] screen. +// ignore_for_file: must_be_immutable + +class CalendarEntryModel { + String? date; + String? status; + String id; + + CalendarEntryModel({ + this.date, + this.status, + required this.id, + }) { + date = date; + status = status; + id = id; + } +} diff --git a/lib/features/calendar/presentation/pages/calendar_screen.dart b/lib/features/calendar/presentation/pages/calendar_screen.dart index ab90403..3824512 100644 --- a/lib/features/calendar/presentation/pages/calendar_screen.dart +++ b/lib/features/calendar/presentation/pages/calendar_screen.dart @@ -1,11 +1,10 @@ // ignore_for_file: unused_local_variable -import 'package:eatvio_app/features/calendar/models/calendar_model.dart'; import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_cubit.dart'; import 'package:eatvio_app/features/calendar/presentation/bloc/calendar_state.dart'; import 'package:eatvio_app/core/app_export.dart'; import 'package:go_router/go_router.dart'; -import 'package:table_calendar/table_calendar.dart'; +import 'package:intl/intl.dart'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; @@ -54,7 +53,7 @@ class CalendarScreen extends StatelessWidget { toolbarHeight: 0, automaticallyImplyLeading: false, ), - backgroundColor: Color.fromARGB(255, 240, 242, 245), + backgroundColor: Colors.white, resizeToAvoidBottomInset: true, body: SizedBox( width: double.maxFinite, @@ -83,82 +82,154 @@ class CalendarScreen extends StatelessWidget { } _buildCalendarBody(BuildContext context, CalendarStateLoaded state) { - return Container( - margin: EdgeInsets.symmetric(horizontal: 16.h, vertical: 16.h), - padding: EdgeInsets.symmetric( - horizontal: 24.h, - vertical: 12.v, - ), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: const BorderRadius.all(Radius.circular(12)), - boxShadow: [ - BoxShadow( - color: Colors.grey.withOpacity(0.5), - spreadRadius: 2, - blurRadius: 5, - offset: Offset(0, 3), + return ListView.separated( + padding: EdgeInsets.all(8), + shrinkWrap: true, + physics: NeverScrollableScrollPhysics(), + separatorBuilder: (context, index) { + return SizedBox( + height: 2.v, + ); + }, + itemCount: state.calendarList.length, + itemBuilder: (context, index) { + Map diary = {}; + if (state.calendarList[index].diary is List) { + diary['status'] = 'Скоро'; + } else if (state.calendarList[index].diary is Map) { + diary = state.calendarList[index].diary as Map; + } + return InkWell( + borderRadius: BorderRadiusStyle.circleBorder8, + onTap: () => GoRouter.of(context).go( + '/diary-screen', + extra: diary['id'].toString(), ), - ], - ), - child: TableCalendar( - locale: 'ru_RU', - firstDay: DateTime.utc(2010, 10, 16), - lastDay: DateTime.utc(2030, 3, 14), - focusedDay: DateTime.now(), - startingDayOfWeek: StartingDayOfWeek.monday, - calendarBuilders: CalendarBuilders( - selectedBuilder: (context, day, focusedDay) => - _buildCellDate(context, day, focusedDay: focusedDay, state), - defaultBuilder: (context, day, focusedDay) => - _buildCellDate(context, day, state), - todayBuilder: (context, day, focusedDay) => - _buildCellDate(context, day, state), - ), - ), + child: Ink( + padding: EdgeInsets.all(8), + decoration: BoxDecoration( + borderRadius: BorderRadiusStyle.circleBorder8, + color: getBackgroundColor(diary['state']), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + formatDate(state.calendarList[index].date), + style: theme.textTheme.titleMedium, + ), + SizedBox(height: 2.v), + if (diary['state'] != null) + Row(children: [ + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: diary['state'] == 'finished' + ? Color.fromRGBO(1, 154, 62, 1) + : Color.fromRGBO(154, 74, 1, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + _getStateText(diary['state'] ?? ''), + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + SizedBox(width: 4), + if (diary['state'] == 'started') + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(13, 110, 253, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Заполнить отчет', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + if (diary['state'] == 'finished') + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(13, 110, 253, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Изменить отчет', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + ]), + if (state.calendarList[index].diary is List) + Container( + padding: + EdgeInsets.all(4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(108, 117, 125, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Cкоро', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + ], + ), + ), + ], + ), + ), + ); + }, ); } } -Widget _buildCellDate( - BuildContext context, DateTime day, CalendarStateLoaded state, - {DateTime? focusedDay}) { - final String dayString = day.toIso8601String().split('T').first; - final List calendarModels = state.calendarList; - - // Находим первую модель, соответствующую дате - final CalendarModel model = calendarModels.firstWhere( - (model) => model.date == dayString, - orElse: () => CalendarModel(date: dayString, diary: {})); - - Color? bgclr; // Объявляем переменную bgclr здесь - - final Map diary = model.diary as Map; - if (model.diary is Map) { - if (diary['state'] == "started") { - bgclr = Colors.grey; - } else if (diary['state'] == "finished") { - bgclr = Colors.green; - } else { - bgclr = Colors.white; - } - } else { - bgclr = Colors.white; // Значение по умолчанию, если diary не является Map +String _getStateText(String state) { + switch (state) { + case 'finished': + return 'Готово'; + case 'started': + return 'В процессе'; + default: + return ''; // Возвращаем пустую строку, если состояние не распознано + } +} + +String formatDate(String dateString) { + // Преобразуем строку в объект DateTime + DateTime dateTime = DateTime.parse(dateString); + + // Форматируем дату + String formattedDate = DateFormat('d MMMM', 'ru_RU').format(dateTime); + + // Возвращаем результат в нужном формате + return '$formattedDate'; +} + +Color getBackgroundColor(String? status) { + switch (status) { + case 'finished': + return Color.fromRGBO(1, 154, 62, .1); + case 'started': + return Color.fromRGBO(154, 74, 1, .1); + default: + return Color.fromRGBO(126, 136, 151, .1); } - - return GestureDetector( - onTap: () => GoRouter.of(context).pushNamed( - 'diaryScreen', - extra: diary['id'], - ), - child: Container( - margin: const EdgeInsets.all(5), - alignment: Alignment.center, - decoration: BoxDecoration( - shape: (day == focusedDay) ? BoxShape.circle : BoxShape.rectangle, - color: bgclr, - borderRadius: (day == focusedDay) ? null : BorderRadius.circular(4), - ), - child: Text(day.day.toString(), style: TextStyle(color: Colors.black)), - )); } diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index b81dd21..9c18af5 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -16,7 +16,8 @@ part 'diary_event.dart'; class DiaryBloc extends Bloc { final DiaryRepository diaryRepository; - DiaryBloc({required this.diaryRepository}) : super(const DiaryState.loading()) { + DiaryBloc({required this.diaryRepository}) + : super(const DiaryState.loading()) { on(loadDiary); on(_changeSatiety); // пользователь нажимает на шкалу сытости on(_changeMood); // пользователь нажимает на шкалу настроения @@ -53,18 +54,33 @@ class DiaryBloc extends Bloc { final DiaryModel diary = await diaryRepository.getDiary(diaryID ?? 45); final Meal currentMeal = diary.meals[0]; - List portionList = [SelectionPopupModel(title: "gr"), SelectionPopupModel(title: "pcs")]; + List portionList = [ + SelectionPopupModel(title: "gr"), + SelectionPopupModel(title: "pcs") + ]; - final Map chartData = await diaryRepository.getChartData(diaryID ?? 45); - final Map dailyNutritionIntake = chartData['dailyNutritionIntake']!; - final Map dailyNutritionRecommendations = chartData['dailyNutritionRecommendation']!; - final double ccal = dailyNutritionIntake['energy']! / dailyNutritionRecommendations['energy']! * 50; - final double proteins = dailyNutritionIntake['proteins']! / dailyNutritionRecommendations['proteins']! * 50; - final double fats = dailyNutritionIntake['fats']! / dailyNutritionRecommendations['fats']! * 50; - final double carbs = dailyNutritionIntake['carbohydrates']! / dailyNutritionRecommendations['carbohydrates']! * 50; + final Map chartData = + await diaryRepository.getChartData(diaryID ?? 45); + print(chartData); + final Map dailyNutritionIntake = + chartData['dailyNutritionIntake']!; + final Map dailyNutritionRecommendations = + chartData['dailyNutritionRecommendation']!; + final double ccal = dailyNutritionIntake['energy']! / + dailyNutritionRecommendations['energy']! * + 100; + final double proteins = dailyNutritionIntake['proteins']! / + dailyNutritionRecommendations['proteins']! * + 100; + final double fats = dailyNutritionIntake['fats']! / + dailyNutritionRecommendations['fats']! * + 100; + final double carbs = dailyNutritionIntake['carbohydrates']! / + dailyNutritionRecommendations['carbohydrates']! * + 100; Color getColor(double value) { - if (value >= 99.1) { + if (value >= 49.1) { return Colors.red; } else { return Colors.blue; @@ -86,7 +102,6 @@ class DiaryBloc extends Bloc { SelectionPopupModel(title: "Прием пищи 5", id: 5), SelectionPopupModel(title: "Прием пищи 6", id: 6), ]; - emit(DiaryState.loaded( diary: diary, currentMeal: currentMeal, @@ -163,9 +178,11 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = currentState.copyWith(wakeupController: event.selectedTime); + var updatedState = + currentState.copyWith(wakeupController: event.selectedTime); final DateFormat formatter = DateFormat('HH:mm'); - final String wakeupString = formatter.format(DateTime(2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); + final String wakeupString = formatter.format(DateTime( + 2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); await diaryRepository.changeWakeup( currentState.diary.id, wakeupString, @@ -180,9 +197,11 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - var updatedState = currentState.copyWith(retireController: event.selectedTime); + var updatedState = + currentState.copyWith(retireController: event.selectedTime); final DateFormat formatter = DateFormat('HH:mm'); - final String retireString = formatter.format(DateTime(2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); + final String retireString = formatter.format(DateTime( + 2022, 1, 1, event.selectedTime.hour, event.selectedTime.minute)); await diaryRepository.changeRetire( currentState.diary.id, retireString, @@ -208,7 +227,8 @@ class DiaryBloc extends Bloc { ) async { if (state is DiaryStateLoaded) { final currentState = state as DiaryStateLoaded; - final Meal meal = currentState.diary.meals.firstWhere((meal) => meal.type == event.value.id); + final Meal meal = currentState.diary.meals + .firstWhere((meal) => meal.type == event.value.id); DiaryStateLoaded updatedState = currentState.copyWith( currentMeal: meal, portions: meal.portions, @@ -227,10 +247,12 @@ class DiaryBloc extends Bloc { if (state is DiaryStateLoaded) { var currentState = state as DiaryStateLoaded; - final Map> productNutritionalValues = await diaryRepository.inputProduct(event.input); + final Map> productNutritionalValues = + await diaryRepository.inputProduct(event.input); var updatedState = currentState.copyWith( product_nameController: TextEditingController(text: event.input), - autocompleteList: productNutritionalValues['product_nutritional_value'] ?? [], + autocompleteList: + productNutritionalValues['product_nutritional_value'] ?? [], ); if (event.input.length > 3) { updatedState = updatedState.copyWith(moderationExpanded: true); diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index e41d052..cd66fb0 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -23,7 +23,13 @@ import 'package:syncfusion_flutter_charts/charts.dart'; // ignore: must_be_immutable class DiaryScreen extends StatelessWidget { - DiaryScreen({Key? key}) : super(key: key); + final String? diaryID; + + const DiaryScreen({ + this.diaryID, + super.key, + }); + Widget build(BuildContext context) { return BlocBuilder( builder: (context, state) { @@ -141,7 +147,6 @@ class DiaryScreen extends StatelessWidget { alignment: Alignment.centerRight, widthFactor: 0.5, child: SfCircularChart( - legend: Legend(isVisible: false), series: [ RadialBarSeries( dataSource: state.chartData, @@ -153,30 +158,29 @@ class DiaryScreen extends StatelessWidget { ), ), )), - SizedBox(height: 16.0), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('Калории'), - Text('Белки'), - Text('Жиры'), Text('Углеводы'), + Text('Жиры'), + Text('Белки'), + Text('Калории'), ], ), Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( - '${state.chartData![0].nutrition.toStringAsFixed(1)}'), // Калории + '${state.chartData![3].nutrition.toStringAsFixed(0)}%'), // Калории Text( - '${state.chartData![1].nutrition.toStringAsFixed(1)}'), // Белки + '${state.chartData![2].nutrition.toStringAsFixed(0)}%'), // Белки Text( - '${state.chartData![2].nutrition.toStringAsFixed(1)}'), // Жиры + '${state.chartData![1].nutrition.toStringAsFixed(0)}%'), // Жиры Text( - '${state.chartData![3].nutrition.toStringAsFixed(1)}'), // Углеводы + '${state.chartData![0].nutrition.toStringAsFixed(0)}% '), // Углеводы ], ), ], -- 2.49.1 From 5ddaf42a5f4a6e6e852c547c5891861c9bc7f242 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 2 Aug 2024 18:08:39 +0300 Subject: [PATCH 101/110] feat(diary): Diary ID is passed on calendar click, new layouts for calendar, fixed nutrition chart --- lib/features/calendar/models/calendar_entry_model.dart | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/features/calendar/models/calendar_entry_model.dart b/lib/features/calendar/models/calendar_entry_model.dart index d9fa704..e0ce0d5 100644 --- a/lib/features/calendar/models/calendar_entry_model.dart +++ b/lib/features/calendar/models/calendar_entry_model.dart @@ -1,5 +1,3 @@ -import 'package:eatvio_app/core/app_export.dart'; - /// This class is used in the [userprofile_item_widget] screen. // ignore_for_file: must_be_immutable -- 2.49.1 From 45e796152c5a4bd8a3df978acab3a032cc8cbf17 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Tue, 6 Aug 2024 14:28:03 +0300 Subject: [PATCH 102/110] feat(calendar): Calendar to diary transition --- .../presentation/pages/calendar_screen.dart | 265 ++++++++++++------ .../diary/presentation/bloc/diary_bloc.dart | 103 ++++++- .../diary/presentation/bloc/diary_event.dart | 9 + .../diary/presentation/bloc/diary_state.dart | 4 +- .../bloc/diary_state.freezed.dart | 78 ++++-- .../presentation/pages/diary_screen.dart | 3 + 6 files changed, 346 insertions(+), 116 deletions(-) diff --git a/lib/features/calendar/presentation/pages/calendar_screen.dart b/lib/features/calendar/presentation/pages/calendar_screen.dart index 3824512..320ad2c 100644 --- a/lib/features/calendar/presentation/pages/calendar_screen.dart +++ b/lib/features/calendar/presentation/pages/calendar_screen.dart @@ -96,106 +96,199 @@ class CalendarScreen extends StatelessWidget { Map diary = {}; if (state.calendarList[index].diary is List) { diary['status'] = 'Скоро'; - } else if (state.calendarList[index].diary is Map) { - diary = state.calendarList[index].diary as Map; - } - return InkWell( - borderRadius: BorderRadiusStyle.circleBorder8, - onTap: () => GoRouter.of(context).go( - '/diary-screen', - extra: diary['id'].toString(), - ), - child: Ink( - padding: EdgeInsets.all(8), - decoration: BoxDecoration( - borderRadius: BorderRadiusStyle.circleBorder8, - color: getBackgroundColor(diary['state']), - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - formatDate(state.calendarList[index].date), - style: theme.textTheme.titleMedium, - ), - SizedBox(height: 2.v), - if (diary['state'] != null) - Row(children: [ + return InkWell( + borderRadius: BorderRadiusStyle.circleBorder8, + child: Ink( + padding: EdgeInsets.all(8), + decoration: BoxDecoration( + borderRadius: BorderRadiusStyle.circleBorder8, + color: getBackgroundColor(diary['state']), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + formatDate(state.calendarList[index].date), + style: theme.textTheme.titleMedium, + ), + SizedBox(height: 2.v), + if (diary['state'] != null) + Row(children: [ + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: diary['state'] == 'finished' + ? Color.fromRGBO(1, 154, 62, 1) + : Color.fromRGBO(154, 74, 1, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + _getStateText(diary['state'] ?? ''), + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + SizedBox(width: 4), + if (diary['state'] == 'started') + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(13, 110, 253, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Заполнить отчет', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + if (diary['state'] == 'finished') + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(13, 110, 253, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Изменить отчет', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + ]), + if (state.calendarList[index].diary is List) Container( padding: EdgeInsets.all( 4.0), // Отступы внутри контейнера decoration: BoxDecoration( - color: diary['state'] == 'finished' - ? Color.fromRGBO(1, 154, 62, 1) - : Color.fromRGBO(154, 74, 1, 1), + color: Color.fromRGBO(108, 117, 125, 1), borderRadius: BorderRadius.circular( 24.0), // Закругленные углы ), child: Text( - _getStateText(diary['state'] ?? ''), + 'Cкоро', style: CustomTextStyles .titleSmallBold, // Предполагается, что текст белый ), ), - SizedBox(width: 4), - if (diary['state'] == 'started') - Container( - padding: EdgeInsets.all( - 4.0), // Отступы внутри контейнера - decoration: BoxDecoration( - color: Color.fromRGBO(13, 110, 253, 1), - borderRadius: BorderRadius.circular( - 24.0), // Закругленные углы - ), - child: Text( - 'Заполнить отчет', - style: CustomTextStyles - .titleSmallBold, // Предполагается, что текст белый - ), - ), - if (diary['state'] == 'finished') - Container( - padding: EdgeInsets.all( - 4.0), // Отступы внутри контейнера - decoration: BoxDecoration( - color: Color.fromRGBO(13, 110, 253, 1), - borderRadius: BorderRadius.circular( - 24.0), // Закругленные углы - ), - child: Text( - 'Изменить отчет', - style: CustomTextStyles - .titleSmallBold, // Предполагается, что текст белый - ), - ), - ]), - if (state.calendarList[index].diary is List) - Container( - padding: - EdgeInsets.all(4.0), // Отступы внутри контейнера - decoration: BoxDecoration( - color: Color.fromRGBO(108, 117, 125, 1), - borderRadius: BorderRadius.circular( - 24.0), // Закругленные углы - ), - child: Text( - 'Cкоро', - style: CustomTextStyles - .titleSmallBold, // Предполагается, что текст белый - ), - ), - ], + ], + ), ), - ), - ], + ], + ), ), - ), - ); + ); + } else { + diary = state.calendarList[index].diary as Map; + return InkWell( + borderRadius: BorderRadiusStyle.circleBorder8, + onTap: () => GoRouter.of(context).go( + '/diary-screen', + extra: diary['id'].toString(), + ), + child: Ink( + padding: EdgeInsets.all(8), + decoration: BoxDecoration( + borderRadius: BorderRadiusStyle.circleBorder8, + color: getBackgroundColor(diary['state']), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + formatDate(state.calendarList[index].date), + style: theme.textTheme.titleMedium, + ), + SizedBox(height: 2.v), + if (diary['state'] != null) + Row(children: [ + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: diary['state'] == 'finished' + ? Color.fromRGBO(1, 154, 62, 1) + : Color.fromRGBO(154, 74, 1, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + _getStateText(diary['state'] ?? ''), + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + SizedBox(width: 4), + if (diary['state'] == 'started') + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(13, 110, 253, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Заполнить отчет', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + if (diary['state'] == 'finished') + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(13, 110, 253, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Изменить отчет', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + ]), + if (state.calendarList[index].diary is List) + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(108, 117, 125, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Cкоро', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + ], + ), + ), + ], + ), + ), + ); + } }, ); } diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index 9c18af5..379aaea 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -19,6 +19,7 @@ class DiaryBloc extends Bloc { DiaryBloc({required this.diaryRepository}) : super(const DiaryState.loading()) { on(loadDiary); + on(loadDiaryById); on(_changeSatiety); // пользователь нажимает на шкалу сытости on(_changeMood); // пользователь нажимает на шкалу настроения on(_changeMealTime); // пользовательяет времяа пиши @@ -61,26 +62,25 @@ class DiaryBloc extends Bloc { final Map chartData = await diaryRepository.getChartData(diaryID ?? 45); - print(chartData); final Map dailyNutritionIntake = chartData['dailyNutritionIntake']!; final Map dailyNutritionRecommendations = chartData['dailyNutritionRecommendation']!; final double ccal = dailyNutritionIntake['energy']! / dailyNutritionRecommendations['energy']! * - 100; + 50; final double proteins = dailyNutritionIntake['proteins']! / dailyNutritionRecommendations['proteins']! * - 100; + 50; final double fats = dailyNutritionIntake['fats']! / dailyNutritionRecommendations['fats']! * - 100; + 50; final double carbs = dailyNutritionIntake['carbohydrates']! / dailyNutritionRecommendations['carbohydrates']! * - 100; + 50; Color getColor(double value) { - if (value >= 49.1) { + if (value >= 99.1) { return Colors.red; } else { return Colors.blue; @@ -102,6 +102,97 @@ class DiaryBloc extends Bloc { SelectionPopupModel(title: "Прием пищи 5", id: 5), SelectionPopupModel(title: "Прием пищи 6", id: 6), ]; + + emit(DiaryState.loaded( + diary: diary, + currentMeal: currentMeal, + portions: currentMeal.portions, + portionList: portionList, + portionController: portionList[0], + mealList: mealList, + chartData: chartDataCounted, + selectedMood: currentMeal.mood, + selectedSatiety: currentMeal.satiety, + wakeupController: TimeOfDay.now(), + retireController: TimeOfDay.now(), + commentController: TextEditingController(), + product_nameController: TextEditingController(), + productQuantityController: TextEditingController(), + caloriesController: TextEditingController(), + fatsController: TextEditingController(), + proteinsController: TextEditingController(), + carbsController: TextEditingController(), + wakeupExpanded: false, + moderationExpanded: false, + moodExpanded: false, + isLoading: false, + isAdded: false, + autocompleteList: [], + recommendedChartValues: [1, 1, 1, 1], + consumedChartValues: [1, 1, 1, 1])); + } catch (e) { + emit(DiaryState.error(errorMessage: e.toString())); + } + } + + loadDiaryById( + LoadDiaryById event, + Emitter emit, + ) async { + emit(const DiaryState.loading()); + try { + final int diaryID = int.parse(event.id ?? "0"); + final DiaryModel diary = await diaryRepository.getDiary(diaryID); + final Meal currentMeal = diary.meals[0]; + + List portionList = [ + SelectionPopupModel(title: "gr"), + SelectionPopupModel(title: "pcs") + ]; + + final Map chartData = + await diaryRepository.getChartData(diaryID); + final Map dailyNutritionIntake = + chartData['dailyNutritionIntake']!; + final Map dailyNutritionRecommendations = + chartData['dailyNutritionRecommendation']!; + final double ccal = dailyNutritionIntake['energy']! / + dailyNutritionRecommendations['energy']! * + 50; + final double proteins = dailyNutritionIntake['proteins']! / + dailyNutritionRecommendations['proteins']! * + 50; + final double fats = dailyNutritionIntake['fats']! / + dailyNutritionRecommendations['fats']! * + 50; + final double carbs = dailyNutritionIntake['carbohydrates']! / + dailyNutritionRecommendations['carbohydrates']! * + 50; + + Color getColor(double value) { + if (value >= 99.1) { + return Colors.red; + } else { + return Colors.blue; + } + } + + final List chartDataCounted = [ + NutritionData('Калории', ccal, getColor(ccal)), + NutritionData('Белки', proteins, getColor(proteins)), + NutritionData('Жиры', fats, getColor(fats)), + NutritionData('Углеводы', carbs, getColor(carbs)), + ]; + + List mealList = [ + SelectionPopupModel(title: "Прием пищи 1", id: 1), + SelectionPopupModel(title: "Прием пищи 2", id: 2), + SelectionPopupModel(title: "Прием пищи 3", id: 3), + SelectionPopupModel(title: "Прием пищи 4", id: 4), + SelectionPopupModel(title: "Прием пищи 5", id: 5), + SelectionPopupModel(title: "Прием пищи 6", id: 6), + ]; + emit(DiaryState.loaded( diary: diary, currentMeal: currentMeal, diff --git a/lib/features/diary/presentation/bloc/diary_event.dart b/lib/features/diary/presentation/bloc/diary_event.dart index 490fa0c..4faa190 100644 --- a/lib/features/diary/presentation/bloc/diary_event.dart +++ b/lib/features/diary/presentation/bloc/diary_event.dart @@ -15,6 +15,15 @@ class LoadDiary extends DiaryEvent { List get props => []; } +class LoadDiaryById extends DiaryEvent { + LoadDiaryById( + this.id, + ); + final String? id; + @override + List get props => []; +} + class ChangeSatiety extends DiaryEvent { ChangeSatiety( this.selectedElement, diff --git a/lib/features/diary/presentation/bloc/diary_state.dart b/lib/features/diary/presentation/bloc/diary_state.dart index 9156576..0725991 100644 --- a/lib/features/diary/presentation/bloc/diary_state.dart +++ b/lib/features/diary/presentation/bloc/diary_state.dart @@ -13,7 +13,9 @@ part 'diary_state.freezed.dart'; abstract class DiaryState with _$DiaryState { const factory DiaryState() = _DiaryState; - const factory DiaryState.loading() = DiaryStateLoading; + const factory DiaryState.loading({ + int? id, + }) = DiaryStateLoading; const factory DiaryState.loaded({ required DiaryModel diary, diff --git a/lib/features/diary/presentation/bloc/diary_state.freezed.dart b/lib/features/diary/presentation/bloc/diary_state.freezed.dart index 99328a6..24dbb0a 100644 --- a/lib/features/diary/presentation/bloc/diary_state.freezed.dart +++ b/lib/features/diary/presentation/bloc/diary_state.freezed.dart @@ -19,7 +19,7 @@ mixin _$DiaryState { @optionalTypeArgs TResult when( TResult Function() $default, { - required TResult Function() loading, + required TResult Function(int? id) loading, required TResult Function( DiaryModel diary, String? diaryDate, @@ -56,7 +56,7 @@ mixin _$DiaryState { @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { - TResult? Function()? loading, + TResult? Function(int? id)? loading, TResult? Function( DiaryModel diary, String? diaryDate, @@ -93,7 +93,7 @@ mixin _$DiaryState { @optionalTypeArgs TResult maybeWhen( TResult Function()? $default, { - TResult Function()? loading, + TResult Function(int? id)? loading, TResult Function( DiaryModel diary, String? diaryDate, @@ -212,7 +212,7 @@ class _$DiaryStateImpl implements _DiaryState { @optionalTypeArgs TResult when( TResult Function() $default, { - required TResult Function() loading, + required TResult Function(int? id) loading, required TResult Function( DiaryModel diary, String? diaryDate, @@ -252,7 +252,7 @@ class _$DiaryStateImpl implements _DiaryState { @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { - TResult? Function()? loading, + TResult? Function(int? id)? loading, TResult? Function( DiaryModel diary, String? diaryDate, @@ -292,7 +292,7 @@ class _$DiaryStateImpl implements _DiaryState { @optionalTypeArgs TResult maybeWhen( TResult Function()? $default, { - TResult Function()? loading, + TResult Function(int? id)? loading, TResult Function( DiaryModel diary, String? diaryDate, @@ -379,6 +379,8 @@ abstract class _$$DiaryStateLoadingImplCopyWith<$Res> { factory _$$DiaryStateLoadingImplCopyWith(_$DiaryStateLoadingImpl value, $Res Function(_$DiaryStateLoadingImpl) then) = __$$DiaryStateLoadingImplCopyWithImpl<$Res>; + @useResult + $Res call({int? id}); } /// @nodoc @@ -388,32 +390,57 @@ class __$$DiaryStateLoadingImplCopyWithImpl<$Res> __$$DiaryStateLoadingImplCopyWithImpl(_$DiaryStateLoadingImpl _value, $Res Function(_$DiaryStateLoadingImpl) _then) : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = freezed, + }) { + return _then(_$DiaryStateLoadingImpl( + id: freezed == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int?, + )); + } } /// @nodoc class _$DiaryStateLoadingImpl implements DiaryStateLoading { - const _$DiaryStateLoadingImpl(); + const _$DiaryStateLoadingImpl({this.id}); + + @override + final int? id; @override String toString() { - return 'DiaryState.loading()'; + return 'DiaryState.loading(id: $id)'; } @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && other is _$DiaryStateLoadingImpl); + (other.runtimeType == runtimeType && + other is _$DiaryStateLoadingImpl && + (identical(other.id, id) || other.id == id)); } @override - int get hashCode => runtimeType.hashCode; + int get hashCode => Object.hash(runtimeType, id); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$DiaryStateLoadingImplCopyWith<_$DiaryStateLoadingImpl> get copyWith => + __$$DiaryStateLoadingImplCopyWithImpl<_$DiaryStateLoadingImpl>( + this, _$identity); @override @optionalTypeArgs TResult when( TResult Function() $default, { - required TResult Function() loading, + required TResult Function(int? id) loading, required TResult Function( DiaryModel diary, String? diaryDate, @@ -446,14 +473,14 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { loaded, required TResult Function(String errorMessage) error, }) { - return loading(); + return loading(id); } @override @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { - TResult? Function()? loading, + TResult? Function(int? id)? loading, TResult? Function( DiaryModel diary, String? diaryDate, @@ -486,14 +513,14 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { loaded, TResult? Function(String errorMessage)? error, }) { - return loading?.call(); + return loading?.call(id); } @override @optionalTypeArgs TResult maybeWhen( TResult Function()? $default, { - TResult Function()? loading, + TResult Function(int? id)? loading, TResult Function( DiaryModel diary, String? diaryDate, @@ -528,7 +555,7 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { required TResult orElse(), }) { if (loading != null) { - return loading(); + return loading(id); } return orElse(); } @@ -572,7 +599,12 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { } abstract class DiaryStateLoading implements DiaryState { - const factory DiaryStateLoading() = _$DiaryStateLoadingImpl; + const factory DiaryStateLoading({final int? id}) = _$DiaryStateLoadingImpl; + + int? get id; + @JsonKey(ignore: true) + _$$DiaryStateLoadingImplCopyWith<_$DiaryStateLoadingImpl> get copyWith => + throw _privateConstructorUsedError; } /// @nodoc @@ -1050,7 +1082,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { @optionalTypeArgs TResult when( TResult Function() $default, { - required TResult Function() loading, + required TResult Function(int? id) loading, required TResult Function( DiaryModel diary, String? diaryDate, @@ -1118,7 +1150,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { - TResult? Function()? loading, + TResult? Function(int? id)? loading, TResult? Function( DiaryModel diary, String? diaryDate, @@ -1186,7 +1218,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { @optionalTypeArgs TResult maybeWhen( TResult Function()? $default, { - TResult Function()? loading, + TResult Function(int? id)? loading, TResult Function( DiaryModel diary, String? diaryDate, @@ -1423,7 +1455,7 @@ class _$DiaryStateErrorImpl implements DiaryStateError { @optionalTypeArgs TResult when( TResult Function() $default, { - required TResult Function() loading, + required TResult Function(int? id) loading, required TResult Function( DiaryModel diary, String? diaryDate, @@ -1463,7 +1495,7 @@ class _$DiaryStateErrorImpl implements DiaryStateError { @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { - TResult? Function()? loading, + TResult? Function(int? id)? loading, TResult? Function( DiaryModel diary, String? diaryDate, @@ -1503,7 +1535,7 @@ class _$DiaryStateErrorImpl implements DiaryStateError { @optionalTypeArgs TResult maybeWhen( TResult Function()? $default, { - TResult Function()? loading, + TResult Function(int? id)? loading, TResult Function( DiaryModel diary, String? diaryDate, diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index cd66fb0..fb78189 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -31,6 +31,9 @@ class DiaryScreen extends StatelessWidget { }); Widget build(BuildContext context) { + if (diaryID != "0") { + context.read().add(LoadDiaryById(diaryID)); + } return BlocBuilder( builder: (context, state) { if (state is DiaryStateLoaded) { -- 2.49.1 From f4c6aebdffa6513b484b5059eba95652fe94b1b9 Mon Sep 17 00:00:00 2001 From: mso7nueh Date: Thu, 8 Aug 2024 10:39:53 +0300 Subject: [PATCH 103/110] feat(feed): add diets api and create blog post screen, fix status bar --- .../initialization_state.freezed.dart | 96 +- .../selection_popup_model.freezed.dart | 53 +- .../user_registration_model.freezed.dart | 183 +- .../user_registration_model.g.dart | 11 +- .../models/blog_post_model.freezed.dart | 81 +- .../blog_post/models/blog_post_model.g.dart | 6 +- .../bloc/blog_post_state.freezed.dart | 88 +- .../presentation/pages/blog_post_screen.dart | 2 +- .../services/blog_post_service.g.dart | 29 +- .../pages/blog_post_create_screen.dart | 154 +- .../new_messages_state.freezed.dart | 92 +- .../notifications_state.freezed.dart | 95 +- .../models/chat_message_model.freezed.dart | 73 +- .../chat/models/chat_message_model.g.dart | 8 +- .../models/chat_messages_model.freezed.dart | 70 +- .../chat/models/chat_messages_model.g.dart | 12 +- .../chat/models/chat_meta_model.freezed.dart | 54 +- .../chat/models/chat_meta_model.g.dart | 6 +- .../chat/models/chat_room_model.freezed.dart | 78 +- .../chat/models/chat_room_model.g.dart | 12 +- .../chat_room_settings_model.freezed.dart | 78 +- .../models/chat_room_settings_model.g.dart | 8 +- .../chat/models/chat_user_model.freezed.dart | 78 +- .../chat/models/chat_user_model.g.dart | 6 +- .../models/websocket_info_model.freezed.dart | 81 +- .../chat/models/websocket_info_model.g.dart | 8 +- .../chat_room_state.freezed.dart | 171 +- .../chat/presentation/pages/chat_screen.dart | 14 +- .../chat_select_screen/chat_search_view.dart | 8 +- .../chat_select_screen.dart | 2 +- .../widgets/chat_entry_widget.dart | 4 +- .../widgets/chat_bubble_widget.dart | 4 +- .../chat/services/chat_service.g.dart | 82 +- lib/features/diary/models/meal.freezed.dart | 136 +- lib/features/diary/models/meal.g.dart | 3 +- lib/features/diary/models/photo.freezed.dart | 62 +- lib/features/diary/models/photo.g.dart | 3 +- .../diary/models/portion.freezed.dart | 58 +- .../diary/models/product.freezed.dart | 30 +- .../presentation/pages/diary_screen.dart | 2 +- .../feed/models/diets_pagination_model.dart | 133 ++ .../diets_pagination_model.freezed.dart | 2026 +++++++++++++++++ .../feed/models/diets_pagination_model.g.dart | 167 ++ .../models/feed_blog_post_model.freezed.dart | 70 +- .../feed/models/feed_blog_post_model.g.dart | 8 +- ...feed_blog_post_settings_model.freezed.dart | 69 +- .../feed_blog_post_settings_model.g.dart | 6 +- lib/features/feed/models/recipes_model.dart | 12 +- .../feed/models/recipes_model.freezed.dart | 334 +-- lib/features/feed/models/recipes_model.g.dart | 31 +- .../feed/models/recipes_pagination_model.dart | 22 +- .../recipes_pagination_model.freezed.dart | 326 +-- .../models/recipes_pagination_model.g.dart | 34 +- .../bloc/feed_cubit/feed_state.freezed.dart | 102 +- .../recipes_cubit/recipes_state.freezed.dart | 96 +- .../feed/presentation/pages/feed_screen.dart | 9 +- .../feed/repositories/feed_repository.dart | 9 + lib/features/feed/services/feed_service.dart | 4 + .../feed/services/feed_service.g.dart | 81 +- .../pages/about_recipes_screen.dart | 75 +- .../models/location_model.freezed.dart | 71 +- .../registration/models/location_model.g.dart | 9 +- .../registration_state.freezed.dart | 41 +- .../services/registration_service.g.dart | 82 +- .../my_profile_screen/my_profile_screen.dart | 2 +- lib/theme/theme_helper.dart | 4 + pubspec.yaml | 6 +- 67 files changed, 4253 insertions(+), 1617 deletions(-) create mode 100644 lib/features/feed/models/diets_pagination_model.dart create mode 100644 lib/features/feed/models/diets_pagination_model.freezed.dart create mode 100644 lib/features/feed/models/diets_pagination_model.g.dart diff --git a/lib/core/initialization_cubit/initialization_state.freezed.dart b/lib/core/initialization_cubit/initialization_state.freezed.dart index 5d54500..3364e44 100644 --- a/lib/core/initialization_cubit/initialization_state.freezed.dart +++ b/lib/core/initialization_cubit/initialization_state.freezed.dart @@ -24,7 +24,6 @@ mixin _$InitializationState { required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; - @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { @@ -71,31 +70,36 @@ mixin _$InitializationState { /// @nodoc abstract class $InitializationStateCopyWith<$Res> { - factory $InitializationStateCopyWith(InitializationState value, $Res Function(InitializationState) then) = + factory $InitializationStateCopyWith( + InitializationState value, $Res Function(InitializationState) then) = _$InitializationStateCopyWithImpl<$Res, InitializationState>; } /// @nodoc -class _$InitializationStateCopyWithImpl<$Res, $Val extends InitializationState> implements $InitializationStateCopyWith<$Res> { +class _$InitializationStateCopyWithImpl<$Res, $Val extends InitializationState> + implements $InitializationStateCopyWith<$Res> { _$InitializationStateCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; } /// @nodoc abstract class _$$InitializationStateImplCopyWith<$Res> { - factory _$$InitializationStateImplCopyWith(_$InitializationStateImpl value, $Res Function(_$InitializationStateImpl) then) = + factory _$$InitializationStateImplCopyWith(_$InitializationStateImpl value, + $Res Function(_$InitializationStateImpl) then) = __$$InitializationStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$InitializationStateImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateImpl> +class __$$InitializationStateImplCopyWithImpl<$Res> + extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateImpl> implements _$$InitializationStateImplCopyWith<$Res> { - __$$InitializationStateImplCopyWithImpl(_$InitializationStateImpl _value, $Res Function(_$InitializationStateImpl) _then) : super(_value, _then); + __$$InitializationStateImplCopyWithImpl(_$InitializationStateImpl _value, + $Res Function(_$InitializationStateImpl) _then) + : super(_value, _then); } /// @nodoc @@ -110,7 +114,9 @@ class _$InitializationStateImpl implements _InitializationState { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$InitializationStateImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$InitializationStateImpl); } @override @@ -197,14 +203,20 @@ abstract class _InitializationState implements InitializationState { /// @nodoc abstract class _$$InitializationStateLoadingImplCopyWith<$Res> { - factory _$$InitializationStateLoadingImplCopyWith(_$InitializationStateLoadingImpl value, $Res Function(_$InitializationStateLoadingImpl) then) = + factory _$$InitializationStateLoadingImplCopyWith( + _$InitializationStateLoadingImpl value, + $Res Function(_$InitializationStateLoadingImpl) then) = __$$InitializationStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$InitializationStateLoadingImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateLoadingImpl> +class __$$InitializationStateLoadingImplCopyWithImpl<$Res> + extends _$InitializationStateCopyWithImpl<$Res, + _$InitializationStateLoadingImpl> implements _$$InitializationStateLoadingImplCopyWith<$Res> { - __$$InitializationStateLoadingImplCopyWithImpl(_$InitializationStateLoadingImpl _value, $Res Function(_$InitializationStateLoadingImpl) _then) + __$$InitializationStateLoadingImplCopyWithImpl( + _$InitializationStateLoadingImpl _value, + $Res Function(_$InitializationStateLoadingImpl) _then) : super(_value, _then); } @@ -220,7 +232,9 @@ class _$InitializationStateLoadingImpl implements InitializationStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$InitializationStateLoadingImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$InitializationStateLoadingImpl); } @override @@ -307,17 +321,22 @@ abstract class InitializationStateLoading implements InitializationState { /// @nodoc abstract class _$$InitializationStateSuccessImplCopyWith<$Res> { - factory _$$InitializationStateSuccessImplCopyWith(_$InitializationStateSuccessImpl value, $Res Function(_$InitializationStateSuccessImpl) then) = + factory _$$InitializationStateSuccessImplCopyWith( + _$InitializationStateSuccessImpl value, + $Res Function(_$InitializationStateSuccessImpl) then) = __$$InitializationStateSuccessImplCopyWithImpl<$Res>; - @useResult $Res call({PusherChannelsClient client}); } /// @nodoc -class __$$InitializationStateSuccessImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateSuccessImpl> +class __$$InitializationStateSuccessImplCopyWithImpl<$Res> + extends _$InitializationStateCopyWithImpl<$Res, + _$InitializationStateSuccessImpl> implements _$$InitializationStateSuccessImplCopyWith<$Res> { - __$$InitializationStateSuccessImplCopyWithImpl(_$InitializationStateSuccessImpl _value, $Res Function(_$InitializationStateSuccessImpl) _then) + __$$InitializationStateSuccessImplCopyWithImpl( + _$InitializationStateSuccessImpl _value, + $Res Function(_$InitializationStateSuccessImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -350,7 +369,9 @@ class _$InitializationStateSuccessImpl implements InitializationStateSuccess { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && other is _$InitializationStateSuccessImpl && (identical(other.client, client) || other.client == client)); + (other.runtimeType == runtimeType && + other is _$InitializationStateSuccessImpl && + (identical(other.client, client) || other.client == client)); } @override @@ -359,8 +380,9 @@ class _$InitializationStateSuccessImpl implements InitializationStateSuccess { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> get copyWith => - __$$InitializationStateSuccessImplCopyWithImpl<_$InitializationStateSuccessImpl>(this, _$identity); + _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> + get copyWith => __$$InitializationStateSuccessImplCopyWithImpl< + _$InitializationStateSuccessImpl>(this, _$identity); @override @optionalTypeArgs @@ -438,27 +460,34 @@ class _$InitializationStateSuccessImpl implements InitializationStateSuccess { } abstract class InitializationStateSuccess implements InitializationState { - const factory InitializationStateSuccess({required final PusherChannelsClient client}) = _$InitializationStateSuccessImpl; + const factory InitializationStateSuccess( + {required final PusherChannelsClient client}) = + _$InitializationStateSuccessImpl; PusherChannelsClient get client; - @JsonKey(ignore: true) - _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> get copyWith => throw _privateConstructorUsedError; + _$$InitializationStateSuccessImplCopyWith<_$InitializationStateSuccessImpl> + get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$InitializationStateErrorImplCopyWith<$Res> { - factory _$$InitializationStateErrorImplCopyWith(_$InitializationStateErrorImpl value, $Res Function(_$InitializationStateErrorImpl) then) = + factory _$$InitializationStateErrorImplCopyWith( + _$InitializationStateErrorImpl value, + $Res Function(_$InitializationStateErrorImpl) then) = __$$InitializationStateErrorImplCopyWithImpl<$Res>; - @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$InitializationStateErrorImplCopyWithImpl<$Res> extends _$InitializationStateCopyWithImpl<$Res, _$InitializationStateErrorImpl> +class __$$InitializationStateErrorImplCopyWithImpl<$Res> + extends _$InitializationStateCopyWithImpl<$Res, + _$InitializationStateErrorImpl> implements _$$InitializationStateErrorImplCopyWith<$Res> { - __$$InitializationStateErrorImplCopyWithImpl(_$InitializationStateErrorImpl _value, $Res Function(_$InitializationStateErrorImpl) _then) + __$$InitializationStateErrorImplCopyWithImpl( + _$InitializationStateErrorImpl _value, + $Res Function(_$InitializationStateErrorImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -493,7 +522,8 @@ class _$InitializationStateErrorImpl implements InitializationStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$InitializationStateErrorImpl && - (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); } @override @@ -502,8 +532,9 @@ class _$InitializationStateErrorImpl implements InitializationStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> get copyWith => - __$$InitializationStateErrorImplCopyWithImpl<_$InitializationStateErrorImpl>(this, _$identity); + _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> + get copyWith => __$$InitializationStateErrorImplCopyWithImpl< + _$InitializationStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -581,10 +612,11 @@ class _$InitializationStateErrorImpl implements InitializationStateError { } abstract class InitializationStateError implements InitializationState { - const factory InitializationStateError({required final String errorMessage}) = _$InitializationStateErrorImpl; + const factory InitializationStateError({required final String errorMessage}) = + _$InitializationStateErrorImpl; String get errorMessage; - @JsonKey(ignore: true) - _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> get copyWith => throw _privateConstructorUsedError; + _$$InitializationStateErrorImplCopyWith<_$InitializationStateErrorImpl> + get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart b/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart index 79d30b4..917785c 100644 --- a/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart +++ b/lib/data/models/selectionPopupModel/selection_popup_model.freezed.dart @@ -17,33 +17,31 @@ final _privateConstructorUsedError = UnsupportedError( /// @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; + $SelectionPopupModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $SelectionPopupModelCopyWith<$Res> { - factory $SelectionPopupModelCopyWith(SelectionPopupModel value, $Res Function(SelectionPopupModel) then) = + 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> { +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; @@ -77,19 +75,23 @@ class _$SelectionPopupModelCopyWithImpl<$Res, $Val extends SelectionPopupModel> } /// @nodoc -abstract class _$$SelectionPopupModelImplCopyWith<$Res> implements $SelectionPopupModelCopyWith<$Res> { - factory _$$SelectionPopupModelImplCopyWith(_$SelectionPopupModelImpl value, $Res Function(_$SelectionPopupModelImpl) then) = +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> +class __$$SelectionPopupModelImplCopyWithImpl<$Res> + extends _$SelectionPopupModelCopyWithImpl<$Res, _$SelectionPopupModelImpl> implements _$$SelectionPopupModelImplCopyWith<$Res> { - __$$SelectionPopupModelImplCopyWithImpl(_$SelectionPopupModelImpl _value, $Res Function(_$SelectionPopupModelImpl) _then) : super(_value, _then); + __$$SelectionPopupModelImplCopyWithImpl(_$SelectionPopupModelImpl _value, + $Res Function(_$SelectionPopupModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -123,7 +125,8 @@ class __$$SelectionPopupModelImplCopyWithImpl<$Res> extends _$SelectionPopupMode /// @nodoc class _$SelectionPopupModelImpl implements _SelectionPopupModel { - const _$SelectionPopupModelImpl({this.id, required this.title, this.value, this.isSelected = false}); + const _$SelectionPopupModelImpl( + {this.id, required this.title, this.value, this.isSelected = false}); @override final int? id; @@ -148,35 +151,39 @@ class _$SelectionPopupModelImpl implements _SelectionPopupModel { (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)); + (identical(other.isSelected, isSelected) || + other.isSelected == isSelected)); } @override - int get hashCode => Object.hash(runtimeType, id, title, const DeepCollectionEquality().hash(value), isSelected); + 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); + __$$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; + 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; + _$$SelectionPopupModelImplCopyWith<_$SelectionPopupModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart b/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart index 4950c89..4a15327 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.freezed.dart @@ -14,7 +14,8 @@ 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) { +UserRegistrationSheet _$UserRegistrationSheetFromJson( + Map json) { return _UserRegistrationSheet.fromJson(json); } @@ -22,88 +23,62 @@ UserRegistrationSheet _$UserRegistrationSheetFromJson(Map json) mixin _$UserRegistrationSheet { @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 location => throw _privateConstructorUsedError; - @JsonKey(name: 'response_body') String get responseBody => 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; + $UserRegistrationSheetCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $UserRegistrationSheetCopyWith<$Res> { - factory $UserRegistrationSheetCopyWith(UserRegistrationSheet value, $Res Function(UserRegistrationSheet) then) = + factory $UserRegistrationSheetCopyWith(UserRegistrationSheet value, + $Res Function(UserRegistrationSheet) then) = _$UserRegistrationSheetCopyWithImpl<$Res, UserRegistrationSheet>; - @useResult $Res call( {@JsonKey(name: 'first_name') String firstName, @@ -136,12 +111,13 @@ abstract class $UserRegistrationSheetCopyWith<$Res> { } /// @nodoc -class _$UserRegistrationSheetCopyWithImpl<$Res, $Val extends UserRegistrationSheet> implements $UserRegistrationSheetCopyWith<$Res> { +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; @@ -290,10 +266,12 @@ class _$UserRegistrationSheetCopyWithImpl<$Res, $Val extends UserRegistrationShe } /// @nodoc -abstract class _$$UserRegistrationSheetImplCopyWith<$Res> implements $UserRegistrationSheetCopyWith<$Res> { - factory _$$UserRegistrationSheetImplCopyWith(_$UserRegistrationSheetImpl value, $Res Function(_$UserRegistrationSheetImpl) then) = +abstract class _$$UserRegistrationSheetImplCopyWith<$Res> + implements $UserRegistrationSheetCopyWith<$Res> { + factory _$$UserRegistrationSheetImplCopyWith( + _$UserRegistrationSheetImpl value, + $Res Function(_$UserRegistrationSheetImpl) then) = __$$UserRegistrationSheetImplCopyWithImpl<$Res>; - @override @useResult $Res call( @@ -327,9 +305,13 @@ abstract class _$$UserRegistrationSheetImplCopyWith<$Res> implements $UserRegist } /// @nodoc -class __$$UserRegistrationSheetImplCopyWithImpl<$Res> extends _$UserRegistrationSheetCopyWithImpl<$Res, _$UserRegistrationSheetImpl> +class __$$UserRegistrationSheetImplCopyWithImpl<$Res> + extends _$UserRegistrationSheetCopyWithImpl<$Res, + _$UserRegistrationSheetImpl> implements _$$UserRegistrationSheetImplCopyWith<$Res> { - __$$UserRegistrationSheetImplCopyWithImpl(_$UserRegistrationSheetImpl _value, $Res Function(_$UserRegistrationSheetImpl) _then) : super(_value, _then); + __$$UserRegistrationSheetImplCopyWithImpl(_$UserRegistrationSheetImpl _value, + $Res Function(_$UserRegistrationSheetImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -483,7 +465,8 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @JsonKey(name: 'last_name') required this.lastName, required this.email, required this.password, - @JsonKey(name: 'password_confirmation') required this.passwordConfirmation, + @JsonKey(name: 'password_confirmation') + required this.passwordConfirmation, @JsonKey(name: 'terms') this.termsAccepted = 'accepted', required this.birthdate, required this.gender, @@ -507,7 +490,8 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @JsonKey(name: 'additional_info') required this.additionalInfo, @JsonKey(name: 'activity_coefficient') this.activityCoefficient = 1.2}); - factory _$UserRegistrationSheetImpl.fromJson(Map json) => _$$UserRegistrationSheetImplFromJson(json); + factory _$UserRegistrationSheetImpl.fromJson(Map json) => + _$$UserRegistrationSheetImplFromJson(json); @override @JsonKey(name: 'first_name') @@ -593,33 +577,54 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { return identical(this, other) || (other.runtimeType == runtimeType && other is _$UserRegistrationSheetImpl && - (identical(other.firstName, firstName) || other.firstName == firstName) && - (identical(other.lastName, lastName) || other.lastName == lastName) && + (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.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.location, location) || other.location == location) && - (identical(other.responseBody, responseBody) || other.responseBody == responseBody) && + (identical(other.location, location) || + other.location == location) && + (identical(other.responseBody, responseBody) || + other.responseBody == responseBody) && (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.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)); + (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) @@ -658,8 +663,9 @@ class _$UserRegistrationSheetImpl implements _UserRegistrationSheet { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$UserRegistrationSheetImplCopyWith<_$UserRegistrationSheetImpl> get copyWith => - __$$UserRegistrationSheetImplCopyWithImpl<_$UserRegistrationSheetImpl>(this, _$identity); + _$$UserRegistrationSheetImplCopyWith<_$UserRegistrationSheetImpl> + get copyWith => __$$UserRegistrationSheetImplCopyWithImpl< + _$UserRegistrationSheetImpl>(this, _$identity); @override Map toJson() { @@ -675,7 +681,8 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { @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: 'password_confirmation') + required final String passwordConfirmation, @JsonKey(name: 'terms') final String termsAccepted, required final String birthdate, required final String gender, @@ -684,124 +691,104 @@ abstract class _UserRegistrationSheet implements UserRegistrationSheet { 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: '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: '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: '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; + @JsonKey(name: 'activity_coefficient') + final double activityCoefficient}) = _$UserRegistrationSheetImpl; - factory _UserRegistrationSheet.fromJson(Map json) = _$UserRegistrationSheetImpl.fromJson; + factory _UserRegistrationSheet.fromJson(Map json) = + _$UserRegistrationSheetImpl.fromJson; @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 location; - @override @JsonKey(name: 'response_body') String get responseBody; - @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; + _$$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 index 7690dbb..9500e91 100644 --- a/lib/data/models/userRegistrationModel/user_registration_model.g.dart +++ b/lib/data/models/userRegistrationModel/user_registration_model.g.dart @@ -6,7 +6,9 @@ part of 'user_registration_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson(Map json) => _$UserRegistrationSheetImpl( +_$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson( + Map json) => + _$UserRegistrationSheetImpl( firstName: json['first_name'] as String, lastName: json['last_name'] as String, email: json['email'] as String, @@ -33,10 +35,13 @@ _$UserRegistrationSheetImpl _$$UserRegistrationSheetImplFromJson(Map _$$UserRegistrationSheetImplToJson(_$UserRegistrationSheetImpl instance) => { +Map _$$UserRegistrationSheetImplToJson( + _$UserRegistrationSheetImpl instance) => + { 'first_name': instance.firstName, 'last_name': instance.lastName, 'email': instance.email, diff --git a/lib/features/blog_post/models/blog_post_model.freezed.dart b/lib/features/blog_post/models/blog_post_model.freezed.dart index 058bff6..7c0a750 100644 --- a/lib/features/blog_post/models/blog_post_model.freezed.dart +++ b/lib/features/blog_post/models/blog_post_model.freezed.dart @@ -21,38 +21,30 @@ BlogPostModel _$BlogPostModelFromJson(Map json) { /// @nodoc mixin _$BlogPostModel { int get id => throw _privateConstructorUsedError; - String get state => throw _privateConstructorUsedError; - String? get image => throw _privateConstructorUsedError; - String get description => throw _privateConstructorUsedError; - String? get author_name => throw _privateConstructorUsedError; - String? get author_avatar_path => throw _privateConstructorUsedError; - @JsonKey(name: "youtube_url") String get youtubeUrl => throw _privateConstructorUsedError; - @JsonKey(name: "created_at") DateTime get createdAt => throw _privateConstructorUsedError; - @JsonKey(name: "updated_at") DateTime get updatedAt => throw _privateConstructorUsedError; - String get title => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $BlogPostModelCopyWith get copyWith => throw _privateConstructorUsedError; + $BlogPostModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $BlogPostModelCopyWith<$Res> { - factory $BlogPostModelCopyWith(BlogPostModel value, $Res Function(BlogPostModel) then) = _$BlogPostModelCopyWithImpl<$Res, BlogPostModel>; - + factory $BlogPostModelCopyWith( + BlogPostModel value, $Res Function(BlogPostModel) then) = + _$BlogPostModelCopyWithImpl<$Res, BlogPostModel>; @useResult $Res call( {int id, @@ -68,12 +60,12 @@ abstract class $BlogPostModelCopyWith<$Res> { } /// @nodoc -class _$BlogPostModelCopyWithImpl<$Res, $Val extends BlogPostModel> implements $BlogPostModelCopyWith<$Res> { +class _$BlogPostModelCopyWithImpl<$Res, $Val extends BlogPostModel> + implements $BlogPostModelCopyWith<$Res> { _$BlogPostModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -137,9 +129,11 @@ class _$BlogPostModelCopyWithImpl<$Res, $Val extends BlogPostModel> implements $ } /// @nodoc -abstract class _$$BlogPostModelImplCopyWith<$Res> implements $BlogPostModelCopyWith<$Res> { - factory _$$BlogPostModelImplCopyWith(_$BlogPostModelImpl value, $Res Function(_$BlogPostModelImpl) then) = __$$BlogPostModelImplCopyWithImpl<$Res>; - +abstract class _$$BlogPostModelImplCopyWith<$Res> + implements $BlogPostModelCopyWith<$Res> { + factory _$$BlogPostModelImplCopyWith( + _$BlogPostModelImpl value, $Res Function(_$BlogPostModelImpl) then) = + __$$BlogPostModelImplCopyWithImpl<$Res>; @override @useResult $Res call( @@ -156,8 +150,12 @@ abstract class _$$BlogPostModelImplCopyWith<$Res> implements $BlogPostModelCopyW } /// @nodoc -class __$$BlogPostModelImplCopyWithImpl<$Res> extends _$BlogPostModelCopyWithImpl<$Res, _$BlogPostModelImpl> implements _$$BlogPostModelImplCopyWith<$Res> { - __$$BlogPostModelImplCopyWithImpl(_$BlogPostModelImpl _value, $Res Function(_$BlogPostModelImpl) _then) : super(_value, _then); +class __$$BlogPostModelImplCopyWithImpl<$Res> + extends _$BlogPostModelCopyWithImpl<$Res, _$BlogPostModelImpl> + implements _$$BlogPostModelImplCopyWith<$Res> { + __$$BlogPostModelImplCopyWithImpl( + _$BlogPostModelImpl _value, $Res Function(_$BlogPostModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -233,7 +231,8 @@ class _$BlogPostModelImpl implements _BlogPostModel { @JsonKey(name: "updated_at") required this.updatedAt, required this.title}); - factory _$BlogPostModelImpl.fromJson(Map json) => _$$BlogPostModelImplFromJson(json); + factory _$BlogPostModelImpl.fromJson(Map json) => + _$$BlogPostModelImplFromJson(json); @override final int id; @@ -272,23 +271,31 @@ class _$BlogPostModelImpl implements _BlogPostModel { (identical(other.id, id) || other.id == id) && (identical(other.state, state) || other.state == state) && (identical(other.image, image) || other.image == image) && - (identical(other.description, description) || other.description == description) && - (identical(other.author_name, author_name) || other.author_name == author_name) && - (identical(other.author_avatar_path, author_avatar_path) || other.author_avatar_path == author_avatar_path) && - (identical(other.youtubeUrl, youtubeUrl) || other.youtubeUrl == youtubeUrl) && - (identical(other.createdAt, createdAt) || other.createdAt == createdAt) && - (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt) && + (identical(other.description, description) || + other.description == description) && + (identical(other.author_name, author_name) || + other.author_name == author_name) && + (identical(other.author_avatar_path, author_avatar_path) || + other.author_avatar_path == author_avatar_path) && + (identical(other.youtubeUrl, youtubeUrl) || + other.youtubeUrl == youtubeUrl) && + (identical(other.createdAt, createdAt) || + other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt) && (identical(other.title, title) || other.title == title)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, state, image, description, author_name, author_avatar_path, youtubeUrl, createdAt, updatedAt, title); + int get hashCode => Object.hash(runtimeType, id, state, image, description, + author_name, author_avatar_path, youtubeUrl, createdAt, updatedAt, title); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => __$$BlogPostModelImplCopyWithImpl<_$BlogPostModelImpl>(this, _$identity); + _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => + __$$BlogPostModelImplCopyWithImpl<_$BlogPostModelImpl>(this, _$identity); @override Map toJson() { @@ -311,42 +318,34 @@ abstract class _BlogPostModel implements BlogPostModel { @JsonKey(name: "updated_at") required final DateTime updatedAt, required final String title}) = _$BlogPostModelImpl; - factory _BlogPostModel.fromJson(Map json) = _$BlogPostModelImpl.fromJson; + factory _BlogPostModel.fromJson(Map json) = + _$BlogPostModelImpl.fromJson; @override int get id; - @override String get state; - @override String? get image; - @override String get description; - @override String? get author_name; - @override String? get author_avatar_path; - @override @JsonKey(name: "youtube_url") String get youtubeUrl; - @override @JsonKey(name: "created_at") DateTime get createdAt; - @override @JsonKey(name: "updated_at") DateTime get updatedAt; - @override String get title; - @override @JsonKey(ignore: true) - _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$BlogPostModelImplCopyWith<_$BlogPostModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/blog_post/models/blog_post_model.g.dart b/lib/features/blog_post/models/blog_post_model.g.dart index 137652f..2e3233c 100644 --- a/lib/features/blog_post/models/blog_post_model.g.dart +++ b/lib/features/blog_post/models/blog_post_model.g.dart @@ -6,7 +6,8 @@ part of 'blog_post_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$BlogPostModelImpl _$$BlogPostModelImplFromJson(Map json) => _$BlogPostModelImpl( +_$BlogPostModelImpl _$$BlogPostModelImplFromJson(Map json) => + _$BlogPostModelImpl( id: (json['id'] as num).toInt(), state: json['state'] as String, image: json['image'] as String?, @@ -19,7 +20,8 @@ _$BlogPostModelImpl _$$BlogPostModelImplFromJson(Map json) => _ title: json['title'] as String, ); -Map _$$BlogPostModelImplToJson(_$BlogPostModelImpl instance) => { +Map _$$BlogPostModelImplToJson(_$BlogPostModelImpl instance) => + { 'id': instance.id, 'state': instance.state, 'image': instance.image, diff --git a/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart b/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart index 3776000..4f99a3c 100644 --- a/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart +++ b/lib/features/blog_post/presentation/bloc/blog_post_state.freezed.dart @@ -24,7 +24,6 @@ mixin _$BlogPostState { required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; - @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { @@ -71,28 +70,36 @@ mixin _$BlogPostState { /// @nodoc abstract class $BlogPostStateCopyWith<$Res> { - factory $BlogPostStateCopyWith(BlogPostState value, $Res Function(BlogPostState) then) = _$BlogPostStateCopyWithImpl<$Res, BlogPostState>; + factory $BlogPostStateCopyWith( + BlogPostState value, $Res Function(BlogPostState) then) = + _$BlogPostStateCopyWithImpl<$Res, BlogPostState>; } /// @nodoc -class _$BlogPostStateCopyWithImpl<$Res, $Val extends BlogPostState> implements $BlogPostStateCopyWith<$Res> { +class _$BlogPostStateCopyWithImpl<$Res, $Val extends BlogPostState> + implements $BlogPostStateCopyWith<$Res> { _$BlogPostStateCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; } /// @nodoc abstract class _$$BlogPostStateImplCopyWith<$Res> { - factory _$$BlogPostStateImplCopyWith(_$BlogPostStateImpl value, $Res Function(_$BlogPostStateImpl) then) = __$$BlogPostStateImplCopyWithImpl<$Res>; + factory _$$BlogPostStateImplCopyWith( + _$BlogPostStateImpl value, $Res Function(_$BlogPostStateImpl) then) = + __$$BlogPostStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$BlogPostStateImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateImpl> implements _$$BlogPostStateImplCopyWith<$Res> { - __$$BlogPostStateImplCopyWithImpl(_$BlogPostStateImpl _value, $Res Function(_$BlogPostStateImpl) _then) : super(_value, _then); +class __$$BlogPostStateImplCopyWithImpl<$Res> + extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateImpl> + implements _$$BlogPostStateImplCopyWith<$Res> { + __$$BlogPostStateImplCopyWithImpl( + _$BlogPostStateImpl _value, $Res Function(_$BlogPostStateImpl) _then) + : super(_value, _then); } /// @nodoc @@ -107,7 +114,8 @@ class _$BlogPostStateImpl implements _BlogPostState { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$BlogPostStateImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$BlogPostStateImpl); } @override @@ -194,14 +202,18 @@ abstract class _BlogPostState implements BlogPostState { /// @nodoc abstract class _$$BlogPostStateLoadingImplCopyWith<$Res> { - factory _$$BlogPostStateLoadingImplCopyWith(_$BlogPostStateLoadingImpl value, $Res Function(_$BlogPostStateLoadingImpl) then) = + factory _$$BlogPostStateLoadingImplCopyWith(_$BlogPostStateLoadingImpl value, + $Res Function(_$BlogPostStateLoadingImpl) then) = __$$BlogPostStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$BlogPostStateLoadingImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadingImpl> +class __$$BlogPostStateLoadingImplCopyWithImpl<$Res> + extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadingImpl> implements _$$BlogPostStateLoadingImplCopyWith<$Res> { - __$$BlogPostStateLoadingImplCopyWithImpl(_$BlogPostStateLoadingImpl _value, $Res Function(_$BlogPostStateLoadingImpl) _then) : super(_value, _then); + __$$BlogPostStateLoadingImplCopyWithImpl(_$BlogPostStateLoadingImpl _value, + $Res Function(_$BlogPostStateLoadingImpl) _then) + : super(_value, _then); } /// @nodoc @@ -216,7 +228,9 @@ class _$BlogPostStateLoadingImpl implements BlogPostStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$BlogPostStateLoadingImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$BlogPostStateLoadingImpl); } @override @@ -303,9 +317,9 @@ abstract class BlogPostStateLoading implements BlogPostState { /// @nodoc abstract class _$$BlogPostStateLoadedImplCopyWith<$Res> { - factory _$$BlogPostStateLoadedImplCopyWith(_$BlogPostStateLoadedImpl value, $Res Function(_$BlogPostStateLoadedImpl) then) = + factory _$$BlogPostStateLoadedImplCopyWith(_$BlogPostStateLoadedImpl value, + $Res Function(_$BlogPostStateLoadedImpl) then) = __$$BlogPostStateLoadedImplCopyWithImpl<$Res>; - @useResult $Res call({BlogPostModel blogPost}); @@ -313,9 +327,12 @@ abstract class _$$BlogPostStateLoadedImplCopyWith<$Res> { } /// @nodoc -class __$$BlogPostStateLoadedImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadedImpl> +class __$$BlogPostStateLoadedImplCopyWithImpl<$Res> + extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateLoadedImpl> implements _$$BlogPostStateLoadedImplCopyWith<$Res> { - __$$BlogPostStateLoadedImplCopyWithImpl(_$BlogPostStateLoadedImpl _value, $Res Function(_$BlogPostStateLoadedImpl) _then) : super(_value, _then); + __$$BlogPostStateLoadedImplCopyWithImpl(_$BlogPostStateLoadedImpl _value, + $Res Function(_$BlogPostStateLoadedImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -355,7 +372,10 @@ class _$BlogPostStateLoadedImpl implements BlogPostStateLoaded { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && other is _$BlogPostStateLoadedImpl && (identical(other.blogPost, blogPost) || other.blogPost == blogPost)); + (other.runtimeType == runtimeType && + other is _$BlogPostStateLoadedImpl && + (identical(other.blogPost, blogPost) || + other.blogPost == blogPost)); } @override @@ -365,7 +385,8 @@ class _$BlogPostStateLoadedImpl implements BlogPostStateLoaded { @override @pragma('vm:prefer-inline') _$$BlogPostStateLoadedImplCopyWith<_$BlogPostStateLoadedImpl> get copyWith => - __$$BlogPostStateLoadedImplCopyWithImpl<_$BlogPostStateLoadedImpl>(this, _$identity); + __$$BlogPostStateLoadedImplCopyWithImpl<_$BlogPostStateLoadedImpl>( + this, _$identity); @override @optionalTypeArgs @@ -443,27 +464,31 @@ class _$BlogPostStateLoadedImpl implements BlogPostStateLoaded { } abstract class BlogPostStateLoaded implements BlogPostState { - const factory BlogPostStateLoaded({required final BlogPostModel blogPost}) = _$BlogPostStateLoadedImpl; + const factory BlogPostStateLoaded({required final BlogPostModel blogPost}) = + _$BlogPostStateLoadedImpl; BlogPostModel get blogPost; - @JsonKey(ignore: true) - _$$BlogPostStateLoadedImplCopyWith<_$BlogPostStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; + _$$BlogPostStateLoadedImplCopyWith<_$BlogPostStateLoadedImpl> get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class _$$BlogPostStateErrorImplCopyWith<$Res> { - factory _$$BlogPostStateErrorImplCopyWith(_$BlogPostStateErrorImpl value, $Res Function(_$BlogPostStateErrorImpl) then) = + factory _$$BlogPostStateErrorImplCopyWith(_$BlogPostStateErrorImpl value, + $Res Function(_$BlogPostStateErrorImpl) then) = __$$BlogPostStateErrorImplCopyWithImpl<$Res>; - @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$BlogPostStateErrorImplCopyWithImpl<$Res> extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateErrorImpl> +class __$$BlogPostStateErrorImplCopyWithImpl<$Res> + extends _$BlogPostStateCopyWithImpl<$Res, _$BlogPostStateErrorImpl> implements _$$BlogPostStateErrorImplCopyWith<$Res> { - __$$BlogPostStateErrorImplCopyWithImpl(_$BlogPostStateErrorImpl _value, $Res Function(_$BlogPostStateErrorImpl) _then) : super(_value, _then); + __$$BlogPostStateErrorImplCopyWithImpl(_$BlogPostStateErrorImpl _value, + $Res Function(_$BlogPostStateErrorImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -497,7 +522,8 @@ class _$BlogPostStateErrorImpl implements BlogPostStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$BlogPostStateErrorImpl && - (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); } @override @@ -507,7 +533,8 @@ class _$BlogPostStateErrorImpl implements BlogPostStateError { @override @pragma('vm:prefer-inline') _$$BlogPostStateErrorImplCopyWith<_$BlogPostStateErrorImpl> get copyWith => - __$$BlogPostStateErrorImplCopyWithImpl<_$BlogPostStateErrorImpl>(this, _$identity); + __$$BlogPostStateErrorImplCopyWithImpl<_$BlogPostStateErrorImpl>( + this, _$identity); @override @optionalTypeArgs @@ -585,10 +612,11 @@ class _$BlogPostStateErrorImpl implements BlogPostStateError { } abstract class BlogPostStateError implements BlogPostState { - const factory BlogPostStateError({required final String errorMessage}) = _$BlogPostStateErrorImpl; + const factory BlogPostStateError({required final String errorMessage}) = + _$BlogPostStateErrorImpl; String get errorMessage; - @JsonKey(ignore: true) - _$$BlogPostStateErrorImplCopyWith<_$BlogPostStateErrorImpl> get copyWith => throw _privateConstructorUsedError; + _$$BlogPostStateErrorImplCopyWith<_$BlogPostStateErrorImpl> get copyWith => + throw _privateConstructorUsedError; } 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 c9f14dc..ad82dec 100644 --- a/lib/features/blog_post/presentation/pages/blog_post_screen.dart +++ b/lib/features/blog_post/presentation/pages/blog_post_screen.dart @@ -177,7 +177,7 @@ class BlogPostScreen extends StatelessWidget { style: theme.textTheme.bodyMedium, ), ), - SizedBox(height: 16.0), + SizedBox(height: 8), Row( children: [ Padding( 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 422f042..5ea30fc 100644 --- a/lib/features/blog_post/services/blog_post_service.g.dart +++ b/lib/features/blog_post/services/blog_post_service.g.dart @@ -24,28 +24,31 @@ class _BlogPostService implements BlogPostService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio + .fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/blogPosts/show/${id}', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/blogPosts/show/${id}', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = BlogPostModel.fromJson(_result.data!); return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && + !(requestOptions.responseType == ResponseType.bytes || + requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { 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 d829514..226bfa1 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,7 +1,6 @@ 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'; @@ -51,68 +50,58 @@ class _BlogPostCreateScreenState extends State { _buildBlogPostCreate(BuildContext context, BlogPostCreateLoadedState state) { return Scaffold( resizeToAvoidBottomInset: false, - body: Container( - width: double.maxFinite, - decoration: AppDecoration.fillGray, - child: ListView( + appBar: AppBar(), + floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, + floatingActionButton: SizedBox( + width: MediaQuery.of(context).size.width - 32, + child: FloatingActionButton.extended( + heroTag: 'nextButtonRegistration', + highlightElevation: 0, + elevation: 0, + focusElevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + backgroundColor: appTheme.blueA400, + onPressed: () => _submitForm(context, state.title!.text, state.description!.text, state.youtubeURL!.text), + label: Text( + 'Создать', + style: theme.textTheme.titleSmall, + ), + ), + ), + body: SingleChildScrollView( + padding: EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, 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: [ - Column( - children: [ - Text("Заголовок новости", style: theme.textTheme.bodyLarge), - CustomTextFormField( - controller: state.title, - validator: _validateTitle, - ), - SizedBox(height: 8.0), - Text("Ссылка на YouTube", style: theme.textTheme.bodyLarge), - CustomTextFormField( - controller: state.youtubeURL, - validator: _validateYouTubeLink, - ), - SizedBox(height: 8.0), - Text("Описание", style: theme.textTheme.bodyLarge), - CustomTextFormField( - controller: state.description, - validator: _validateDescription, - maxLines: 6, - ), - SizedBox(height: 16.0), - _buildAddPhoto(context, state), - SizedBox(height: 16.0), - // Add widget for image upload here - CustomOutlinedButton( - onPressed: () => _submitForm(context, state.title!.text, state.description!.text, state.youtubeURL!.text), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - text: 'Создать', - ), - ], - ), - ], - ), + Text('Заголовок'), + SizedBox(height: 8), + CustomTextFormField( + controller: state.title, + validator: _validateTitle, ), + SizedBox(height: 16), + Text('Описание'), + SizedBox(height: 8), + CustomTextFormField( + controller: state.description, + validator: _validateDescription, + maxLines: 6, + minLines: 1, + ), + SizedBox(height: 16), + Text('Ссылка на видео'), + SizedBox(height: 8), + CustomTextFormField( + controller: state.youtubeURL, + validator: _validateYouTubeLink, + ), + SizedBox(height: 16), + Text('Изображение поста'), + SizedBox(height: 8), + _buildAddPhoto(context, state), + SizedBox(height: 80), ], ), ), @@ -145,47 +134,34 @@ _buildAddPhoto(BuildContext context, BlogPostCreateLoadedState state) { children: [ if (state.image == null) Container( - margin: EdgeInsets.symmetric(horizontal: 10.h), - padding: EdgeInsets.symmetric( - horizontal: 40.h, - vertical: 80.v, - ), + height: 128, decoration: AppDecoration.fillGray.copyWith( - borderRadius: BorderRadiusStyle.roundedBorder5, + borderRadius: BorderRadius.circular(16), ), child: Row( - mainAxisAlignment: MainAxisAlignment.end, - mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, children: [ - Padding( - padding: EdgeInsets.only( - left: 7.h, - top: 5.v, - ), - child: Text( - "Добавить фото", - selectionColor: appTheme.blueA400, - ), - ), - Spacer(), Icon( Icons.photo_library, color: appTheme.blueGray300, ), + SizedBox(width: 8), + Text( + "Добавить фото", + selectionColor: appTheme.blueA400, + ), ], ), ), if (state.image != null) - Container( - margin: EdgeInsets.symmetric(horizontal: 10.h), - padding: EdgeInsets.symmetric( - horizontal: 40.h, - vertical: 80.v, + ClipRRect( + borderRadius: BorderRadius.circular(16), + child: Image( + image: FileImage( + File(state.image!.path), + ), ), - decoration: AppDecoration.fillGray.copyWith( - borderRadius: BorderRadiusStyle.roundedBorder5, - ), - child: Image(image: FileImage(File(state.image!.path))), ) ], ), diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart index e150ef9..02a1c4b 100644 --- a/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart +++ b/lib/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.freezed.dart @@ -24,7 +24,6 @@ mixin _$NewMessagesState { required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; - @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { @@ -71,30 +70,36 @@ mixin _$NewMessagesState { /// @nodoc abstract class $NewMessagesStateCopyWith<$Res> { - factory $NewMessagesStateCopyWith(NewMessagesState value, $Res Function(NewMessagesState) then) = _$NewMessagesStateCopyWithImpl<$Res, NewMessagesState>; + factory $NewMessagesStateCopyWith( + NewMessagesState value, $Res Function(NewMessagesState) then) = + _$NewMessagesStateCopyWithImpl<$Res, NewMessagesState>; } /// @nodoc -class _$NewMessagesStateCopyWithImpl<$Res, $Val extends NewMessagesState> implements $NewMessagesStateCopyWith<$Res> { +class _$NewMessagesStateCopyWithImpl<$Res, $Val extends NewMessagesState> + implements $NewMessagesStateCopyWith<$Res> { _$NewMessagesStateCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; } /// @nodoc abstract class _$$NewMessagesStateImplCopyWith<$Res> { - factory _$$NewMessagesStateImplCopyWith(_$NewMessagesStateImpl value, $Res Function(_$NewMessagesStateImpl) then) = + factory _$$NewMessagesStateImplCopyWith(_$NewMessagesStateImpl value, + $Res Function(_$NewMessagesStateImpl) then) = __$$NewMessagesStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NewMessagesStateImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateImpl> +class __$$NewMessagesStateImplCopyWithImpl<$Res> + extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateImpl> implements _$$NewMessagesStateImplCopyWith<$Res> { - __$$NewMessagesStateImplCopyWithImpl(_$NewMessagesStateImpl _value, $Res Function(_$NewMessagesStateImpl) _then) : super(_value, _then); + __$$NewMessagesStateImplCopyWithImpl(_$NewMessagesStateImpl _value, + $Res Function(_$NewMessagesStateImpl) _then) + : super(_value, _then); } /// @nodoc @@ -109,7 +114,8 @@ class _$NewMessagesStateImpl implements _NewMessagesState { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$NewMessagesStateImpl); } @override @@ -196,14 +202,19 @@ abstract class _NewMessagesState implements NewMessagesState { /// @nodoc abstract class _$$NewMessagesStateEmptyImplCopyWith<$Res> { - factory _$$NewMessagesStateEmptyImplCopyWith(_$NewMessagesStateEmptyImpl value, $Res Function(_$NewMessagesStateEmptyImpl) then) = + factory _$$NewMessagesStateEmptyImplCopyWith( + _$NewMessagesStateEmptyImpl value, + $Res Function(_$NewMessagesStateEmptyImpl) then) = __$$NewMessagesStateEmptyImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NewMessagesStateEmptyImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateEmptyImpl> +class __$$NewMessagesStateEmptyImplCopyWithImpl<$Res> + extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateEmptyImpl> implements _$$NewMessagesStateEmptyImplCopyWith<$Res> { - __$$NewMessagesStateEmptyImplCopyWithImpl(_$NewMessagesStateEmptyImpl _value, $Res Function(_$NewMessagesStateEmptyImpl) _then) : super(_value, _then); + __$$NewMessagesStateEmptyImplCopyWithImpl(_$NewMessagesStateEmptyImpl _value, + $Res Function(_$NewMessagesStateEmptyImpl) _then) + : super(_value, _then); } /// @nodoc @@ -218,7 +229,9 @@ class _$NewMessagesStateEmptyImpl implements NewMessagesStateEmpty { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateEmptyImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$NewMessagesStateEmptyImpl); } @override @@ -305,17 +318,22 @@ abstract class NewMessagesStateEmpty implements NewMessagesState { /// @nodoc abstract class _$$NewMessagesStateLoadedImplCopyWith<$Res> { - factory _$$NewMessagesStateLoadedImplCopyWith(_$NewMessagesStateLoadedImpl value, $Res Function(_$NewMessagesStateLoadedImpl) then) = + factory _$$NewMessagesStateLoadedImplCopyWith( + _$NewMessagesStateLoadedImpl value, + $Res Function(_$NewMessagesStateLoadedImpl) then) = __$$NewMessagesStateLoadedImplCopyWithImpl<$Res>; - @useResult $Res call({int messagesCount}); } /// @nodoc -class __$$NewMessagesStateLoadedImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateLoadedImpl> +class __$$NewMessagesStateLoadedImplCopyWithImpl<$Res> + extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateLoadedImpl> implements _$$NewMessagesStateLoadedImplCopyWith<$Res> { - __$$NewMessagesStateLoadedImplCopyWithImpl(_$NewMessagesStateLoadedImpl _value, $Res Function(_$NewMessagesStateLoadedImpl) _then) : super(_value, _then); + __$$NewMessagesStateLoadedImplCopyWithImpl( + _$NewMessagesStateLoadedImpl _value, + $Res Function(_$NewMessagesStateLoadedImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -349,7 +367,8 @@ class _$NewMessagesStateLoadedImpl implements NewMessagesStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateLoadedImpl && - (identical(other.messagesCount, messagesCount) || other.messagesCount == messagesCount)); + (identical(other.messagesCount, messagesCount) || + other.messagesCount == messagesCount)); } @override @@ -358,8 +377,9 @@ class _$NewMessagesStateLoadedImpl implements NewMessagesStateLoaded { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> get copyWith => - __$$NewMessagesStateLoadedImplCopyWithImpl<_$NewMessagesStateLoadedImpl>(this, _$identity); + _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> + get copyWith => __$$NewMessagesStateLoadedImplCopyWithImpl< + _$NewMessagesStateLoadedImpl>(this, _$identity); @override @optionalTypeArgs @@ -437,27 +457,32 @@ class _$NewMessagesStateLoadedImpl implements NewMessagesStateLoaded { } abstract class NewMessagesStateLoaded implements NewMessagesState { - const factory NewMessagesStateLoaded({required final int messagesCount}) = _$NewMessagesStateLoadedImpl; + const factory NewMessagesStateLoaded({required final int messagesCount}) = + _$NewMessagesStateLoadedImpl; int get messagesCount; - @JsonKey(ignore: true) - _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; + _$$NewMessagesStateLoadedImplCopyWith<_$NewMessagesStateLoadedImpl> + get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$NewMessagesStateErrorImplCopyWith<$Res> { - factory _$$NewMessagesStateErrorImplCopyWith(_$NewMessagesStateErrorImpl value, $Res Function(_$NewMessagesStateErrorImpl) then) = + factory _$$NewMessagesStateErrorImplCopyWith( + _$NewMessagesStateErrorImpl value, + $Res Function(_$NewMessagesStateErrorImpl) then) = __$$NewMessagesStateErrorImplCopyWithImpl<$Res>; - @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$NewMessagesStateErrorImplCopyWithImpl<$Res> extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateErrorImpl> +class __$$NewMessagesStateErrorImplCopyWithImpl<$Res> + extends _$NewMessagesStateCopyWithImpl<$Res, _$NewMessagesStateErrorImpl> implements _$$NewMessagesStateErrorImplCopyWith<$Res> { - __$$NewMessagesStateErrorImplCopyWithImpl(_$NewMessagesStateErrorImpl _value, $Res Function(_$NewMessagesStateErrorImpl) _then) : super(_value, _then); + __$$NewMessagesStateErrorImplCopyWithImpl(_$NewMessagesStateErrorImpl _value, + $Res Function(_$NewMessagesStateErrorImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -491,7 +516,8 @@ class _$NewMessagesStateErrorImpl implements NewMessagesStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NewMessagesStateErrorImpl && - (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); } @override @@ -500,8 +526,9 @@ class _$NewMessagesStateErrorImpl implements NewMessagesStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> get copyWith => - __$$NewMessagesStateErrorImplCopyWithImpl<_$NewMessagesStateErrorImpl>(this, _$identity); + _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> + get copyWith => __$$NewMessagesStateErrorImplCopyWithImpl< + _$NewMessagesStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -579,10 +606,11 @@ class _$NewMessagesStateErrorImpl implements NewMessagesStateError { } abstract class NewMessagesStateError implements NewMessagesState { - const factory NewMessagesStateError({required final String errorMessage}) = _$NewMessagesStateErrorImpl; + const factory NewMessagesStateError({required final String errorMessage}) = + _$NewMessagesStateErrorImpl; String get errorMessage; - @JsonKey(ignore: true) - _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> get copyWith => throw _privateConstructorUsedError; + _$$NewMessagesStateErrorImplCopyWith<_$NewMessagesStateErrorImpl> + get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart b/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart index b4b95e0..0deeebb 100644 --- a/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart +++ b/lib/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.freezed.dart @@ -24,7 +24,6 @@ mixin _$NotificationsState { required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; - @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { @@ -71,31 +70,36 @@ mixin _$NotificationsState { /// @nodoc abstract class $NotificationsStateCopyWith<$Res> { - factory $NotificationsStateCopyWith(NotificationsState value, $Res Function(NotificationsState) then) = + factory $NotificationsStateCopyWith( + NotificationsState value, $Res Function(NotificationsState) then) = _$NotificationsStateCopyWithImpl<$Res, NotificationsState>; } /// @nodoc -class _$NotificationsStateCopyWithImpl<$Res, $Val extends NotificationsState> implements $NotificationsStateCopyWith<$Res> { +class _$NotificationsStateCopyWithImpl<$Res, $Val extends NotificationsState> + implements $NotificationsStateCopyWith<$Res> { _$NotificationsStateCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; } /// @nodoc abstract class _$$NotificationsStateImplCopyWith<$Res> { - factory _$$NotificationsStateImplCopyWith(_$NotificationsStateImpl value, $Res Function(_$NotificationsStateImpl) then) = + factory _$$NotificationsStateImplCopyWith(_$NotificationsStateImpl value, + $Res Function(_$NotificationsStateImpl) then) = __$$NotificationsStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NotificationsStateImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateImpl> +class __$$NotificationsStateImplCopyWithImpl<$Res> + extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateImpl> implements _$$NotificationsStateImplCopyWith<$Res> { - __$$NotificationsStateImplCopyWithImpl(_$NotificationsStateImpl _value, $Res Function(_$NotificationsStateImpl) _then) : super(_value, _then); + __$$NotificationsStateImplCopyWithImpl(_$NotificationsStateImpl _value, + $Res Function(_$NotificationsStateImpl) _then) + : super(_value, _then); } /// @nodoc @@ -110,7 +114,8 @@ class _$NotificationsStateImpl implements _NotificationsState { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$NotificationsStateImpl); } @override @@ -197,14 +202,21 @@ abstract class _NotificationsState implements NotificationsState { /// @nodoc abstract class _$$NotificationsStateEmptyImplCopyWith<$Res> { - factory _$$NotificationsStateEmptyImplCopyWith(_$NotificationsStateEmptyImpl value, $Res Function(_$NotificationsStateEmptyImpl) then) = + factory _$$NotificationsStateEmptyImplCopyWith( + _$NotificationsStateEmptyImpl value, + $Res Function(_$NotificationsStateEmptyImpl) then) = __$$NotificationsStateEmptyImplCopyWithImpl<$Res>; } /// @nodoc -class __$$NotificationsStateEmptyImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateEmptyImpl> +class __$$NotificationsStateEmptyImplCopyWithImpl<$Res> + extends _$NotificationsStateCopyWithImpl<$Res, + _$NotificationsStateEmptyImpl> implements _$$NotificationsStateEmptyImplCopyWith<$Res> { - __$$NotificationsStateEmptyImplCopyWithImpl(_$NotificationsStateEmptyImpl _value, $Res Function(_$NotificationsStateEmptyImpl) _then) : super(_value, _then); + __$$NotificationsStateEmptyImplCopyWithImpl( + _$NotificationsStateEmptyImpl _value, + $Res Function(_$NotificationsStateEmptyImpl) _then) + : super(_value, _then); } /// @nodoc @@ -219,7 +231,9 @@ class _$NotificationsStateEmptyImpl implements NotificationsStateEmpty { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateEmptyImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$NotificationsStateEmptyImpl); } @override @@ -306,17 +320,22 @@ abstract class NotificationsStateEmpty implements NotificationsState { /// @nodoc abstract class _$$NotificationsStateLoadedImplCopyWith<$Res> { - factory _$$NotificationsStateLoadedImplCopyWith(_$NotificationsStateLoadedImpl value, $Res Function(_$NotificationsStateLoadedImpl) then) = + factory _$$NotificationsStateLoadedImplCopyWith( + _$NotificationsStateLoadedImpl value, + $Res Function(_$NotificationsStateLoadedImpl) then) = __$$NotificationsStateLoadedImplCopyWithImpl<$Res>; - @useResult $Res call({int notificationsCount}); } /// @nodoc -class __$$NotificationsStateLoadedImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateLoadedImpl> +class __$$NotificationsStateLoadedImplCopyWithImpl<$Res> + extends _$NotificationsStateCopyWithImpl<$Res, + _$NotificationsStateLoadedImpl> implements _$$NotificationsStateLoadedImplCopyWith<$Res> { - __$$NotificationsStateLoadedImplCopyWithImpl(_$NotificationsStateLoadedImpl _value, $Res Function(_$NotificationsStateLoadedImpl) _then) + __$$NotificationsStateLoadedImplCopyWithImpl( + _$NotificationsStateLoadedImpl _value, + $Res Function(_$NotificationsStateLoadedImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -351,7 +370,8 @@ class _$NotificationsStateLoadedImpl implements NotificationsStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateLoadedImpl && - (identical(other.notificationsCount, notificationsCount) || other.notificationsCount == notificationsCount)); + (identical(other.notificationsCount, notificationsCount) || + other.notificationsCount == notificationsCount)); } @override @@ -360,8 +380,9 @@ class _$NotificationsStateLoadedImpl implements NotificationsStateLoaded { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> get copyWith => - __$$NotificationsStateLoadedImplCopyWithImpl<_$NotificationsStateLoadedImpl>(this, _$identity); + _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> + get copyWith => __$$NotificationsStateLoadedImplCopyWithImpl< + _$NotificationsStateLoadedImpl>(this, _$identity); @override @optionalTypeArgs @@ -439,27 +460,34 @@ class _$NotificationsStateLoadedImpl implements NotificationsStateLoaded { } abstract class NotificationsStateLoaded implements NotificationsState { - const factory NotificationsStateLoaded({required final int notificationsCount}) = _$NotificationsStateLoadedImpl; + const factory NotificationsStateLoaded( + {required final int notificationsCount}) = _$NotificationsStateLoadedImpl; int get notificationsCount; - @JsonKey(ignore: true) - _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; + _$$NotificationsStateLoadedImplCopyWith<_$NotificationsStateLoadedImpl> + get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$NotificationsStateErrorImplCopyWith<$Res> { - factory _$$NotificationsStateErrorImplCopyWith(_$NotificationsStateErrorImpl value, $Res Function(_$NotificationsStateErrorImpl) then) = + factory _$$NotificationsStateErrorImplCopyWith( + _$NotificationsStateErrorImpl value, + $Res Function(_$NotificationsStateErrorImpl) then) = __$$NotificationsStateErrorImplCopyWithImpl<$Res>; - @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$NotificationsStateErrorImplCopyWithImpl<$Res> extends _$NotificationsStateCopyWithImpl<$Res, _$NotificationsStateErrorImpl> +class __$$NotificationsStateErrorImplCopyWithImpl<$Res> + extends _$NotificationsStateCopyWithImpl<$Res, + _$NotificationsStateErrorImpl> implements _$$NotificationsStateErrorImplCopyWith<$Res> { - __$$NotificationsStateErrorImplCopyWithImpl(_$NotificationsStateErrorImpl _value, $Res Function(_$NotificationsStateErrorImpl) _then) : super(_value, _then); + __$$NotificationsStateErrorImplCopyWithImpl( + _$NotificationsStateErrorImpl _value, + $Res Function(_$NotificationsStateErrorImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -493,7 +521,8 @@ class _$NotificationsStateErrorImpl implements NotificationsStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$NotificationsStateErrorImpl && - (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); } @override @@ -502,8 +531,9 @@ class _$NotificationsStateErrorImpl implements NotificationsStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> get copyWith => - __$$NotificationsStateErrorImplCopyWithImpl<_$NotificationsStateErrorImpl>(this, _$identity); + _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> + get copyWith => __$$NotificationsStateErrorImplCopyWithImpl< + _$NotificationsStateErrorImpl>(this, _$identity); @override @optionalTypeArgs @@ -581,10 +611,11 @@ class _$NotificationsStateErrorImpl implements NotificationsStateError { } abstract class NotificationsStateError implements NotificationsState { - const factory NotificationsStateError({required final String errorMessage}) = _$NotificationsStateErrorImpl; + const factory NotificationsStateError({required final String errorMessage}) = + _$NotificationsStateErrorImpl; String get errorMessage; - @JsonKey(ignore: true) - _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> get copyWith => throw _privateConstructorUsedError; + _$$NotificationsStateErrorImplCopyWith<_$NotificationsStateErrorImpl> + get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_message_model.freezed.dart b/lib/features/chat/models/chat_message_model.freezed.dart index 6dfda16..76a91cb 100644 --- a/lib/features/chat/models/chat_message_model.freezed.dart +++ b/lib/features/chat/models/chat_message_model.freezed.dart @@ -21,28 +21,25 @@ ChatMessageModel _$ChatMessageModelFromJson(Map json) { /// @nodoc mixin _$ChatMessageModel { int get id => throw _privateConstructorUsedError; - String get data => throw _privateConstructorUsedError; - @JsonKey(name: 'media_data') List? get mediaData => throw _privateConstructorUsedError; - @JsonKey(name: 'author_id') int get authorId => throw _privateConstructorUsedError; - @JsonKey(name: 'updated_at') String get updatedAt => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $ChatMessageModelCopyWith get copyWith => throw _privateConstructorUsedError; + $ChatMessageModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatMessageModelCopyWith<$Res> { - factory $ChatMessageModelCopyWith(ChatMessageModel value, $Res Function(ChatMessageModel) then) = _$ChatMessageModelCopyWithImpl<$Res, ChatMessageModel>; - + factory $ChatMessageModelCopyWith( + ChatMessageModel value, $Res Function(ChatMessageModel) then) = + _$ChatMessageModelCopyWithImpl<$Res, ChatMessageModel>; @useResult $Res call( {int id, @@ -53,12 +50,12 @@ abstract class $ChatMessageModelCopyWith<$Res> { } /// @nodoc -class _$ChatMessageModelCopyWithImpl<$Res, $Val extends ChatMessageModel> implements $ChatMessageModelCopyWith<$Res> { +class _$ChatMessageModelCopyWithImpl<$Res, $Val extends ChatMessageModel> + implements $ChatMessageModelCopyWith<$Res> { _$ChatMessageModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -97,10 +94,11 @@ class _$ChatMessageModelCopyWithImpl<$Res, $Val extends ChatMessageModel> implem } /// @nodoc -abstract class _$$ChatMessageModelImplCopyWith<$Res> implements $ChatMessageModelCopyWith<$Res> { - factory _$$ChatMessageModelImplCopyWith(_$ChatMessageModelImpl value, $Res Function(_$ChatMessageModelImpl) then) = +abstract class _$$ChatMessageModelImplCopyWith<$Res> + implements $ChatMessageModelCopyWith<$Res> { + factory _$$ChatMessageModelImplCopyWith(_$ChatMessageModelImpl value, + $Res Function(_$ChatMessageModelImpl) then) = __$$ChatMessageModelImplCopyWithImpl<$Res>; - @override @useResult $Res call( @@ -112,9 +110,12 @@ abstract class _$$ChatMessageModelImplCopyWith<$Res> implements $ChatMessageMode } /// @nodoc -class __$$ChatMessageModelImplCopyWithImpl<$Res> extends _$ChatMessageModelCopyWithImpl<$Res, _$ChatMessageModelImpl> +class __$$ChatMessageModelImplCopyWithImpl<$Res> + extends _$ChatMessageModelCopyWithImpl<$Res, _$ChatMessageModelImpl> implements _$$ChatMessageModelImplCopyWith<$Res> { - __$$ChatMessageModelImplCopyWithImpl(_$ChatMessageModelImpl _value, $Res Function(_$ChatMessageModelImpl) _then) : super(_value, _then); + __$$ChatMessageModelImplCopyWithImpl(_$ChatMessageModelImpl _value, + $Res Function(_$ChatMessageModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -161,14 +162,14 @@ class _$ChatMessageModelImpl implements _ChatMessageModel { @JsonKey(name: 'updated_at') required this.updatedAt}) : _mediaData = mediaData; - factory _$ChatMessageModelImpl.fromJson(Map json) => _$$ChatMessageModelImplFromJson(json); + factory _$ChatMessageModelImpl.fromJson(Map json) => + _$$ChatMessageModelImplFromJson(json); @override final int id; @override final String data; final List? _mediaData; - @override @JsonKey(name: 'media_data') List? get mediaData { @@ -198,19 +199,25 @@ class _$ChatMessageModelImpl implements _ChatMessageModel { other is _$ChatMessageModelImpl && (identical(other.id, id) || other.id == id) && (identical(other.data, data) || other.data == data) && - const DeepCollectionEquality().equals(other._mediaData, _mediaData) && - (identical(other.authorId, authorId) || other.authorId == authorId) && - (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)); + const DeepCollectionEquality() + .equals(other._mediaData, _mediaData) && + (identical(other.authorId, authorId) || + other.authorId == authorId) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, data, const DeepCollectionEquality().hash(_mediaData), authorId, updatedAt); + int get hashCode => Object.hash(runtimeType, id, data, + const DeepCollectionEquality().hash(_mediaData), authorId, updatedAt); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => __$$ChatMessageModelImplCopyWithImpl<_$ChatMessageModelImpl>(this, _$identity); + _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => + __$$ChatMessageModelImplCopyWithImpl<_$ChatMessageModelImpl>( + this, _$identity); @override Map toJson() { @@ -222,33 +229,31 @@ class _$ChatMessageModelImpl implements _ChatMessageModel { abstract class _ChatMessageModel implements ChatMessageModel { const factory _ChatMessageModel( - {required final int id, - required final String data, - @JsonKey(name: 'media_data') required final List? mediaData, - @JsonKey(name: 'author_id') required final int authorId, - @JsonKey(name: 'updated_at') required final String updatedAt}) = _$ChatMessageModelImpl; + {required final int id, + required final String data, + @JsonKey(name: 'media_data') required final List? mediaData, + @JsonKey(name: 'author_id') required final int authorId, + @JsonKey(name: 'updated_at') required final String updatedAt}) = + _$ChatMessageModelImpl; - factory _ChatMessageModel.fromJson(Map json) = _$ChatMessageModelImpl.fromJson; + factory _ChatMessageModel.fromJson(Map json) = + _$ChatMessageModelImpl.fromJson; @override int get id; - @override String get data; - @override @JsonKey(name: 'media_data') List? get mediaData; - @override @JsonKey(name: 'author_id') int get authorId; - @override @JsonKey(name: 'updated_at') String get updatedAt; - @override @JsonKey(ignore: true) - _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatMessageModelImplCopyWith<_$ChatMessageModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_message_model.g.dart b/lib/features/chat/models/chat_message_model.g.dart index 7053109..3a8d182 100644 --- a/lib/features/chat/models/chat_message_model.g.dart +++ b/lib/features/chat/models/chat_message_model.g.dart @@ -6,7 +6,9 @@ part of 'chat_message_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatMessageModelImpl _$$ChatMessageModelImplFromJson(Map json) => _$ChatMessageModelImpl( +_$ChatMessageModelImpl _$$ChatMessageModelImplFromJson( + Map json) => + _$ChatMessageModelImpl( id: (json['id'] as num).toInt(), data: json['data'] as String, mediaData: json['media_data'] as List?, @@ -14,7 +16,9 @@ _$ChatMessageModelImpl _$$ChatMessageModelImplFromJson(Map json updatedAt: json['updated_at'] as String, ); -Map _$$ChatMessageModelImplToJson(_$ChatMessageModelImpl instance) => { +Map _$$ChatMessageModelImplToJson( + _$ChatMessageModelImpl instance) => + { 'id': instance.id, 'data': instance.data, 'media_data': instance.mediaData, diff --git a/lib/features/chat/models/chat_messages_model.freezed.dart b/lib/features/chat/models/chat_messages_model.freezed.dart index 88f6278..a970241 100644 --- a/lib/features/chat/models/chat_messages_model.freezed.dart +++ b/lib/features/chat/models/chat_messages_model.freezed.dart @@ -22,32 +22,34 @@ ChatMessagesModel _$ChatMessagesModelFromJson(Map json) { mixin _$ChatMessagesModel { @JsonKey(name: 'data') List get messagesList => throw _privateConstructorUsedError; - ChatMetaModel get meta => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $ChatMessagesModelCopyWith get copyWith => throw _privateConstructorUsedError; + $ChatMessagesModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatMessagesModelCopyWith<$Res> { - factory $ChatMessagesModelCopyWith(ChatMessagesModel value, $Res Function(ChatMessagesModel) then) = _$ChatMessagesModelCopyWithImpl<$Res, ChatMessagesModel>; - + factory $ChatMessagesModelCopyWith( + ChatMessagesModel value, $Res Function(ChatMessagesModel) then) = + _$ChatMessagesModelCopyWithImpl<$Res, ChatMessagesModel>; @useResult - $Res call({@JsonKey(name: 'data') List messagesList, ChatMetaModel meta}); + $Res call( + {@JsonKey(name: 'data') List messagesList, + ChatMetaModel meta}); $ChatMetaModelCopyWith<$Res> get meta; } /// @nodoc -class _$ChatMessagesModelCopyWithImpl<$Res, $Val extends ChatMessagesModel> implements $ChatMessagesModelCopyWith<$Res> { +class _$ChatMessagesModelCopyWithImpl<$Res, $Val extends ChatMessagesModel> + implements $ChatMessagesModelCopyWith<$Res> { _$ChatMessagesModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -79,22 +81,28 @@ class _$ChatMessagesModelCopyWithImpl<$Res, $Val extends ChatMessagesModel> impl } /// @nodoc -abstract class _$$ChatMessagesModelImplCopyWith<$Res> implements $ChatMessagesModelCopyWith<$Res> { - factory _$$ChatMessagesModelImplCopyWith(_$ChatMessagesModelImpl value, $Res Function(_$ChatMessagesModelImpl) then) = +abstract class _$$ChatMessagesModelImplCopyWith<$Res> + implements $ChatMessagesModelCopyWith<$Res> { + factory _$$ChatMessagesModelImplCopyWith(_$ChatMessagesModelImpl value, + $Res Function(_$ChatMessagesModelImpl) then) = __$$ChatMessagesModelImplCopyWithImpl<$Res>; - @override @useResult - $Res call({@JsonKey(name: 'data') List messagesList, ChatMetaModel meta}); + $Res call( + {@JsonKey(name: 'data') List messagesList, + ChatMetaModel meta}); @override $ChatMetaModelCopyWith<$Res> get meta; } /// @nodoc -class __$$ChatMessagesModelImplCopyWithImpl<$Res> extends _$ChatMessagesModelCopyWithImpl<$Res, _$ChatMessagesModelImpl> +class __$$ChatMessagesModelImplCopyWithImpl<$Res> + extends _$ChatMessagesModelCopyWithImpl<$Res, _$ChatMessagesModelImpl> implements _$$ChatMessagesModelImplCopyWith<$Res> { - __$$ChatMessagesModelImplCopyWithImpl(_$ChatMessagesModelImpl _value, $Res Function(_$ChatMessagesModelImpl) _then) : super(_value, _then); + __$$ChatMessagesModelImplCopyWithImpl(_$ChatMessagesModelImpl _value, + $Res Function(_$ChatMessagesModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -118,12 +126,16 @@ class __$$ChatMessagesModelImplCopyWithImpl<$Res> extends _$ChatMessagesModelCop /// @nodoc @JsonSerializable() class _$ChatMessagesModelImpl implements _ChatMessagesModel { - const _$ChatMessagesModelImpl({@JsonKey(name: 'data') required final List messagesList, required this.meta}) : _messagesList = messagesList; + const _$ChatMessagesModelImpl( + {@JsonKey(name: 'data') + required final List messagesList, + required this.meta}) + : _messagesList = messagesList; - factory _$ChatMessagesModelImpl.fromJson(Map json) => _$$ChatMessagesModelImplFromJson(json); + factory _$ChatMessagesModelImpl.fromJson(Map json) => + _$$ChatMessagesModelImplFromJson(json); final List _messagesList; - @override @JsonKey(name: 'data') List get messagesList { @@ -145,18 +157,22 @@ class _$ChatMessagesModelImpl implements _ChatMessagesModel { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatMessagesModelImpl && - const DeepCollectionEquality().equals(other._messagesList, _messagesList) && + const DeepCollectionEquality() + .equals(other._messagesList, _messagesList) && (identical(other.meta, meta) || other.meta == meta)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_messagesList), meta); + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_messagesList), meta); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => __$$ChatMessagesModelImplCopyWithImpl<_$ChatMessagesModelImpl>(this, _$identity); + _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => + __$$ChatMessagesModelImplCopyWithImpl<_$ChatMessagesModelImpl>( + this, _$identity); @override Map toJson() { @@ -167,19 +183,21 @@ class _$ChatMessagesModelImpl implements _ChatMessagesModel { } abstract class _ChatMessagesModel implements ChatMessagesModel { - const factory _ChatMessagesModel({@JsonKey(name: 'data') required final List messagesList, required final ChatMetaModel meta}) = - _$ChatMessagesModelImpl; + const factory _ChatMessagesModel( + {@JsonKey(name: 'data') + required final List messagesList, + required final ChatMetaModel meta}) = _$ChatMessagesModelImpl; - factory _ChatMessagesModel.fromJson(Map json) = _$ChatMessagesModelImpl.fromJson; + factory _ChatMessagesModel.fromJson(Map json) = + _$ChatMessagesModelImpl.fromJson; @override @JsonKey(name: 'data') List get messagesList; - @override ChatMetaModel get meta; - @override @JsonKey(ignore: true) - _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatMessagesModelImplCopyWith<_$ChatMessagesModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_messages_model.g.dart b/lib/features/chat/models/chat_messages_model.g.dart index 1a7fe48..6216cd8 100644 --- a/lib/features/chat/models/chat_messages_model.g.dart +++ b/lib/features/chat/models/chat_messages_model.g.dart @@ -6,12 +6,18 @@ part of 'chat_messages_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatMessagesModelImpl _$$ChatMessagesModelImplFromJson(Map json) => _$ChatMessagesModelImpl( - messagesList: (json['data'] as List).map((e) => ChatMessageModel.fromJson(e as Map)).toList(), +_$ChatMessagesModelImpl _$$ChatMessagesModelImplFromJson( + Map json) => + _$ChatMessagesModelImpl( + messagesList: (json['data'] as List) + .map((e) => ChatMessageModel.fromJson(e as Map)) + .toList(), meta: ChatMetaModel.fromJson(json['meta'] as Map), ); -Map _$$ChatMessagesModelImplToJson(_$ChatMessagesModelImpl instance) => { +Map _$$ChatMessagesModelImplToJson( + _$ChatMessagesModelImpl instance) => + { 'data': instance.messagesList, 'meta': instance.meta, }; diff --git a/lib/features/chat/models/chat_meta_model.freezed.dart b/lib/features/chat/models/chat_meta_model.freezed.dart index 206048f..11ecb9e 100644 --- a/lib/features/chat/models/chat_meta_model.freezed.dart +++ b/lib/features/chat/models/chat_meta_model.freezed.dart @@ -24,26 +24,27 @@ mixin _$ChatMetaModel { int get lastPage => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $ChatMetaModelCopyWith get copyWith => throw _privateConstructorUsedError; + $ChatMetaModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatMetaModelCopyWith<$Res> { - factory $ChatMetaModelCopyWith(ChatMetaModel value, $Res Function(ChatMetaModel) then) = _$ChatMetaModelCopyWithImpl<$Res, ChatMetaModel>; - + factory $ChatMetaModelCopyWith( + ChatMetaModel value, $Res Function(ChatMetaModel) then) = + _$ChatMetaModelCopyWithImpl<$Res, ChatMetaModel>; @useResult $Res call({@JsonKey(name: "last_page") int lastPage}); } /// @nodoc -class _$ChatMetaModelCopyWithImpl<$Res, $Val extends ChatMetaModel> implements $ChatMetaModelCopyWith<$Res> { +class _$ChatMetaModelCopyWithImpl<$Res, $Val extends ChatMetaModel> + implements $ChatMetaModelCopyWith<$Res> { _$ChatMetaModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -62,17 +63,23 @@ class _$ChatMetaModelCopyWithImpl<$Res, $Val extends ChatMetaModel> implements $ } /// @nodoc -abstract class _$$ChatMetaModelImplCopyWith<$Res> implements $ChatMetaModelCopyWith<$Res> { - factory _$$ChatMetaModelImplCopyWith(_$ChatMetaModelImpl value, $Res Function(_$ChatMetaModelImpl) then) = __$$ChatMetaModelImplCopyWithImpl<$Res>; - +abstract class _$$ChatMetaModelImplCopyWith<$Res> + implements $ChatMetaModelCopyWith<$Res> { + factory _$$ChatMetaModelImplCopyWith( + _$ChatMetaModelImpl value, $Res Function(_$ChatMetaModelImpl) then) = + __$$ChatMetaModelImplCopyWithImpl<$Res>; @override @useResult $Res call({@JsonKey(name: "last_page") int lastPage}); } /// @nodoc -class __$$ChatMetaModelImplCopyWithImpl<$Res> extends _$ChatMetaModelCopyWithImpl<$Res, _$ChatMetaModelImpl> implements _$$ChatMetaModelImplCopyWith<$Res> { - __$$ChatMetaModelImplCopyWithImpl(_$ChatMetaModelImpl _value, $Res Function(_$ChatMetaModelImpl) _then) : super(_value, _then); +class __$$ChatMetaModelImplCopyWithImpl<$Res> + extends _$ChatMetaModelCopyWithImpl<$Res, _$ChatMetaModelImpl> + implements _$$ChatMetaModelImplCopyWith<$Res> { + __$$ChatMetaModelImplCopyWithImpl( + _$ChatMetaModelImpl _value, $Res Function(_$ChatMetaModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -91,9 +98,11 @@ class __$$ChatMetaModelImplCopyWithImpl<$Res> extends _$ChatMetaModelCopyWithImp /// @nodoc @JsonSerializable() class _$ChatMetaModelImpl implements _ChatMetaModel { - const _$ChatMetaModelImpl({@JsonKey(name: "last_page") required this.lastPage}); + const _$ChatMetaModelImpl( + {@JsonKey(name: "last_page") required this.lastPage}); - factory _$ChatMetaModelImpl.fromJson(Map json) => _$$ChatMetaModelImplFromJson(json); + factory _$ChatMetaModelImpl.fromJson(Map json) => + _$$ChatMetaModelImplFromJson(json); @override @JsonKey(name: "last_page") @@ -107,7 +116,10 @@ class _$ChatMetaModelImpl implements _ChatMetaModel { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && other is _$ChatMetaModelImpl && (identical(other.lastPage, lastPage) || other.lastPage == lastPage)); + (other.runtimeType == runtimeType && + other is _$ChatMetaModelImpl && + (identical(other.lastPage, lastPage) || + other.lastPage == lastPage)); } @JsonKey(ignore: true) @@ -117,7 +129,8 @@ class _$ChatMetaModelImpl implements _ChatMetaModel { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => __$$ChatMetaModelImplCopyWithImpl<_$ChatMetaModelImpl>(this, _$identity); + _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => + __$$ChatMetaModelImplCopyWithImpl<_$ChatMetaModelImpl>(this, _$identity); @override Map toJson() { @@ -128,15 +141,18 @@ class _$ChatMetaModelImpl implements _ChatMetaModel { } abstract class _ChatMetaModel implements ChatMetaModel { - const factory _ChatMetaModel({@JsonKey(name: "last_page") required final int lastPage}) = _$ChatMetaModelImpl; + const factory _ChatMetaModel( + {@JsonKey(name: "last_page") required final int lastPage}) = + _$ChatMetaModelImpl; - factory _ChatMetaModel.fromJson(Map json) = _$ChatMetaModelImpl.fromJson; + factory _ChatMetaModel.fromJson(Map json) = + _$ChatMetaModelImpl.fromJson; @override @JsonKey(name: "last_page") int get lastPage; - @override @JsonKey(ignore: true) - _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatMetaModelImplCopyWith<_$ChatMetaModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_meta_model.g.dart b/lib/features/chat/models/chat_meta_model.g.dart index bbd16d1..7126e2d 100644 --- a/lib/features/chat/models/chat_meta_model.g.dart +++ b/lib/features/chat/models/chat_meta_model.g.dart @@ -6,10 +6,12 @@ part of 'chat_meta_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatMetaModelImpl _$$ChatMetaModelImplFromJson(Map json) => _$ChatMetaModelImpl( +_$ChatMetaModelImpl _$$ChatMetaModelImplFromJson(Map json) => + _$ChatMetaModelImpl( lastPage: (json['last_page'] as num).toInt(), ); -Map _$$ChatMetaModelImplToJson(_$ChatMetaModelImpl instance) => { +Map _$$ChatMetaModelImplToJson(_$ChatMetaModelImpl instance) => + { 'last_page': instance.lastPage, }; diff --git a/lib/features/chat/models/chat_room_model.freezed.dart b/lib/features/chat/models/chat_room_model.freezed.dart index 2606623..5a0b6e6 100644 --- a/lib/features/chat/models/chat_room_model.freezed.dart +++ b/lib/features/chat/models/chat_room_model.freezed.dart @@ -21,35 +21,39 @@ ChatRoomModel _$ChatRoomModelFromJson(Map json) { /// @nodoc mixin _$ChatRoomModel { String get id => throw _privateConstructorUsedError; - @JsonKey(name: 'chat_room_setting') - ChatRoomSettingsModel get chatRoomSettings => throw _privateConstructorUsedError; - + ChatRoomSettingsModel get chatRoomSettings => + throw _privateConstructorUsedError; Map get users => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $ChatRoomModelCopyWith get copyWith => throw _privateConstructorUsedError; + $ChatRoomModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatRoomModelCopyWith<$Res> { - factory $ChatRoomModelCopyWith(ChatRoomModel value, $Res Function(ChatRoomModel) then) = _$ChatRoomModelCopyWithImpl<$Res, ChatRoomModel>; - + factory $ChatRoomModelCopyWith( + ChatRoomModel value, $Res Function(ChatRoomModel) then) = + _$ChatRoomModelCopyWithImpl<$Res, ChatRoomModel>; @useResult - $Res call({String id, @JsonKey(name: 'chat_room_setting') ChatRoomSettingsModel chatRoomSettings, Map users}); + $Res call( + {String id, + @JsonKey(name: 'chat_room_setting') + ChatRoomSettingsModel chatRoomSettings, + Map users}); $ChatRoomSettingsModelCopyWith<$Res> get chatRoomSettings; } /// @nodoc -class _$ChatRoomModelCopyWithImpl<$Res, $Val extends ChatRoomModel> implements $ChatRoomModelCopyWith<$Res> { +class _$ChatRoomModelCopyWithImpl<$Res, $Val extends ChatRoomModel> + implements $ChatRoomModelCopyWith<$Res> { _$ChatRoomModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -79,27 +83,38 @@ class _$ChatRoomModelCopyWithImpl<$Res, $Val extends ChatRoomModel> implements $ @override @pragma('vm:prefer-inline') $ChatRoomSettingsModelCopyWith<$Res> get chatRoomSettings { - return $ChatRoomSettingsModelCopyWith<$Res>(_value.chatRoomSettings, (value) { + return $ChatRoomSettingsModelCopyWith<$Res>(_value.chatRoomSettings, + (value) { return _then(_value.copyWith(chatRoomSettings: value) as $Val); }); } } /// @nodoc -abstract class _$$ChatRoomModelImplCopyWith<$Res> implements $ChatRoomModelCopyWith<$Res> { - factory _$$ChatRoomModelImplCopyWith(_$ChatRoomModelImpl value, $Res Function(_$ChatRoomModelImpl) then) = __$$ChatRoomModelImplCopyWithImpl<$Res>; - +abstract class _$$ChatRoomModelImplCopyWith<$Res> + implements $ChatRoomModelCopyWith<$Res> { + factory _$$ChatRoomModelImplCopyWith( + _$ChatRoomModelImpl value, $Res Function(_$ChatRoomModelImpl) then) = + __$$ChatRoomModelImplCopyWithImpl<$Res>; @override @useResult - $Res call({String id, @JsonKey(name: 'chat_room_setting') ChatRoomSettingsModel chatRoomSettings, Map users}); + $Res call( + {String id, + @JsonKey(name: 'chat_room_setting') + ChatRoomSettingsModel chatRoomSettings, + Map users}); @override $ChatRoomSettingsModelCopyWith<$Res> get chatRoomSettings; } /// @nodoc -class __$$ChatRoomModelImplCopyWithImpl<$Res> extends _$ChatRoomModelCopyWithImpl<$Res, _$ChatRoomModelImpl> implements _$$ChatRoomModelImplCopyWith<$Res> { - __$$ChatRoomModelImplCopyWithImpl(_$ChatRoomModelImpl _value, $Res Function(_$ChatRoomModelImpl) _then) : super(_value, _then); +class __$$ChatRoomModelImplCopyWithImpl<$Res> + extends _$ChatRoomModelCopyWithImpl<$Res, _$ChatRoomModelImpl> + implements _$$ChatRoomModelImplCopyWith<$Res> { + __$$ChatRoomModelImplCopyWithImpl( + _$ChatRoomModelImpl _value, $Res Function(_$ChatRoomModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -129,10 +144,13 @@ class __$$ChatRoomModelImplCopyWithImpl<$Res> extends _$ChatRoomModelCopyWithImp @JsonSerializable() class _$ChatRoomModelImpl implements _ChatRoomModel { const _$ChatRoomModelImpl( - {required this.id, @JsonKey(name: 'chat_room_setting') required this.chatRoomSettings, required final Map users}) + {required this.id, + @JsonKey(name: 'chat_room_setting') required this.chatRoomSettings, + required final Map users}) : _users = users; - factory _$ChatRoomModelImpl.fromJson(Map json) => _$$ChatRoomModelImplFromJson(json); + factory _$ChatRoomModelImpl.fromJson(Map json) => + _$$ChatRoomModelImplFromJson(json); @override final String id; @@ -140,7 +158,6 @@ class _$ChatRoomModelImpl implements _ChatRoomModel { @JsonKey(name: 'chat_room_setting') final ChatRoomSettingsModel chatRoomSettings; final Map _users; - @override Map get users { if (_users is EqualUnmodifiableMapView) return _users; @@ -159,18 +176,21 @@ class _$ChatRoomModelImpl implements _ChatRoomModel { (other.runtimeType == runtimeType && other is _$ChatRoomModelImpl && (identical(other.id, id) || other.id == id) && - (identical(other.chatRoomSettings, chatRoomSettings) || other.chatRoomSettings == chatRoomSettings) && + (identical(other.chatRoomSettings, chatRoomSettings) || + other.chatRoomSettings == chatRoomSettings) && const DeepCollectionEquality().equals(other._users, _users)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, chatRoomSettings, const DeepCollectionEquality().hash(_users)); + int get hashCode => Object.hash(runtimeType, id, chatRoomSettings, + const DeepCollectionEquality().hash(_users)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => __$$ChatRoomModelImplCopyWithImpl<_$ChatRoomModelImpl>(this, _$identity); + _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => + __$$ChatRoomModelImplCopyWithImpl<_$ChatRoomModelImpl>(this, _$identity); @override Map toJson() { @@ -183,22 +203,22 @@ class _$ChatRoomModelImpl implements _ChatRoomModel { abstract class _ChatRoomModel implements ChatRoomModel { const factory _ChatRoomModel( {required final String id, - @JsonKey(name: 'chat_room_setting') required final ChatRoomSettingsModel chatRoomSettings, + @JsonKey(name: 'chat_room_setting') + required final ChatRoomSettingsModel chatRoomSettings, required final Map users}) = _$ChatRoomModelImpl; - factory _ChatRoomModel.fromJson(Map json) = _$ChatRoomModelImpl.fromJson; + factory _ChatRoomModel.fromJson(Map json) = + _$ChatRoomModelImpl.fromJson; @override String get id; - @override @JsonKey(name: 'chat_room_setting') ChatRoomSettingsModel get chatRoomSettings; - @override Map get users; - @override @JsonKey(ignore: true) - _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatRoomModelImplCopyWith<_$ChatRoomModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_room_model.g.dart b/lib/features/chat/models/chat_room_model.g.dart index 6230d4f..68d3195 100644 --- a/lib/features/chat/models/chat_room_model.g.dart +++ b/lib/features/chat/models/chat_room_model.g.dart @@ -6,15 +6,19 @@ part of 'chat_room_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatRoomModelImpl _$$ChatRoomModelImplFromJson(Map json) => _$ChatRoomModelImpl( +_$ChatRoomModelImpl _$$ChatRoomModelImplFromJson(Map json) => + _$ChatRoomModelImpl( id: json['id'] as String, - chatRoomSettings: ChatRoomSettingsModel.fromJson(json['chat_room_setting'] as Map), + chatRoomSettings: ChatRoomSettingsModel.fromJson( + json['chat_room_setting'] as Map), users: (json['users'] as Map).map( - (k, e) => MapEntry(k, ChatUserModel.fromJson(e as Map)), + (k, e) => + MapEntry(k, ChatUserModel.fromJson(e as Map)), ), ); -Map _$$ChatRoomModelImplToJson(_$ChatRoomModelImpl instance) => { +Map _$$ChatRoomModelImplToJson(_$ChatRoomModelImpl instance) => + { 'id': instance.id, 'chat_room_setting': instance.chatRoomSettings, 'users': instance.users, diff --git a/lib/features/chat/models/chat_room_settings_model.freezed.dart b/lib/features/chat/models/chat_room_settings_model.freezed.dart index 48a1145..4f21755 100644 --- a/lib/features/chat/models/chat_room_settings_model.freezed.dart +++ b/lib/features/chat/models/chat_room_settings_model.freezed.dart @@ -14,36 +14,33 @@ 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'); -ChatRoomSettingsModel _$ChatRoomSettingsModelFromJson(Map json) { +ChatRoomSettingsModel _$ChatRoomSettingsModelFromJson( + Map json) { return _ChatRoomSettingsModel.fromJson(json); } /// @nodoc mixin _$ChatRoomSettingsModel { int get id => throw _privateConstructorUsedError; - @JsonKey(name: 'room_name') String get roomName => throw _privateConstructorUsedError; - String get state => throw _privateConstructorUsedError; - @JsonKey(name: 'access_level') String get accessLevel => throw _privateConstructorUsedError; - @JsonKey(name: 'updated_at') String get updatedAt => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $ChatRoomSettingsModelCopyWith get copyWith => throw _privateConstructorUsedError; + $ChatRoomSettingsModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatRoomSettingsModelCopyWith<$Res> { - factory $ChatRoomSettingsModelCopyWith(ChatRoomSettingsModel value, $Res Function(ChatRoomSettingsModel) then) = + factory $ChatRoomSettingsModelCopyWith(ChatRoomSettingsModel value, + $Res Function(ChatRoomSettingsModel) then) = _$ChatRoomSettingsModelCopyWithImpl<$Res, ChatRoomSettingsModel>; - @useResult $Res call( {int id, @@ -54,12 +51,13 @@ abstract class $ChatRoomSettingsModelCopyWith<$Res> { } /// @nodoc -class _$ChatRoomSettingsModelCopyWithImpl<$Res, $Val extends ChatRoomSettingsModel> implements $ChatRoomSettingsModelCopyWith<$Res> { +class _$ChatRoomSettingsModelCopyWithImpl<$Res, + $Val extends ChatRoomSettingsModel> + implements $ChatRoomSettingsModelCopyWith<$Res> { _$ChatRoomSettingsModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -98,10 +96,12 @@ class _$ChatRoomSettingsModelCopyWithImpl<$Res, $Val extends ChatRoomSettingsMod } /// @nodoc -abstract class _$$ChatRoomSettingsModelImplCopyWith<$Res> implements $ChatRoomSettingsModelCopyWith<$Res> { - factory _$$ChatRoomSettingsModelImplCopyWith(_$ChatRoomSettingsModelImpl value, $Res Function(_$ChatRoomSettingsModelImpl) then) = +abstract class _$$ChatRoomSettingsModelImplCopyWith<$Res> + implements $ChatRoomSettingsModelCopyWith<$Res> { + factory _$$ChatRoomSettingsModelImplCopyWith( + _$ChatRoomSettingsModelImpl value, + $Res Function(_$ChatRoomSettingsModelImpl) then) = __$$ChatRoomSettingsModelImplCopyWithImpl<$Res>; - @override @useResult $Res call( @@ -113,9 +113,13 @@ abstract class _$$ChatRoomSettingsModelImplCopyWith<$Res> implements $ChatRoomSe } /// @nodoc -class __$$ChatRoomSettingsModelImplCopyWithImpl<$Res> extends _$ChatRoomSettingsModelCopyWithImpl<$Res, _$ChatRoomSettingsModelImpl> +class __$$ChatRoomSettingsModelImplCopyWithImpl<$Res> + extends _$ChatRoomSettingsModelCopyWithImpl<$Res, + _$ChatRoomSettingsModelImpl> implements _$$ChatRoomSettingsModelImplCopyWith<$Res> { - __$$ChatRoomSettingsModelImplCopyWithImpl(_$ChatRoomSettingsModelImpl _value, $Res Function(_$ChatRoomSettingsModelImpl) _then) : super(_value, _then); + __$$ChatRoomSettingsModelImplCopyWithImpl(_$ChatRoomSettingsModelImpl _value, + $Res Function(_$ChatRoomSettingsModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -161,7 +165,8 @@ class _$ChatRoomSettingsModelImpl implements _ChatRoomSettingsModel { @JsonKey(name: 'access_level') required this.accessLevel, @JsonKey(name: 'updated_at') required this.updatedAt}); - factory _$ChatRoomSettingsModelImpl.fromJson(Map json) => _$$ChatRoomSettingsModelImplFromJson(json); + factory _$ChatRoomSettingsModelImpl.fromJson(Map json) => + _$$ChatRoomSettingsModelImplFromJson(json); @override final int id; @@ -188,21 +193,26 @@ class _$ChatRoomSettingsModelImpl implements _ChatRoomSettingsModel { (other.runtimeType == runtimeType && other is _$ChatRoomSettingsModelImpl && (identical(other.id, id) || other.id == id) && - (identical(other.roomName, roomName) || other.roomName == roomName) && + (identical(other.roomName, roomName) || + other.roomName == roomName) && (identical(other.state, state) || other.state == state) && - (identical(other.accessLevel, accessLevel) || other.accessLevel == accessLevel) && - (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt)); + (identical(other.accessLevel, accessLevel) || + other.accessLevel == accessLevel) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, roomName, state, accessLevel, updatedAt); + int get hashCode => + Object.hash(runtimeType, id, roomName, state, accessLevel, updatedAt); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> get copyWith => - __$$ChatRoomSettingsModelImplCopyWithImpl<_$ChatRoomSettingsModelImpl>(this, _$identity); + _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> + get copyWith => __$$ChatRoomSettingsModelImplCopyWithImpl< + _$ChatRoomSettingsModelImpl>(this, _$identity); @override Map toJson() { @@ -214,33 +224,31 @@ class _$ChatRoomSettingsModelImpl implements _ChatRoomSettingsModel { abstract class _ChatRoomSettingsModel implements ChatRoomSettingsModel { const factory _ChatRoomSettingsModel( - {required final int id, - @JsonKey(name: 'room_name') required final String roomName, - required final String state, - @JsonKey(name: 'access_level') required final String accessLevel, - @JsonKey(name: 'updated_at') required final String updatedAt}) = _$ChatRoomSettingsModelImpl; + {required final int id, + @JsonKey(name: 'room_name') required final String roomName, + required final String state, + @JsonKey(name: 'access_level') required final String accessLevel, + @JsonKey(name: 'updated_at') required final String updatedAt}) = + _$ChatRoomSettingsModelImpl; - factory _ChatRoomSettingsModel.fromJson(Map json) = _$ChatRoomSettingsModelImpl.fromJson; + factory _ChatRoomSettingsModel.fromJson(Map json) = + _$ChatRoomSettingsModelImpl.fromJson; @override int get id; - @override @JsonKey(name: 'room_name') String get roomName; - @override String get state; - @override @JsonKey(name: 'access_level') String get accessLevel; - @override @JsonKey(name: 'updated_at') String get updatedAt; - @override @JsonKey(ignore: true) - _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatRoomSettingsModelImplCopyWith<_$ChatRoomSettingsModelImpl> + get copyWith => throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_room_settings_model.g.dart b/lib/features/chat/models/chat_room_settings_model.g.dart index 1a2ef32..7b82433 100644 --- a/lib/features/chat/models/chat_room_settings_model.g.dart +++ b/lib/features/chat/models/chat_room_settings_model.g.dart @@ -6,7 +6,9 @@ part of 'chat_room_settings_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatRoomSettingsModelImpl _$$ChatRoomSettingsModelImplFromJson(Map json) => _$ChatRoomSettingsModelImpl( +_$ChatRoomSettingsModelImpl _$$ChatRoomSettingsModelImplFromJson( + Map json) => + _$ChatRoomSettingsModelImpl( id: (json['id'] as num).toInt(), roomName: json['room_name'] as String, state: json['state'] as String, @@ -14,7 +16,9 @@ _$ChatRoomSettingsModelImpl _$$ChatRoomSettingsModelImplFromJson(Map _$$ChatRoomSettingsModelImplToJson(_$ChatRoomSettingsModelImpl instance) => { +Map _$$ChatRoomSettingsModelImplToJson( + _$ChatRoomSettingsModelImpl instance) => + { 'id': instance.id, 'room_name': instance.roomName, 'state': instance.state, diff --git a/lib/features/chat/models/chat_user_model.freezed.dart b/lib/features/chat/models/chat_user_model.freezed.dart index 9077493..095c09e 100644 --- a/lib/features/chat/models/chat_user_model.freezed.dart +++ b/lib/features/chat/models/chat_user_model.freezed.dart @@ -21,36 +21,38 @@ ChatUserModel _$ChatUserModelFromJson(Map json) { /// @nodoc mixin _$ChatUserModel { int get id => throw _privateConstructorUsedError; - String get name => throw _privateConstructorUsedError; - @JsonKey(name: 'profile_photo_path') String? get profilePhotoPath => throw _privateConstructorUsedError; - @JsonKey(name: 'profile_photo_url') String? get profilePhotoUrl => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $ChatUserModelCopyWith get copyWith => throw _privateConstructorUsedError; + $ChatUserModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $ChatUserModelCopyWith<$Res> { - factory $ChatUserModelCopyWith(ChatUserModel value, $Res Function(ChatUserModel) then) = _$ChatUserModelCopyWithImpl<$Res, ChatUserModel>; - + factory $ChatUserModelCopyWith( + ChatUserModel value, $Res Function(ChatUserModel) then) = + _$ChatUserModelCopyWithImpl<$Res, ChatUserModel>; @useResult - $Res call({int id, String name, @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); + $Res call( + {int id, + String name, + @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, + @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); } /// @nodoc -class _$ChatUserModelCopyWithImpl<$Res, $Val extends ChatUserModel> implements $ChatUserModelCopyWith<$Res> { +class _$ChatUserModelCopyWithImpl<$Res, $Val extends ChatUserModel> + implements $ChatUserModelCopyWith<$Res> { _$ChatUserModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -84,17 +86,27 @@ class _$ChatUserModelCopyWithImpl<$Res, $Val extends ChatUserModel> implements $ } /// @nodoc -abstract class _$$ChatUserModelImplCopyWith<$Res> implements $ChatUserModelCopyWith<$Res> { - factory _$$ChatUserModelImplCopyWith(_$ChatUserModelImpl value, $Res Function(_$ChatUserModelImpl) then) = __$$ChatUserModelImplCopyWithImpl<$Res>; - +abstract class _$$ChatUserModelImplCopyWith<$Res> + implements $ChatUserModelCopyWith<$Res> { + factory _$$ChatUserModelImplCopyWith( + _$ChatUserModelImpl value, $Res Function(_$ChatUserModelImpl) then) = + __$$ChatUserModelImplCopyWithImpl<$Res>; @override @useResult - $Res call({int id, String name, @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); + $Res call( + {int id, + String name, + @JsonKey(name: 'profile_photo_path') String? profilePhotoPath, + @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl}); } /// @nodoc -class __$$ChatUserModelImplCopyWithImpl<$Res> extends _$ChatUserModelCopyWithImpl<$Res, _$ChatUserModelImpl> implements _$$ChatUserModelImplCopyWith<$Res> { - __$$ChatUserModelImplCopyWithImpl(_$ChatUserModelImpl _value, $Res Function(_$ChatUserModelImpl) _then) : super(_value, _then); +class __$$ChatUserModelImplCopyWithImpl<$Res> + extends _$ChatUserModelCopyWithImpl<$Res, _$ChatUserModelImpl> + implements _$$ChatUserModelImplCopyWith<$Res> { + __$$ChatUserModelImplCopyWithImpl( + _$ChatUserModelImpl _value, $Res Function(_$ChatUserModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -134,7 +146,8 @@ class _$ChatUserModelImpl implements _ChatUserModel { @JsonKey(name: 'profile_photo_path') this.profilePhotoPath, @JsonKey(name: 'profile_photo_url') this.profilePhotoUrl}); - factory _$ChatUserModelImpl.fromJson(Map json) => _$$ChatUserModelImplFromJson(json); + factory _$ChatUserModelImpl.fromJson(Map json) => + _$$ChatUserModelImplFromJson(json); @override final int id; @@ -159,18 +172,22 @@ class _$ChatUserModelImpl implements _ChatUserModel { other is _$ChatUserModelImpl && (identical(other.id, id) || other.id == id) && (identical(other.name, name) || other.name == name) && - (identical(other.profilePhotoPath, profilePhotoPath) || other.profilePhotoPath == profilePhotoPath) && - (identical(other.profilePhotoUrl, profilePhotoUrl) || other.profilePhotoUrl == profilePhotoUrl)); + (identical(other.profilePhotoPath, profilePhotoPath) || + other.profilePhotoPath == profilePhotoPath) && + (identical(other.profilePhotoUrl, profilePhotoUrl) || + other.profilePhotoUrl == profilePhotoUrl)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, name, profilePhotoPath, profilePhotoUrl); + int get hashCode => + Object.hash(runtimeType, id, name, profilePhotoPath, profilePhotoUrl); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => __$$ChatUserModelImplCopyWithImpl<_$ChatUserModelImpl>(this, _$identity); + _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => + __$$ChatUserModelImplCopyWithImpl<_$ChatUserModelImpl>(this, _$identity); @override Map toJson() { @@ -182,28 +199,27 @@ class _$ChatUserModelImpl implements _ChatUserModel { abstract class _ChatUserModel implements ChatUserModel { const factory _ChatUserModel( - {required final int id, - required final String name, - @JsonKey(name: 'profile_photo_path') final String? profilePhotoPath, - @JsonKey(name: 'profile_photo_url') final String? profilePhotoUrl}) = _$ChatUserModelImpl; + {required final int id, + required final String name, + @JsonKey(name: 'profile_photo_path') final String? profilePhotoPath, + @JsonKey(name: 'profile_photo_url') final String? profilePhotoUrl}) = + _$ChatUserModelImpl; - factory _ChatUserModel.fromJson(Map json) = _$ChatUserModelImpl.fromJson; + factory _ChatUserModel.fromJson(Map json) = + _$ChatUserModelImpl.fromJson; @override int get id; - @override String get name; - @override @JsonKey(name: 'profile_photo_path') String? get profilePhotoPath; - @override @JsonKey(name: 'profile_photo_url') String? get profilePhotoUrl; - @override @JsonKey(ignore: true) - _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatUserModelImplCopyWith<_$ChatUserModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/chat_user_model.g.dart b/lib/features/chat/models/chat_user_model.g.dart index 06fa92a..78e0f98 100644 --- a/lib/features/chat/models/chat_user_model.g.dart +++ b/lib/features/chat/models/chat_user_model.g.dart @@ -6,14 +6,16 @@ part of 'chat_user_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$ChatUserModelImpl _$$ChatUserModelImplFromJson(Map json) => _$ChatUserModelImpl( +_$ChatUserModelImpl _$$ChatUserModelImplFromJson(Map json) => + _$ChatUserModelImpl( id: (json['id'] as num).toInt(), name: json['name'] as String, profilePhotoPath: json['profile_photo_path'] as String?, profilePhotoUrl: json['profile_photo_url'] as String?, ); -Map _$$ChatUserModelImplToJson(_$ChatUserModelImpl instance) => { +Map _$$ChatUserModelImplToJson(_$ChatUserModelImpl instance) => + { 'id': instance.id, 'name': instance.name, 'profile_photo_path': instance.profilePhotoPath, diff --git a/lib/features/chat/models/websocket_info_model.freezed.dart b/lib/features/chat/models/websocket_info_model.freezed.dart index 002f2ec..cd383a2 100644 --- a/lib/features/chat/models/websocket_info_model.freezed.dart +++ b/lib/features/chat/models/websocket_info_model.freezed.dart @@ -21,38 +21,39 @@ WebsocketInfoModel _$WebsocketInfoModelFromJson(Map json) { /// @nodoc mixin _$WebsocketInfoModel { String get key => throw _privateConstructorUsedError; - String get host => throw _privateConstructorUsedError; - String get port => throw _privateConstructorUsedError; - String get cluster => throw _privateConstructorUsedError; - @JsonKey(name: 'user_id') int get userId => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $WebsocketInfoModelCopyWith get copyWith => throw _privateConstructorUsedError; + $WebsocketInfoModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $WebsocketInfoModelCopyWith<$Res> { - factory $WebsocketInfoModelCopyWith(WebsocketInfoModel value, $Res Function(WebsocketInfoModel) then) = + factory $WebsocketInfoModelCopyWith( + WebsocketInfoModel value, $Res Function(WebsocketInfoModel) then) = _$WebsocketInfoModelCopyWithImpl<$Res, WebsocketInfoModel>; - @useResult - $Res call({String key, String host, String port, String cluster, @JsonKey(name: 'user_id') int userId}); + $Res call( + {String key, + String host, + String port, + String cluster, + @JsonKey(name: 'user_id') int userId}); } /// @nodoc -class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel> implements $WebsocketInfoModelCopyWith<$Res> { +class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel> + implements $WebsocketInfoModelCopyWith<$Res> { _$WebsocketInfoModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -91,19 +92,28 @@ class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel> im } /// @nodoc -abstract class _$$WebsocketInfoModelImplCopyWith<$Res> implements $WebsocketInfoModelCopyWith<$Res> { - factory _$$WebsocketInfoModelImplCopyWith(_$WebsocketInfoModelImpl value, $Res Function(_$WebsocketInfoModelImpl) then) = +abstract class _$$WebsocketInfoModelImplCopyWith<$Res> + implements $WebsocketInfoModelCopyWith<$Res> { + factory _$$WebsocketInfoModelImplCopyWith(_$WebsocketInfoModelImpl value, + $Res Function(_$WebsocketInfoModelImpl) then) = __$$WebsocketInfoModelImplCopyWithImpl<$Res>; - @override @useResult - $Res call({String key, String host, String port, String cluster, @JsonKey(name: 'user_id') int userId}); + $Res call( + {String key, + String host, + String port, + String cluster, + @JsonKey(name: 'user_id') int userId}); } /// @nodoc -class __$$WebsocketInfoModelImplCopyWithImpl<$Res> extends _$WebsocketInfoModelCopyWithImpl<$Res, _$WebsocketInfoModelImpl> +class __$$WebsocketInfoModelImplCopyWithImpl<$Res> + extends _$WebsocketInfoModelCopyWithImpl<$Res, _$WebsocketInfoModelImpl> implements _$$WebsocketInfoModelImplCopyWith<$Res> { - __$$WebsocketInfoModelImplCopyWithImpl(_$WebsocketInfoModelImpl _value, $Res Function(_$WebsocketInfoModelImpl) _then) : super(_value, _then); + __$$WebsocketInfoModelImplCopyWithImpl(_$WebsocketInfoModelImpl _value, + $Res Function(_$WebsocketInfoModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -143,9 +153,14 @@ class __$$WebsocketInfoModelImplCopyWithImpl<$Res> extends _$WebsocketInfoModelC @JsonSerializable() class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { const _$WebsocketInfoModelImpl( - {required this.key, required this.host, required this.port, required this.cluster, @JsonKey(name: 'user_id') required this.userId}); + {required this.key, + required this.host, + required this.port, + required this.cluster, + @JsonKey(name: 'user_id') required this.userId}); - factory _$WebsocketInfoModelImpl.fromJson(Map json) => _$$WebsocketInfoModelImplFromJson(json); + factory _$WebsocketInfoModelImpl.fromJson(Map json) => + _$$WebsocketInfoModelImplFromJson(json); @override final String key; @@ -178,13 +193,15 @@ class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, key, host, port, cluster, userId); + int get hashCode => + Object.hash(runtimeType, key, host, port, cluster, userId); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith => - __$$WebsocketInfoModelImplCopyWithImpl<_$WebsocketInfoModelImpl>(this, _$identity); + __$$WebsocketInfoModelImplCopyWithImpl<_$WebsocketInfoModelImpl>( + this, _$identity); @override Map toJson() { @@ -196,31 +213,29 @@ class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { abstract class _WebsocketInfoModel implements WebsocketInfoModel { const factory _WebsocketInfoModel( - {required final String key, - required final String host, - required final String port, - required final String cluster, - @JsonKey(name: 'user_id') required final int userId}) = _$WebsocketInfoModelImpl; + {required final String key, + required final String host, + required final String port, + required final String cluster, + @JsonKey(name: 'user_id') required final int userId}) = + _$WebsocketInfoModelImpl; - factory _WebsocketInfoModel.fromJson(Map json) = _$WebsocketInfoModelImpl.fromJson; + factory _WebsocketInfoModel.fromJson(Map json) = + _$WebsocketInfoModelImpl.fromJson; @override String get key; - @override String get host; - @override String get port; - @override String get cluster; - @override @JsonKey(name: 'user_id') int get userId; - @override @JsonKey(ignore: true) - _$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/chat/models/websocket_info_model.g.dart b/lib/features/chat/models/websocket_info_model.g.dart index 91c386f..b2bb124 100644 --- a/lib/features/chat/models/websocket_info_model.g.dart +++ b/lib/features/chat/models/websocket_info_model.g.dart @@ -6,7 +6,9 @@ part of 'websocket_info_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson(Map json) => _$WebsocketInfoModelImpl( +_$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson( + Map json) => + _$WebsocketInfoModelImpl( key: json['key'] as String, host: json['host'] as String, port: json['port'] as String, @@ -14,7 +16,9 @@ _$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson(Map userId: (json['user_id'] as num).toInt(), ); -Map _$$WebsocketInfoModelImplToJson(_$WebsocketInfoModelImpl instance) => { +Map _$$WebsocketInfoModelImplToJson( + _$WebsocketInfoModelImpl instance) => + { 'key': instance.key, 'host': instance.host, 'port': instance.port, diff --git a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart index 0001c80..43bf9df 100644 --- a/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart +++ b/lib/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.freezed.dart @@ -20,16 +20,19 @@ mixin _$ChatRoomState { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, + required TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading) + loaded, required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; - @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult? Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult? Function(String errorMessage)? error, }) => throw _privateConstructorUsedError; @@ -37,7 +40,9 @@ mixin _$ChatRoomState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) => @@ -71,28 +76,36 @@ mixin _$ChatRoomState { /// @nodoc abstract class $ChatRoomStateCopyWith<$Res> { - factory $ChatRoomStateCopyWith(ChatRoomState value, $Res Function(ChatRoomState) then) = _$ChatRoomStateCopyWithImpl<$Res, ChatRoomState>; + factory $ChatRoomStateCopyWith( + ChatRoomState value, $Res Function(ChatRoomState) then) = + _$ChatRoomStateCopyWithImpl<$Res, ChatRoomState>; } /// @nodoc -class _$ChatRoomStateCopyWithImpl<$Res, $Val extends ChatRoomState> implements $ChatRoomStateCopyWith<$Res> { +class _$ChatRoomStateCopyWithImpl<$Res, $Val extends ChatRoomState> + implements $ChatRoomStateCopyWith<$Res> { _$ChatRoomStateCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; } /// @nodoc abstract class _$$ChatRoomStateImplCopyWith<$Res> { - factory _$$ChatRoomStateImplCopyWith(_$ChatRoomStateImpl value, $Res Function(_$ChatRoomStateImpl) then) = __$$ChatRoomStateImplCopyWithImpl<$Res>; + factory _$$ChatRoomStateImplCopyWith( + _$ChatRoomStateImpl value, $Res Function(_$ChatRoomStateImpl) then) = + __$$ChatRoomStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$ChatRoomStateImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateImpl> implements _$$ChatRoomStateImplCopyWith<$Res> { - __$$ChatRoomStateImplCopyWithImpl(_$ChatRoomStateImpl _value, $Res Function(_$ChatRoomStateImpl) _then) : super(_value, _then); +class __$$ChatRoomStateImplCopyWithImpl<$Res> + extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateImpl> + implements _$$ChatRoomStateImplCopyWith<$Res> { + __$$ChatRoomStateImplCopyWithImpl( + _$ChatRoomStateImpl _value, $Res Function(_$ChatRoomStateImpl) _then) + : super(_value, _then); } /// @nodoc @@ -107,7 +120,8 @@ class _$ChatRoomStateImpl implements _ChatRoomState { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$ChatRoomStateImpl); } @override @@ -118,7 +132,9 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, + required TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading) + loaded, required TResult Function(String errorMessage) error, }) { return $default(); @@ -129,7 +145,9 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult? Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult? Function(String errorMessage)? error, }) { return $default?.call(); @@ -140,7 +158,9 @@ class _$ChatRoomStateImpl implements _ChatRoomState { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -194,14 +214,18 @@ abstract class _ChatRoomState implements ChatRoomState { /// @nodoc abstract class _$$ChatRoomStateLoadingImplCopyWith<$Res> { - factory _$$ChatRoomStateLoadingImplCopyWith(_$ChatRoomStateLoadingImpl value, $Res Function(_$ChatRoomStateLoadingImpl) then) = + factory _$$ChatRoomStateLoadingImplCopyWith(_$ChatRoomStateLoadingImpl value, + $Res Function(_$ChatRoomStateLoadingImpl) then) = __$$ChatRoomStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$ChatRoomStateLoadingImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadingImpl> +class __$$ChatRoomStateLoadingImplCopyWithImpl<$Res> + extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadingImpl> implements _$$ChatRoomStateLoadingImplCopyWith<$Res> { - __$$ChatRoomStateLoadingImplCopyWithImpl(_$ChatRoomStateLoadingImpl _value, $Res Function(_$ChatRoomStateLoadingImpl) _then) : super(_value, _then); + __$$ChatRoomStateLoadingImplCopyWithImpl(_$ChatRoomStateLoadingImpl _value, + $Res Function(_$ChatRoomStateLoadingImpl) _then) + : super(_value, _then); } /// @nodoc @@ -216,7 +240,9 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateLoadingImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ChatRoomStateLoadingImpl); } @override @@ -227,7 +253,9 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, + required TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading) + loaded, required TResult Function(String errorMessage) error, }) { return loading(); @@ -238,7 +266,9 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult? Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult? Function(String errorMessage)? error, }) { return loading?.call(); @@ -249,7 +279,9 @@ class _$ChatRoomStateLoadingImpl implements ChatRoomStateLoading { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -303,19 +335,26 @@ abstract class ChatRoomStateLoading implements ChatRoomState { /// @nodoc abstract class _$$ChatRoomStateLoadedImplCopyWith<$Res> { - factory _$$ChatRoomStateLoadedImplCopyWith(_$ChatRoomStateLoadedImpl value, $Res Function(_$ChatRoomStateLoadedImpl) then) = + factory _$$ChatRoomStateLoadedImplCopyWith(_$ChatRoomStateLoadedImpl value, + $Res Function(_$ChatRoomStateLoadedImpl) then) = __$$ChatRoomStateLoadedImplCopyWithImpl<$Res>; - @useResult - $Res call({ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading}); + $Res call( + {ChatRoomModel chatRoom, + List chatMessages, + bool isTyping, + bool isLoading}); $ChatRoomModelCopyWith<$Res> get chatRoom; } /// @nodoc -class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadedImpl> +class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> + extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateLoadedImpl> implements _$$ChatRoomStateLoadedImplCopyWith<$Res> { - __$$ChatRoomStateLoadedImplCopyWithImpl(_$ChatRoomStateLoadedImpl _value, $Res Function(_$ChatRoomStateLoadedImpl) _then) : super(_value, _then); + __$$ChatRoomStateLoadedImplCopyWithImpl(_$ChatRoomStateLoadedImpl _value, + $Res Function(_$ChatRoomStateLoadedImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -357,13 +396,16 @@ class __$$ChatRoomStateLoadedImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyW /// @nodoc class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { - const _$ChatRoomStateLoadedImpl({required this.chatRoom, required final List chatMessages, required this.isTyping, required this.isLoading}) + const _$ChatRoomStateLoadedImpl( + {required this.chatRoom, + required final List chatMessages, + required this.isTyping, + required this.isLoading}) : _chatMessages = chatMessages; @override final ChatRoomModel chatRoom; final List _chatMessages; - @override List get chatMessages { if (_chatMessages is EqualUnmodifiableListView) return _chatMessages; @@ -386,27 +428,35 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateLoadedImpl && - (identical(other.chatRoom, chatRoom) || other.chatRoom == chatRoom) && - const DeepCollectionEquality().equals(other._chatMessages, _chatMessages) && - (identical(other.isTyping, isTyping) || other.isTyping == isTyping) && - (identical(other.isLoading, isLoading) || other.isLoading == isLoading)); + (identical(other.chatRoom, chatRoom) || + other.chatRoom == chatRoom) && + const DeepCollectionEquality() + .equals(other._chatMessages, _chatMessages) && + (identical(other.isTyping, isTyping) || + other.isTyping == isTyping) && + (identical(other.isLoading, isLoading) || + other.isLoading == isLoading)); } @override - int get hashCode => Object.hash(runtimeType, chatRoom, const DeepCollectionEquality().hash(_chatMessages), isTyping, isLoading); + int get hashCode => Object.hash(runtimeType, chatRoom, + const DeepCollectionEquality().hash(_chatMessages), isTyping, isLoading); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$ChatRoomStateLoadedImplCopyWith<_$ChatRoomStateLoadedImpl> get copyWith => - __$$ChatRoomStateLoadedImplCopyWithImpl<_$ChatRoomStateLoadedImpl>(this, _$identity); + __$$ChatRoomStateLoadedImplCopyWithImpl<_$ChatRoomStateLoadedImpl>( + this, _$identity); @override @optionalTypeArgs TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, + required TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading) + loaded, required TResult Function(String errorMessage) error, }) { return loaded(chatRoom, chatMessages, isTyping, isLoading); @@ -417,7 +467,9 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult? Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult? Function(String errorMessage)? error, }) { return loaded?.call(chatRoom, chatMessages, isTyping, isLoading); @@ -428,7 +480,9 @@ class _$ChatRoomStateLoadedImpl implements ChatRoomStateLoaded { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -484,30 +538,30 @@ abstract class ChatRoomStateLoaded implements ChatRoomState { required final bool isLoading}) = _$ChatRoomStateLoadedImpl; ChatRoomModel get chatRoom; - List get chatMessages; - bool get isTyping; - bool get isLoading; - @JsonKey(ignore: true) - _$$ChatRoomStateLoadedImplCopyWith<_$ChatRoomStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatRoomStateLoadedImplCopyWith<_$ChatRoomStateLoadedImpl> get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class _$$ChatRoomStateErrorImplCopyWith<$Res> { - factory _$$ChatRoomStateErrorImplCopyWith(_$ChatRoomStateErrorImpl value, $Res Function(_$ChatRoomStateErrorImpl) then) = + factory _$$ChatRoomStateErrorImplCopyWith(_$ChatRoomStateErrorImpl value, + $Res Function(_$ChatRoomStateErrorImpl) then) = __$$ChatRoomStateErrorImplCopyWithImpl<$Res>; - @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$ChatRoomStateErrorImplCopyWithImpl<$Res> extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateErrorImpl> +class __$$ChatRoomStateErrorImplCopyWithImpl<$Res> + extends _$ChatRoomStateCopyWithImpl<$Res, _$ChatRoomStateErrorImpl> implements _$$ChatRoomStateErrorImplCopyWith<$Res> { - __$$ChatRoomStateErrorImplCopyWithImpl(_$ChatRoomStateErrorImpl _value, $Res Function(_$ChatRoomStateErrorImpl) _then) : super(_value, _then); + __$$ChatRoomStateErrorImplCopyWithImpl(_$ChatRoomStateErrorImpl _value, + $Res Function(_$ChatRoomStateErrorImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -541,7 +595,8 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$ChatRoomStateErrorImpl && - (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); } @override @@ -551,14 +606,17 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { @override @pragma('vm:prefer-inline') _$$ChatRoomStateErrorImplCopyWith<_$ChatRoomStateErrorImpl> get copyWith => - __$$ChatRoomStateErrorImplCopyWithImpl<_$ChatRoomStateErrorImpl>(this, _$identity); + __$$ChatRoomStateErrorImplCopyWithImpl<_$ChatRoomStateErrorImpl>( + this, _$identity); @override @optionalTypeArgs TResult when( TResult Function() $default, { required TResult Function() loading, - required TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading) loaded, + required TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading) + loaded, required TResult Function(String errorMessage) error, }) { return error(errorMessage); @@ -569,7 +627,9 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { TResult? whenOrNull( TResult? Function()? $default, { TResult? Function()? loading, - TResult? Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult? Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult? Function(String errorMessage)? error, }) { return error?.call(errorMessage); @@ -580,7 +640,9 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { TResult maybeWhen( TResult Function()? $default, { TResult Function()? loading, - TResult Function(ChatRoomModel chatRoom, List chatMessages, bool isTyping, bool isLoading)? loaded, + TResult Function(ChatRoomModel chatRoom, + List chatMessages, bool isTyping, bool isLoading)? + loaded, TResult Function(String errorMessage)? error, required TResult orElse(), }) { @@ -629,10 +691,11 @@ class _$ChatRoomStateErrorImpl implements ChatRoomStateError { } abstract class ChatRoomStateError implements ChatRoomState { - const factory ChatRoomStateError({required final String errorMessage}) = _$ChatRoomStateErrorImpl; + const factory ChatRoomStateError({required final String errorMessage}) = + _$ChatRoomStateErrorImpl; String get errorMessage; - @JsonKey(ignore: true) - _$$ChatRoomStateErrorImplCopyWith<_$ChatRoomStateErrorImpl> get copyWith => throw _privateConstructorUsedError; + _$$ChatRoomStateErrorImplCopyWith<_$ChatRoomStateErrorImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/chat/presentation/pages/chat_screen.dart b/lib/features/chat/presentation/pages/chat_screen.dart index d474712..e6822c5 100644 --- a/lib/features/chat/presentation/pages/chat_screen.dart +++ b/lib/features/chat/presentation/pages/chat_screen.dart @@ -52,13 +52,9 @@ class _ChatScreenState extends State { _buildChat(BuildContext context, ChatRoomStateLoaded state) { return Scaffold( resizeToAvoidBottomInset: true, - backgroundColor: PrimaryColors().gray50, appBar: AppBar( titleSpacing: 0, centerTitle: false, - backgroundColor: Colors.white, - forceMaterialTransparency: true, - elevation: 0, title: Row( children: [ Container( @@ -156,7 +152,7 @@ class _ChatScreenState extends State { SizedBox(width: 8), InkWell( onTap: () {}, - borderRadius: BorderRadiusStyle.circleBorder17, + borderRadius: BorderRadius.circular(16), child: Ink( height: 32, width: 32, @@ -190,21 +186,21 @@ class _ChatScreenState extends State { ), filled: true, border: OutlineInputBorder( - borderRadius: BorderRadiusStyle.circleBorder17, + borderRadius: BorderRadius.circular(16), borderSide: BorderSide( color: Color(0xFFD1D1D6), width: 1, ), ), enabledBorder: OutlineInputBorder( - borderRadius: BorderRadiusStyle.circleBorder17, + borderRadius: BorderRadius.circular(16), borderSide: BorderSide( color: Color(0xFFD1D1D6), width: 1, ), ), focusedBorder: OutlineInputBorder( - borderRadius: BorderRadiusStyle.circleBorder17, + borderRadius: BorderRadius.circular(16), borderSide: BorderSide( color: Color(0xFFD1D1D6), width: 1, @@ -215,7 +211,7 @@ class _ChatScreenState extends State { ), SizedBox(width: 8), InkWell( - borderRadius: BorderRadiusStyle.circleBorder17, + borderRadius: BorderRadius.circular(16), onTap: () { if (textEditingController.text.isNotEmpty) { context.read().sendMessage( 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 1b8b49e..15f6c44 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 @@ -103,7 +103,7 @@ class CustomSearchView extends StatelessWidget { hintStyle: hintStyle ?? CustomTextStyles.bodySmallMulishBluegray800, prefixIcon: prefix ?? Padding( - padding: EdgeInsets.only(left: 10), + padding: EdgeInsets.only(left: 12), child: Icon( Icons.search, color: Color(0xFF7B8794), @@ -127,17 +127,17 @@ class CustomSearchView extends StatelessWidget { filled: filled, border: borderDecoration ?? OutlineInputBorder( - borderRadius: BorderRadius.circular(8.h), + borderRadius: BorderRadius.circular(16), borderSide: BorderSide.none, ), enabledBorder: borderDecoration ?? OutlineInputBorder( - borderRadius: BorderRadius.circular(8.h), + borderRadius: BorderRadius.circular(16), borderSide: BorderSide.none, ), focusedBorder: borderDecoration ?? OutlineInputBorder( - borderRadius: BorderRadius.circular(8.h), + borderRadius: BorderRadius.circular(16), borderSide: BorderSide.none, ), ); 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 fb48d2e..9fea543 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 @@ -86,7 +86,7 @@ _buildChatList(BuildContext context, ChatSelectLoadedState state) { physics: NeverScrollableScrollPhysics(), separatorBuilder: (context, index) { return SizedBox( - height: 10.v, + height: 8, ); }, itemCount: state.chatRooms?.length ?? 0, 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 0e46e71..03c8371 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 @@ -16,7 +16,7 @@ class ChatEntryWidget extends StatelessWidget { @override Widget build(BuildContext context) { return InkWell( - borderRadius: BorderRadiusStyle.circleBorder8, + borderRadius: BorderRadius.circular(16), onTap: () => GoRouter.of(context).pushNamed( 'chatScreen', extra: chatEntryObj.id.toString(), @@ -24,7 +24,7 @@ class ChatEntryWidget extends StatelessWidget { child: Ink( padding: EdgeInsets.all(16), decoration: BoxDecoration( - borderRadius: BorderRadiusStyle.circleBorder8, + borderRadius: BorderRadius.circular(16), color: Color(0xFFF6FAFF), ), child: Row( diff --git a/lib/features/chat/presentation/widgets/chat_bubble_widget.dart b/lib/features/chat/presentation/widgets/chat_bubble_widget.dart index 5a773cc..555aa23 100644 --- a/lib/features/chat/presentation/widgets/chat_bubble_widget.dart +++ b/lib/features/chat/presentation/widgets/chat_bubble_widget.dart @@ -26,7 +26,7 @@ class ChatBubbleWidget extends StatelessWidget { alignment: isCurrentUser ? Alignment.centerRight : Alignment.centerLeft, child: DecoratedBox( decoration: BoxDecoration( - color: isCurrentUser ? Color(0xFFF6FAFF) : Colors.white, + color: isCurrentUser ? Color(0xFF7F9CF5) : Colors.white, borderRadius: BorderRadiusStyle.circleBorder17, ), child: Padding( @@ -102,7 +102,7 @@ class ChatBubbleWidget extends StatelessWidget { Text( text, style: TextStyle( - color: Color(0xFF323F4B), + color: isCurrentUser ? Colors.white : Color(0xFF323F4B), ), ), ], diff --git a/lib/features/chat/services/chat_service.g.dart b/lib/features/chat/services/chat_service.g.dart index 8d212c4..2f0674b 100644 --- a/lib/features/chat/services/chat_service.g.dart +++ b/lib/features/chat/services/chat_service.g.dart @@ -24,23 +24,25 @@ class _ChatService implements ChatService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType>(Options( + final _result = await _dio.fetch>( + _setStreamType>(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/chat/show/${id}', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); - var _value = _result.data!.map((k, dynamic v) => MapEntry(k, ChatRoomModel.fromJson(v as Map))); + .compose( + _dio.options, + '/api/chat/show/${id}', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + var _value = _result.data!.map((k, dynamic v) => + MapEntry(k, ChatRoomModel.fromJson(v as Map))); return _value; } @@ -96,22 +98,23 @@ class _ChatService implements ChatService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio + .fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/chat/show/${id}/messages?page=${page}', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/chat/show/${id}/messages?page=${page}', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = ChatMessagesModel.fromJson(_result.data!); return _value; } @@ -122,28 +125,31 @@ class _ChatService implements ChatService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio + .fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/profile/ws/params', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/profile/ws/params', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = WebsocketInfoModel.fromJson(_result.data!); return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && + !(requestOptions.responseType == ResponseType.bytes || + requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { diff --git a/lib/features/diary/models/meal.freezed.dart b/lib/features/diary/models/meal.freezed.dart index 3f7f068..2c249b0 100644 --- a/lib/features/diary/models/meal.freezed.dart +++ b/lib/features/diary/models/meal.freezed.dart @@ -21,21 +21,14 @@ Meal _$MealFromJson(Map json) { /// @nodoc mixin _$Meal { int get id => throw _privateConstructorUsedError; - String get time => throw _privateConstructorUsedError; - int get type => throw _privateConstructorUsedError; - int get satiety => throw _privateConstructorUsedError; - int get mood => throw _privateConstructorUsedError; - List get portions => throw _privateConstructorUsedError; - List get photos => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) $MealCopyWith get copyWith => throw _privateConstructorUsedError; } @@ -43,16 +36,16 @@ mixin _$Meal { /// @nodoc abstract class $MealCopyWith<$Res> { factory $MealCopyWith(Meal value, $Res Function(Meal) then) = - _$MealCopyWithImpl<$Res, Meal>; - + _$MealCopyWithImpl<$Res, Meal>; @useResult - $Res call({int id, - String time, - int type, - int satiety, - int mood, - List portions, - List photos}); + $Res call( + {int id, + String time, + int type, + int satiety, + int mood, + List portions, + List photos}); } /// @nodoc @@ -62,7 +55,6 @@ class _$MealCopyWithImpl<$Res, $Val extends Meal> // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -81,53 +73,55 @@ class _$MealCopyWithImpl<$Res, $Val extends Meal> id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, time: null == time ? _value.time : time // ignore: cast_nullable_to_non_nullable - as String, + as String, type: null == type ? _value.type : type // ignore: cast_nullable_to_non_nullable - as int, + as int, satiety: null == satiety ? _value.satiety : satiety // ignore: cast_nullable_to_non_nullable - as int, + as int, mood: null == mood ? _value.mood : mood // ignore: cast_nullable_to_non_nullable - as int, + as int, portions: null == portions ? _value.portions : portions // ignore: cast_nullable_to_non_nullable - as List, + as List, photos: null == photos ? _value.photos : photos // ignore: cast_nullable_to_non_nullable - as List, + as List, ) as $Val); } } /// @nodoc abstract class _$$MealImplCopyWith<$Res> implements $MealCopyWith<$Res> { - factory _$$MealImplCopyWith(_$MealImpl value, $Res Function(_$MealImpl) then) = - __$$MealImplCopyWithImpl<$Res>; - + factory _$$MealImplCopyWith( + _$MealImpl value, $Res Function(_$MealImpl) then) = + __$$MealImplCopyWithImpl<$Res>; @override @useResult - $Res call({int id, - String time, - int type, - int satiety, - int mood, - List portions, - List photos}); + $Res call( + {int id, + String time, + int type, + int satiety, + int mood, + List portions, + List photos}); } /// @nodoc -class __$$MealImplCopyWithImpl<$Res> extends _$MealCopyWithImpl<$Res, _$MealImpl> +class __$$MealImplCopyWithImpl<$Res> + extends _$MealCopyWithImpl<$Res, _$MealImpl> implements _$$MealImplCopyWith<$Res> { __$$MealImplCopyWithImpl(_$MealImpl _value, $Res Function(_$MealImpl) _then) : super(_value, _then); @@ -147,31 +141,31 @@ class __$$MealImplCopyWithImpl<$Res> extends _$MealCopyWithImpl<$Res, _$MealImpl id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, time: null == time ? _value.time : time // ignore: cast_nullable_to_non_nullable - as String, + as String, type: null == type ? _value.type : type // ignore: cast_nullable_to_non_nullable - as int, + as int, satiety: null == satiety ? _value.satiety : satiety // ignore: cast_nullable_to_non_nullable - as int, + as int, mood: null == mood ? _value.mood : mood // ignore: cast_nullable_to_non_nullable - as int, + as int, portions: null == portions ? _value._portions : portions // ignore: cast_nullable_to_non_nullable - as List, + as List, photos: null == photos ? _value._photos : photos // ignore: cast_nullable_to_non_nullable - as List, + as List, )); } } @@ -179,13 +173,14 @@ class __$$MealImplCopyWithImpl<$Res> extends _$MealCopyWithImpl<$Res, _$MealImpl /// @nodoc @JsonSerializable() class _$MealImpl implements _Meal { - const _$MealImpl({required this.id, - required this.time, - required this.type, - required this.satiety, - required this.mood, - required final List portions, - required final List photos}) + const _$MealImpl( + {required this.id, + required this.time, + required this.type, + required this.satiety, + required this.mood, + required final List portions, + required final List photos}) : _portions = portions, _photos = photos; @@ -203,7 +198,6 @@ class _$MealImpl implements _Meal { @override final int mood; final List _portions; - @override List get portions { if (_portions is EqualUnmodifiableListView) return _portions; @@ -212,7 +206,6 @@ class _$MealImpl implements _Meal { } final List _photos; - @override List get photos { if (_photos is EqualUnmodifiableListView) return _photos; @@ -241,16 +234,15 @@ class _$MealImpl implements _Meal { @JsonKey(ignore: true) @override - int get hashCode => - Object.hash( - runtimeType, - id, - time, - type, - satiety, - mood, - const DeepCollectionEquality().hash(_portions), - const DeepCollectionEquality().hash(_photos)); + int get hashCode => Object.hash( + runtimeType, + id, + time, + type, + satiety, + mood, + const DeepCollectionEquality().hash(_portions), + const DeepCollectionEquality().hash(_photos)); @JsonKey(ignore: true) @override @@ -267,37 +259,31 @@ class _$MealImpl implements _Meal { } abstract class _Meal implements Meal { - const factory _Meal({required final int id, - required final String time, - required final int type, - required final int satiety, - required final int mood, - required final List portions, - required final List photos}) = _$MealImpl; + const factory _Meal( + {required final int id, + required final String time, + required final int type, + required final int satiety, + required final int mood, + required final List portions, + required final List photos}) = _$MealImpl; factory _Meal.fromJson(Map json) = _$MealImpl.fromJson; @override int get id; - @override String get time; - @override int get type; - @override int get satiety; - @override int get mood; - @override List get portions; - @override List get photos; - @override @JsonKey(ignore: true) _$$MealImplCopyWith<_$MealImpl> get copyWith => diff --git a/lib/features/diary/models/meal.g.dart b/lib/features/diary/models/meal.g.dart index d6c9adf..5536ed9 100644 --- a/lib/features/diary/models/meal.g.dart +++ b/lib/features/diary/models/meal.g.dart @@ -6,8 +6,7 @@ part of 'meal.dart'; // JsonSerializableGenerator // ************************************************************************** -_$MealImpl _$$MealImplFromJson(Map json) => - _$MealImpl( +_$MealImpl _$$MealImplFromJson(Map json) => _$MealImpl( id: (json['id'] as num).toInt(), time: json['time'] as String, type: (json['type'] as num).toInt(), diff --git a/lib/features/diary/models/photo.freezed.dart b/lib/features/diary/models/photo.freezed.dart index b58eceb..2d9c70b 100644 --- a/lib/features/diary/models/photo.freezed.dart +++ b/lib/features/diary/models/photo.freezed.dart @@ -21,14 +21,11 @@ Photo _$PhotoFromJson(Map json) { /// @nodoc mixin _$Photo { int get id => throw _privateConstructorUsedError; - @JsonKey(name: 'original_name') String get originalName => throw _privateConstructorUsedError; - String get path => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) $PhotoCopyWith get copyWith => throw _privateConstructorUsedError; } @@ -36,12 +33,12 @@ mixin _$Photo { /// @nodoc abstract class $PhotoCopyWith<$Res> { factory $PhotoCopyWith(Photo value, $Res Function(Photo) then) = - _$PhotoCopyWithImpl<$Res, Photo>; - + _$PhotoCopyWithImpl<$Res, Photo>; @useResult - $Res call({int id, - @JsonKey(name: 'original_name') String originalName, - String path}); + $Res call( + {int id, + @JsonKey(name: 'original_name') String originalName, + String path}); } /// @nodoc @@ -51,7 +48,6 @@ class _$PhotoCopyWithImpl<$Res, $Val extends Photo> // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -66,35 +62,38 @@ class _$PhotoCopyWithImpl<$Res, $Val extends Photo> id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, originalName: null == originalName ? _value.originalName : originalName // ignore: cast_nullable_to_non_nullable - as String, + as String, path: null == path ? _value.path : path // ignore: cast_nullable_to_non_nullable - as String, + as String, ) as $Val); } } /// @nodoc abstract class _$$PhotoImplCopyWith<$Res> implements $PhotoCopyWith<$Res> { - factory _$$PhotoImplCopyWith(_$PhotoImpl value, $Res Function(_$PhotoImpl) then) = - __$$PhotoImplCopyWithImpl<$Res>; - + factory _$$PhotoImplCopyWith( + _$PhotoImpl value, $Res Function(_$PhotoImpl) then) = + __$$PhotoImplCopyWithImpl<$Res>; @override @useResult - $Res call({int id, - @JsonKey(name: 'original_name') String originalName, - String path}); + $Res call( + {int id, + @JsonKey(name: 'original_name') String originalName, + String path}); } /// @nodoc -class __$$PhotoImplCopyWithImpl<$Res> extends _$PhotoCopyWithImpl<$Res, _$PhotoImpl> +class __$$PhotoImplCopyWithImpl<$Res> + extends _$PhotoCopyWithImpl<$Res, _$PhotoImpl> implements _$$PhotoImplCopyWith<$Res> { - __$$PhotoImplCopyWithImpl(_$PhotoImpl _value, $Res Function(_$PhotoImpl) _then) + __$$PhotoImplCopyWithImpl( + _$PhotoImpl _value, $Res Function(_$PhotoImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -108,15 +107,15 @@ class __$$PhotoImplCopyWithImpl<$Res> extends _$PhotoCopyWithImpl<$Res, _$PhotoI id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, originalName: null == originalName ? _value.originalName : originalName // ignore: cast_nullable_to_non_nullable - as String, + as String, path: null == path ? _value.path : path // ignore: cast_nullable_to_non_nullable - as String, + as String, )); } } @@ -124,9 +123,10 @@ class __$$PhotoImplCopyWithImpl<$Res> extends _$PhotoCopyWithImpl<$Res, _$PhotoI /// @nodoc @JsonSerializable() class _$PhotoImpl implements _Photo { - const _$PhotoImpl({required this.id, - @JsonKey(name: 'original_name') required this.originalName, - required this.path}); + const _$PhotoImpl( + {required this.id, + @JsonKey(name: 'original_name') required this.originalName, + required this.path}); factory _$PhotoImpl.fromJson(Map json) => _$$PhotoImplFromJson(json); @@ -174,22 +174,20 @@ class _$PhotoImpl implements _Photo { } abstract class _Photo implements Photo { - const factory _Photo({required final int id, - @JsonKey(name: 'original_name') required final String originalName, - required final String path}) = _$PhotoImpl; + const factory _Photo( + {required final int id, + @JsonKey(name: 'original_name') required final String originalName, + required final String path}) = _$PhotoImpl; factory _Photo.fromJson(Map json) = _$PhotoImpl.fromJson; @override int get id; - @override @JsonKey(name: 'original_name') String get originalName; - @override String get path; - @override @JsonKey(ignore: true) _$$PhotoImplCopyWith<_$PhotoImpl> get copyWith => diff --git a/lib/features/diary/models/photo.g.dart b/lib/features/diary/models/photo.g.dart index 19711bb..cacf65a 100644 --- a/lib/features/diary/models/photo.g.dart +++ b/lib/features/diary/models/photo.g.dart @@ -6,8 +6,7 @@ part of 'photo.dart'; // JsonSerializableGenerator // ************************************************************************** -_$PhotoImpl _$$PhotoImplFromJson(Map json) => - _$PhotoImpl( +_$PhotoImpl _$$PhotoImplFromJson(Map json) => _$PhotoImpl( id: (json['id'] as num).toInt(), originalName: json['original_name'] as String, path: json['path'] as String, diff --git a/lib/features/diary/models/portion.freezed.dart b/lib/features/diary/models/portion.freezed.dart index b909af6..a7a35a2 100644 --- a/lib/features/diary/models/portion.freezed.dart +++ b/lib/features/diary/models/portion.freezed.dart @@ -21,15 +21,11 @@ Portion _$PortionFromJson(Map json) { /// @nodoc mixin _$Portion { int get id => throw _privateConstructorUsedError; - String get product_name => throw _privateConstructorUsedError; - int get quantity => throw _privateConstructorUsedError; - String get portion => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) $PortionCopyWith get copyWith => throw _privateConstructorUsedError; } @@ -37,8 +33,7 @@ mixin _$Portion { /// @nodoc abstract class $PortionCopyWith<$Res> { factory $PortionCopyWith(Portion value, $Res Function(Portion) then) = - _$PortionCopyWithImpl<$Res, Portion>; - + _$PortionCopyWithImpl<$Res, Portion>; @useResult $Res call({int id, String product_name, int quantity, String portion}); } @@ -50,7 +45,6 @@ class _$PortionCopyWithImpl<$Res, $Val extends Portion> // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -66,37 +60,39 @@ class _$PortionCopyWithImpl<$Res, $Val extends Portion> id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, product_name: null == product_name ? _value.product_name : product_name // ignore: cast_nullable_to_non_nullable - as String, + as String, quantity: null == quantity ? _value.quantity : quantity // ignore: cast_nullable_to_non_nullable - as int, + as int, portion: null == portion ? _value.portion : portion // ignore: cast_nullable_to_non_nullable - as String, + as String, ) as $Val); } } /// @nodoc abstract class _$$PortionImplCopyWith<$Res> implements $PortionCopyWith<$Res> { - factory _$$PortionImplCopyWith(_$PortionImpl value, $Res Function(_$PortionImpl) then) = - __$$PortionImplCopyWithImpl<$Res>; - + factory _$$PortionImplCopyWith( + _$PortionImpl value, $Res Function(_$PortionImpl) then) = + __$$PortionImplCopyWithImpl<$Res>; @override @useResult $Res call({int id, String product_name, int quantity, String portion}); } /// @nodoc -class __$$PortionImplCopyWithImpl<$Res> extends _$PortionCopyWithImpl<$Res, _$PortionImpl> +class __$$PortionImplCopyWithImpl<$Res> + extends _$PortionCopyWithImpl<$Res, _$PortionImpl> implements _$$PortionImplCopyWith<$Res> { - __$$PortionImplCopyWithImpl(_$PortionImpl _value, $Res Function(_$PortionImpl) _then) + __$$PortionImplCopyWithImpl( + _$PortionImpl _value, $Res Function(_$PortionImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -111,19 +107,19 @@ class __$$PortionImplCopyWithImpl<$Res> extends _$PortionCopyWithImpl<$Res, _$Po id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, product_name: null == product_name ? _value.product_name : product_name // ignore: cast_nullable_to_non_nullable - as String, + as String, quantity: null == quantity ? _value.quantity : quantity // ignore: cast_nullable_to_non_nullable - as int, + as int, portion: null == portion ? _value.portion : portion // ignore: cast_nullable_to_non_nullable - as String, + as String, )); } } @@ -131,10 +127,11 @@ class __$$PortionImplCopyWithImpl<$Res> extends _$PortionCopyWithImpl<$Res, _$Po /// @nodoc @JsonSerializable() class _$PortionImpl implements _Portion { - const _$PortionImpl({required this.id, - required this.product_name, - required this.quantity, - required this.portion}); + const _$PortionImpl( + {required this.id, + required this.product_name, + required this.quantity, + required this.portion}); factory _$PortionImpl.fromJson(Map json) => _$$PortionImplFromJson(json); @@ -186,25 +183,22 @@ class _$PortionImpl implements _Portion { } abstract class _Portion implements Portion { - const factory _Portion({required final int id, - required final String product_name, - required final int quantity, - required final String portion}) = _$PortionImpl; + const factory _Portion( + {required final int id, + required final String product_name, + required final int quantity, + required final String portion}) = _$PortionImpl; factory _Portion.fromJson(Map json) = _$PortionImpl.fromJson; @override int get id; - @override String get product_name; - @override int get quantity; - @override String get portion; - @override @JsonKey(ignore: true) _$$PortionImplCopyWith<_$PortionImpl> get copyWith => diff --git a/lib/features/diary/models/product.freezed.dart b/lib/features/diary/models/product.freezed.dart index d4c87df..d30ada3 100644 --- a/lib/features/diary/models/product.freezed.dart +++ b/lib/features/diary/models/product.freezed.dart @@ -21,11 +21,9 @@ Product _$ProductFromJson(Map json) { /// @nodoc mixin _$Product { int get id => throw _privateConstructorUsedError; - String get name => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) $ProductCopyWith get copyWith => throw _privateConstructorUsedError; } @@ -33,8 +31,7 @@ mixin _$Product { /// @nodoc abstract class $ProductCopyWith<$Res> { factory $ProductCopyWith(Product value, $Res Function(Product) then) = - _$ProductCopyWithImpl<$Res, Product>; - + _$ProductCopyWithImpl<$Res, Product>; @useResult $Res call({int id, String name}); } @@ -46,7 +43,6 @@ class _$ProductCopyWithImpl<$Res, $Val extends Product> // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -60,29 +56,31 @@ class _$ProductCopyWithImpl<$Res, $Val extends Product> id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, name: null == name ? _value.name : name // ignore: cast_nullable_to_non_nullable - as String, + as String, ) as $Val); } } /// @nodoc abstract class _$$ProductImplCopyWith<$Res> implements $ProductCopyWith<$Res> { - factory _$$ProductImplCopyWith(_$ProductImpl value, $Res Function(_$ProductImpl) then) = - __$$ProductImplCopyWithImpl<$Res>; - + factory _$$ProductImplCopyWith( + _$ProductImpl value, $Res Function(_$ProductImpl) then) = + __$$ProductImplCopyWithImpl<$Res>; @override @useResult $Res call({int id, String name}); } /// @nodoc -class __$$ProductImplCopyWithImpl<$Res> extends _$ProductCopyWithImpl<$Res, _$ProductImpl> +class __$$ProductImplCopyWithImpl<$Res> + extends _$ProductCopyWithImpl<$Res, _$ProductImpl> implements _$$ProductImplCopyWith<$Res> { - __$$ProductImplCopyWithImpl(_$ProductImpl _value, $Res Function(_$ProductImpl) _then) + __$$ProductImplCopyWithImpl( + _$ProductImpl _value, $Res Function(_$ProductImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -95,11 +93,11 @@ class __$$ProductImplCopyWithImpl<$Res> extends _$ProductCopyWithImpl<$Res, _$Pr id: null == id ? _value.id : id // ignore: cast_nullable_to_non_nullable - as int, + as int, name: null == name ? _value.name : name // ignore: cast_nullable_to_non_nullable - as String, + as String, )); } } @@ -151,16 +149,14 @@ class _$ProductImpl implements _Product { abstract class _Product implements Product { const factory _Product({required final int id, required final String name}) = - _$ProductImpl; + _$ProductImpl; factory _Product.fromJson(Map json) = _$ProductImpl.fromJson; @override int get id; - @override String get name; - @override @JsonKey(ignore: true) _$$ProductImplCopyWith<_$ProductImpl> get copyWith => diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index fb78189..047dc64 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -1,5 +1,6 @@ // ignore_for_file: unused_local_variable +import 'package:carousel_slider_plus/carousel_slider_plus.dart'; import 'package:eatvio_app/features/diary/models/diary_model.dart'; import 'package:eatvio_app/features/diary/models/meal.dart'; import 'package:eatvio_app/features/diary/models/photo.dart'; @@ -18,7 +19,6 @@ import 'package:flutter/services.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:image_picker/image_picker.dart'; -import 'package:carousel_slider/carousel_slider.dart'; import 'package:syncfusion_flutter_charts/charts.dart'; // ignore: must_be_immutable diff --git a/lib/features/feed/models/diets_pagination_model.dart b/lib/features/feed/models/diets_pagination_model.dart new file mode 100644 index 0000000..10fb6af --- /dev/null +++ b/lib/features/feed/models/diets_pagination_model.dart @@ -0,0 +1,133 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'diets_pagination_model.freezed.dart'; +part 'diets_pagination_model.g.dart'; + +@freezed +class DietsPagination with _$DietsPagination { + const factory DietsPagination({ + @JsonKey(name: "data") required List data, + @JsonKey(name: "links") required Links links, + @JsonKey(name: "meta") required Meta meta, + }) = _DietsPagination; + + factory DietsPagination.fromJson(Map json) => _$DietsPaginationFromJson(json); +} + +@freezed +class Datum with _$Datum { + const factory Datum({ + @JsonKey(name: "id") required int id, + @JsonKey(name: "name") required String name, + @JsonKey(name: "image") required String image, + @JsonKey(name: "duration") required int duration, + @JsonKey(name: "state") required String state, + @JsonKey(name: "type") required Type type, + @JsonKey(name: "details") required String details, + @JsonKey(name: "daily_schedule") required List>> dailySchedule, + @JsonKey(name: "author") required Author author, + @JsonKey(name: "total_likes") required int totalLikes, + @JsonKey(name: "total_views") required int totalViews, + @JsonKey(name: "total_comments") required int totalComments, + }) = _Datum; + + factory Datum.fromJson(Map json) => _$DatumFromJson(json); +} + +@freezed +class Author with _$Author { + const factory Author({ + @JsonKey(name: "author_slug") required String authorSlug, + @JsonKey(name: "author_name") required String authorName, + @JsonKey(name: "author_profile_icon") required String authorProfileIcon, + @JsonKey(name: "author_is_me") required bool authorIsMe, + }) = _Author; + + factory Author.fromJson(Map json) => _$AuthorFromJson(json); +} + +@freezed +class DailySchedule with _$DailySchedule { + const factory DailySchedule({ + @JsonKey(name: "name") required String name, + @JsonKey(name: "uniq") required String uniq, + @JsonKey(name: "portion") required Portion portion, + @JsonKey(name: "quantity") required int quantity, + }) = _DailySchedule; + + factory DailySchedule.fromJson(Map json) => _$DailyScheduleFromJson(json); +} + +enum Portion { + @JsonValue("grams") + GRAMS, + @JsonValue("milliliters") + MILLILITERS, + @JsonValue("pcs") + PCS +} + +final portionValues = EnumValues({"grams": Portion.GRAMS, "milliliters": Portion.MILLILITERS, "pcs": Portion.PCS}); + +@freezed +class Type with _$Type { + const factory Type({ + @JsonKey(name: "alko") bool? alko, + @JsonKey(name: "veg") bool? veg, + @JsonKey(name: "corb") bool? corb, + @JsonKey(name: "meat") bool? meat, + }) = _Type; + + factory Type.fromJson(Map json) => _$TypeFromJson(json); +} + +@freezed +class Links with _$Links { + const factory Links({ + @JsonKey(name: "first") required String first, + @JsonKey(name: "last") required String last, + @JsonKey(name: "prev") required dynamic prev, + @JsonKey(name: "next") required dynamic next, + }) = _Links; + + factory Links.fromJson(Map json) => _$LinksFromJson(json); +} + +@freezed +class Meta with _$Meta { + const factory Meta({ + @JsonKey(name: "current_page") required int currentPage, + @JsonKey(name: "from") required int from, + @JsonKey(name: "last_page") required int lastPage, + @JsonKey(name: "links") required List links, + @JsonKey(name: "path") required String path, + @JsonKey(name: "per_page") required int perPage, + @JsonKey(name: "to") required int to, + @JsonKey(name: "total") required int total, + }) = _Meta; + + factory Meta.fromJson(Map json) => _$MetaFromJson(json); +} + +@freezed +class Link with _$Link { + const factory Link({ + @JsonKey(name: "url") required String? url, + @JsonKey(name: "label") required String label, + @JsonKey(name: "active") required bool active, + }) = _Link; + + factory Link.fromJson(Map json) => _$LinkFromJson(json); +} + +class EnumValues { + Map map; + late Map reverseMap; + + EnumValues(this.map); + + Map get reverse { + reverseMap = map.map((k, v) => MapEntry(v, k)); + return reverseMap; + } +} diff --git a/lib/features/feed/models/diets_pagination_model.freezed.dart b/lib/features/feed/models/diets_pagination_model.freezed.dart new file mode 100644 index 0000000..2c40267 --- /dev/null +++ b/lib/features/feed/models/diets_pagination_model.freezed.dart @@ -0,0 +1,2026 @@ +// 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 'diets_pagination_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'); + +DietsPagination _$DietsPaginationFromJson(Map json) { + return _DietsPagination.fromJson(json); +} + +/// @nodoc +mixin _$DietsPagination { + @JsonKey(name: "data") + List get data => throw _privateConstructorUsedError; + @JsonKey(name: "links") + Links get links => throw _privateConstructorUsedError; + @JsonKey(name: "meta") + Meta get meta => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $DietsPaginationCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DietsPaginationCopyWith<$Res> { + factory $DietsPaginationCopyWith( + DietsPagination value, $Res Function(DietsPagination) then) = + _$DietsPaginationCopyWithImpl<$Res, DietsPagination>; + @useResult + $Res call( + {@JsonKey(name: "data") List data, + @JsonKey(name: "links") Links links, + @JsonKey(name: "meta") Meta meta}); + + $LinksCopyWith<$Res> get links; + $MetaCopyWith<$Res> get meta; +} + +/// @nodoc +class _$DietsPaginationCopyWithImpl<$Res, $Val extends DietsPagination> + implements $DietsPaginationCopyWith<$Res> { + _$DietsPaginationCopyWithImpl(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? data = null, + Object? links = null, + Object? meta = null, + }) { + return _then(_value.copyWith( + data: null == data + ? _value.data + : data // ignore: cast_nullable_to_non_nullable + as List, + links: null == links + ? _value.links + : links // ignore: cast_nullable_to_non_nullable + as Links, + meta: null == meta + ? _value.meta + : meta // ignore: cast_nullable_to_non_nullable + as Meta, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $LinksCopyWith<$Res> get links { + return $LinksCopyWith<$Res>(_value.links, (value) { + return _then(_value.copyWith(links: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $MetaCopyWith<$Res> get meta { + return $MetaCopyWith<$Res>(_value.meta, (value) { + return _then(_value.copyWith(meta: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$DietsPaginationImplCopyWith<$Res> + implements $DietsPaginationCopyWith<$Res> { + factory _$$DietsPaginationImplCopyWith(_$DietsPaginationImpl value, + $Res Function(_$DietsPaginationImpl) then) = + __$$DietsPaginationImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {@JsonKey(name: "data") List data, + @JsonKey(name: "links") Links links, + @JsonKey(name: "meta") Meta meta}); + + @override + $LinksCopyWith<$Res> get links; + @override + $MetaCopyWith<$Res> get meta; +} + +/// @nodoc +class __$$DietsPaginationImplCopyWithImpl<$Res> + extends _$DietsPaginationCopyWithImpl<$Res, _$DietsPaginationImpl> + implements _$$DietsPaginationImplCopyWith<$Res> { + __$$DietsPaginationImplCopyWithImpl( + _$DietsPaginationImpl _value, $Res Function(_$DietsPaginationImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? data = null, + Object? links = null, + Object? meta = null, + }) { + return _then(_$DietsPaginationImpl( + data: null == data + ? _value._data + : data // ignore: cast_nullable_to_non_nullable + as List, + links: null == links + ? _value.links + : links // ignore: cast_nullable_to_non_nullable + as Links, + meta: null == meta + ? _value.meta + : meta // ignore: cast_nullable_to_non_nullable + as Meta, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$DietsPaginationImpl implements _DietsPagination { + const _$DietsPaginationImpl( + {@JsonKey(name: "data") required final List data, + @JsonKey(name: "links") required this.links, + @JsonKey(name: "meta") required this.meta}) + : _data = data; + + factory _$DietsPaginationImpl.fromJson(Map json) => + _$$DietsPaginationImplFromJson(json); + + final List _data; + @override + @JsonKey(name: "data") + List get data { + if (_data is EqualUnmodifiableListView) return _data; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_data); + } + + @override + @JsonKey(name: "links") + final Links links; + @override + @JsonKey(name: "meta") + final Meta meta; + + @override + String toString() { + return 'DietsPagination(data: $data, links: $links, meta: $meta)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DietsPaginationImpl && + const DeepCollectionEquality().equals(other._data, _data) && + (identical(other.links, links) || other.links == links) && + (identical(other.meta, meta) || other.meta == meta)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_data), links, meta); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$DietsPaginationImplCopyWith<_$DietsPaginationImpl> get copyWith => + __$$DietsPaginationImplCopyWithImpl<_$DietsPaginationImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$DietsPaginationImplToJson( + this, + ); + } +} + +abstract class _DietsPagination implements DietsPagination { + const factory _DietsPagination( + {@JsonKey(name: "data") required final List data, + @JsonKey(name: "links") required final Links links, + @JsonKey(name: "meta") required final Meta meta}) = _$DietsPaginationImpl; + + factory _DietsPagination.fromJson(Map json) = + _$DietsPaginationImpl.fromJson; + + @override + @JsonKey(name: "data") + List get data; + @override + @JsonKey(name: "links") + Links get links; + @override + @JsonKey(name: "meta") + Meta get meta; + @override + @JsonKey(ignore: true) + _$$DietsPaginationImplCopyWith<_$DietsPaginationImpl> get copyWith => + throw _privateConstructorUsedError; +} + +Datum _$DatumFromJson(Map json) { + return _Datum.fromJson(json); +} + +/// @nodoc +mixin _$Datum { + @JsonKey(name: "id") + int get id => throw _privateConstructorUsedError; + @JsonKey(name: "name") + String get name => throw _privateConstructorUsedError; + @JsonKey(name: "image") + String get image => throw _privateConstructorUsedError; + @JsonKey(name: "duration") + int get duration => throw _privateConstructorUsedError; + @JsonKey(name: "state") + String get state => throw _privateConstructorUsedError; + @JsonKey(name: "type") + Type get type => throw _privateConstructorUsedError; + @JsonKey(name: "details") + String get details => throw _privateConstructorUsedError; + @JsonKey(name: "daily_schedule") + List>> get dailySchedule => + throw _privateConstructorUsedError; + @JsonKey(name: "author") + Author get author => throw _privateConstructorUsedError; + @JsonKey(name: "total_likes") + int get totalLikes => throw _privateConstructorUsedError; + @JsonKey(name: "total_views") + int get totalViews => throw _privateConstructorUsedError; + @JsonKey(name: "total_comments") + int get totalComments => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $DatumCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DatumCopyWith<$Res> { + factory $DatumCopyWith(Datum value, $Res Function(Datum) then) = + _$DatumCopyWithImpl<$Res, Datum>; + @useResult + $Res call( + {@JsonKey(name: "id") int id, + @JsonKey(name: "name") String name, + @JsonKey(name: "image") String image, + @JsonKey(name: "duration") int duration, + @JsonKey(name: "state") String state, + @JsonKey(name: "type") Type type, + @JsonKey(name: "details") String details, + @JsonKey(name: "daily_schedule") + List>> dailySchedule, + @JsonKey(name: "author") Author author, + @JsonKey(name: "total_likes") int totalLikes, + @JsonKey(name: "total_views") int totalViews, + @JsonKey(name: "total_comments") int totalComments}); + + $TypeCopyWith<$Res> get type; + $AuthorCopyWith<$Res> get author; +} + +/// @nodoc +class _$DatumCopyWithImpl<$Res, $Val extends Datum> + implements $DatumCopyWith<$Res> { + _$DatumCopyWithImpl(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 = null, + Object? name = null, + Object? image = null, + Object? duration = null, + Object? state = null, + Object? type = null, + Object? details = null, + Object? dailySchedule = null, + Object? author = null, + Object? totalLikes = null, + Object? totalViews = null, + Object? totalComments = null, + }) { + return _then(_value.copyWith( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + image: null == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as String, + duration: null == duration + ? _value.duration + : duration // ignore: cast_nullable_to_non_nullable + as int, + state: null == state + ? _value.state + : state // ignore: cast_nullable_to_non_nullable + as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as Type, + details: null == details + ? _value.details + : details // ignore: cast_nullable_to_non_nullable + as String, + dailySchedule: null == dailySchedule + ? _value.dailySchedule + : dailySchedule // ignore: cast_nullable_to_non_nullable + as List>>, + author: null == author + ? _value.author + : author // ignore: cast_nullable_to_non_nullable + as Author, + totalLikes: null == totalLikes + ? _value.totalLikes + : totalLikes // ignore: cast_nullable_to_non_nullable + as int, + totalViews: null == totalViews + ? _value.totalViews + : totalViews // ignore: cast_nullable_to_non_nullable + as int, + totalComments: null == totalComments + ? _value.totalComments + : totalComments // ignore: cast_nullable_to_non_nullable + as int, + ) as $Val); + } + + @override + @pragma('vm:prefer-inline') + $TypeCopyWith<$Res> get type { + return $TypeCopyWith<$Res>(_value.type, (value) { + return _then(_value.copyWith(type: value) as $Val); + }); + } + + @override + @pragma('vm:prefer-inline') + $AuthorCopyWith<$Res> get author { + return $AuthorCopyWith<$Res>(_value.author, (value) { + return _then(_value.copyWith(author: value) as $Val); + }); + } +} + +/// @nodoc +abstract class _$$DatumImplCopyWith<$Res> implements $DatumCopyWith<$Res> { + factory _$$DatumImplCopyWith( + _$DatumImpl value, $Res Function(_$DatumImpl) then) = + __$$DatumImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {@JsonKey(name: "id") int id, + @JsonKey(name: "name") String name, + @JsonKey(name: "image") String image, + @JsonKey(name: "duration") int duration, + @JsonKey(name: "state") String state, + @JsonKey(name: "type") Type type, + @JsonKey(name: "details") String details, + @JsonKey(name: "daily_schedule") + List>> dailySchedule, + @JsonKey(name: "author") Author author, + @JsonKey(name: "total_likes") int totalLikes, + @JsonKey(name: "total_views") int totalViews, + @JsonKey(name: "total_comments") int totalComments}); + + @override + $TypeCopyWith<$Res> get type; + @override + $AuthorCopyWith<$Res> get author; +} + +/// @nodoc +class __$$DatumImplCopyWithImpl<$Res> + extends _$DatumCopyWithImpl<$Res, _$DatumImpl> + implements _$$DatumImplCopyWith<$Res> { + __$$DatumImplCopyWithImpl( + _$DatumImpl _value, $Res Function(_$DatumImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? name = null, + Object? image = null, + Object? duration = null, + Object? state = null, + Object? type = null, + Object? details = null, + Object? dailySchedule = null, + Object? author = null, + Object? totalLikes = null, + Object? totalViews = null, + Object? totalComments = null, + }) { + return _then(_$DatumImpl( + id: null == id + ? _value.id + : id // ignore: cast_nullable_to_non_nullable + as int, + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + image: null == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as String, + duration: null == duration + ? _value.duration + : duration // ignore: cast_nullable_to_non_nullable + as int, + state: null == state + ? _value.state + : state // ignore: cast_nullable_to_non_nullable + as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as Type, + details: null == details + ? _value.details + : details // ignore: cast_nullable_to_non_nullable + as String, + dailySchedule: null == dailySchedule + ? _value._dailySchedule + : dailySchedule // ignore: cast_nullable_to_non_nullable + as List>>, + author: null == author + ? _value.author + : author // ignore: cast_nullable_to_non_nullable + as Author, + totalLikes: null == totalLikes + ? _value.totalLikes + : totalLikes // ignore: cast_nullable_to_non_nullable + as int, + totalViews: null == totalViews + ? _value.totalViews + : totalViews // ignore: cast_nullable_to_non_nullable + as int, + totalComments: null == totalComments + ? _value.totalComments + : totalComments // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$DatumImpl implements _Datum { + const _$DatumImpl( + {@JsonKey(name: "id") required this.id, + @JsonKey(name: "name") required this.name, + @JsonKey(name: "image") required this.image, + @JsonKey(name: "duration") required this.duration, + @JsonKey(name: "state") required this.state, + @JsonKey(name: "type") required this.type, + @JsonKey(name: "details") required this.details, + @JsonKey(name: "daily_schedule") + required final List>> dailySchedule, + @JsonKey(name: "author") required this.author, + @JsonKey(name: "total_likes") required this.totalLikes, + @JsonKey(name: "total_views") required this.totalViews, + @JsonKey(name: "total_comments") required this.totalComments}) + : _dailySchedule = dailySchedule; + + factory _$DatumImpl.fromJson(Map json) => + _$$DatumImplFromJson(json); + + @override + @JsonKey(name: "id") + final int id; + @override + @JsonKey(name: "name") + final String name; + @override + @JsonKey(name: "image") + final String image; + @override + @JsonKey(name: "duration") + final int duration; + @override + @JsonKey(name: "state") + final String state; + @override + @JsonKey(name: "type") + final Type type; + @override + @JsonKey(name: "details") + final String details; + final List>> _dailySchedule; + @override + @JsonKey(name: "daily_schedule") + List>> get dailySchedule { + if (_dailySchedule is EqualUnmodifiableListView) return _dailySchedule; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_dailySchedule); + } + + @override + @JsonKey(name: "author") + final Author author; + @override + @JsonKey(name: "total_likes") + final int totalLikes; + @override + @JsonKey(name: "total_views") + final int totalViews; + @override + @JsonKey(name: "total_comments") + final int totalComments; + + @override + String toString() { + return 'Datum(id: $id, name: $name, image: $image, duration: $duration, state: $state, type: $type, details: $details, dailySchedule: $dailySchedule, author: $author, totalLikes: $totalLikes, totalViews: $totalViews, totalComments: $totalComments)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DatumImpl && + (identical(other.id, id) || other.id == id) && + (identical(other.name, name) || other.name == name) && + (identical(other.image, image) || other.image == image) && + (identical(other.duration, duration) || + other.duration == duration) && + (identical(other.state, state) || other.state == state) && + (identical(other.type, type) || other.type == type) && + (identical(other.details, details) || other.details == details) && + const DeepCollectionEquality() + .equals(other._dailySchedule, _dailySchedule) && + (identical(other.author, author) || other.author == author) && + (identical(other.totalLikes, totalLikes) || + other.totalLikes == totalLikes) && + (identical(other.totalViews, totalViews) || + other.totalViews == totalViews) && + (identical(other.totalComments, totalComments) || + other.totalComments == totalComments)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, + id, + name, + image, + duration, + state, + type, + details, + const DeepCollectionEquality().hash(_dailySchedule), + author, + totalLikes, + totalViews, + totalComments); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$DatumImplCopyWith<_$DatumImpl> get copyWith => + __$$DatumImplCopyWithImpl<_$DatumImpl>(this, _$identity); + + @override + Map toJson() { + return _$$DatumImplToJson( + this, + ); + } +} + +abstract class _Datum implements Datum { + const factory _Datum( + {@JsonKey(name: "id") required final int id, + @JsonKey(name: "name") required final String name, + @JsonKey(name: "image") required final String image, + @JsonKey(name: "duration") required final int duration, + @JsonKey(name: "state") required final String state, + @JsonKey(name: "type") required final Type type, + @JsonKey(name: "details") required final String details, + @JsonKey(name: "daily_schedule") + required final List>> dailySchedule, + @JsonKey(name: "author") required final Author author, + @JsonKey(name: "total_likes") required final int totalLikes, + @JsonKey(name: "total_views") required final int totalViews, + @JsonKey(name: "total_comments") required final int totalComments}) = + _$DatumImpl; + + factory _Datum.fromJson(Map json) = _$DatumImpl.fromJson; + + @override + @JsonKey(name: "id") + int get id; + @override + @JsonKey(name: "name") + String get name; + @override + @JsonKey(name: "image") + String get image; + @override + @JsonKey(name: "duration") + int get duration; + @override + @JsonKey(name: "state") + String get state; + @override + @JsonKey(name: "type") + Type get type; + @override + @JsonKey(name: "details") + String get details; + @override + @JsonKey(name: "daily_schedule") + List>> get dailySchedule; + @override + @JsonKey(name: "author") + Author get author; + @override + @JsonKey(name: "total_likes") + int get totalLikes; + @override + @JsonKey(name: "total_views") + int get totalViews; + @override + @JsonKey(name: "total_comments") + int get totalComments; + @override + @JsonKey(ignore: true) + _$$DatumImplCopyWith<_$DatumImpl> get copyWith => + throw _privateConstructorUsedError; +} + +Author _$AuthorFromJson(Map json) { + return _Author.fromJson(json); +} + +/// @nodoc +mixin _$Author { + @JsonKey(name: "author_slug") + String get authorSlug => throw _privateConstructorUsedError; + @JsonKey(name: "author_name") + String get authorName => throw _privateConstructorUsedError; + @JsonKey(name: "author_profile_icon") + String get authorProfileIcon => throw _privateConstructorUsedError; + @JsonKey(name: "author_is_me") + bool get authorIsMe => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $AuthorCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $AuthorCopyWith<$Res> { + factory $AuthorCopyWith(Author value, $Res Function(Author) then) = + _$AuthorCopyWithImpl<$Res, Author>; + @useResult + $Res call( + {@JsonKey(name: "author_slug") String authorSlug, + @JsonKey(name: "author_name") String authorName, + @JsonKey(name: "author_profile_icon") String authorProfileIcon, + @JsonKey(name: "author_is_me") bool authorIsMe}); +} + +/// @nodoc +class _$AuthorCopyWithImpl<$Res, $Val extends Author> + implements $AuthorCopyWith<$Res> { + _$AuthorCopyWithImpl(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? authorSlug = null, + Object? authorName = null, + Object? authorProfileIcon = null, + Object? authorIsMe = null, + }) { + return _then(_value.copyWith( + authorSlug: null == authorSlug + ? _value.authorSlug + : authorSlug // ignore: cast_nullable_to_non_nullable + as String, + authorName: null == authorName + ? _value.authorName + : authorName // ignore: cast_nullable_to_non_nullable + as String, + authorProfileIcon: null == authorProfileIcon + ? _value.authorProfileIcon + : authorProfileIcon // ignore: cast_nullable_to_non_nullable + as String, + authorIsMe: null == authorIsMe + ? _value.authorIsMe + : authorIsMe // ignore: cast_nullable_to_non_nullable + as bool, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$AuthorImplCopyWith<$Res> implements $AuthorCopyWith<$Res> { + factory _$$AuthorImplCopyWith( + _$AuthorImpl value, $Res Function(_$AuthorImpl) then) = + __$$AuthorImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {@JsonKey(name: "author_slug") String authorSlug, + @JsonKey(name: "author_name") String authorName, + @JsonKey(name: "author_profile_icon") String authorProfileIcon, + @JsonKey(name: "author_is_me") bool authorIsMe}); +} + +/// @nodoc +class __$$AuthorImplCopyWithImpl<$Res> + extends _$AuthorCopyWithImpl<$Res, _$AuthorImpl> + implements _$$AuthorImplCopyWith<$Res> { + __$$AuthorImplCopyWithImpl( + _$AuthorImpl _value, $Res Function(_$AuthorImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? authorSlug = null, + Object? authorName = null, + Object? authorProfileIcon = null, + Object? authorIsMe = null, + }) { + return _then(_$AuthorImpl( + authorSlug: null == authorSlug + ? _value.authorSlug + : authorSlug // ignore: cast_nullable_to_non_nullable + as String, + authorName: null == authorName + ? _value.authorName + : authorName // ignore: cast_nullable_to_non_nullable + as String, + authorProfileIcon: null == authorProfileIcon + ? _value.authorProfileIcon + : authorProfileIcon // ignore: cast_nullable_to_non_nullable + as String, + authorIsMe: null == authorIsMe + ? _value.authorIsMe + : authorIsMe // ignore: cast_nullable_to_non_nullable + as bool, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$AuthorImpl implements _Author { + const _$AuthorImpl( + {@JsonKey(name: "author_slug") required this.authorSlug, + @JsonKey(name: "author_name") required this.authorName, + @JsonKey(name: "author_profile_icon") required this.authorProfileIcon, + @JsonKey(name: "author_is_me") required this.authorIsMe}); + + factory _$AuthorImpl.fromJson(Map json) => + _$$AuthorImplFromJson(json); + + @override + @JsonKey(name: "author_slug") + final String authorSlug; + @override + @JsonKey(name: "author_name") + final String authorName; + @override + @JsonKey(name: "author_profile_icon") + final String authorProfileIcon; + @override + @JsonKey(name: "author_is_me") + final bool authorIsMe; + + @override + String toString() { + return 'Author(authorSlug: $authorSlug, authorName: $authorName, authorProfileIcon: $authorProfileIcon, authorIsMe: $authorIsMe)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$AuthorImpl && + (identical(other.authorSlug, authorSlug) || + other.authorSlug == authorSlug) && + (identical(other.authorName, authorName) || + other.authorName == authorName) && + (identical(other.authorProfileIcon, authorProfileIcon) || + other.authorProfileIcon == authorProfileIcon) && + (identical(other.authorIsMe, authorIsMe) || + other.authorIsMe == authorIsMe)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, authorSlug, authorName, authorProfileIcon, authorIsMe); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$AuthorImplCopyWith<_$AuthorImpl> get copyWith => + __$$AuthorImplCopyWithImpl<_$AuthorImpl>(this, _$identity); + + @override + Map toJson() { + return _$$AuthorImplToJson( + this, + ); + } +} + +abstract class _Author implements Author { + const factory _Author( + {@JsonKey(name: "author_slug") required final String authorSlug, + @JsonKey(name: "author_name") required final String authorName, + @JsonKey(name: "author_profile_icon") + required final String authorProfileIcon, + @JsonKey(name: "author_is_me") required final bool authorIsMe}) = + _$AuthorImpl; + + factory _Author.fromJson(Map json) = _$AuthorImpl.fromJson; + + @override + @JsonKey(name: "author_slug") + String get authorSlug; + @override + @JsonKey(name: "author_name") + String get authorName; + @override + @JsonKey(name: "author_profile_icon") + String get authorProfileIcon; + @override + @JsonKey(name: "author_is_me") + bool get authorIsMe; + @override + @JsonKey(ignore: true) + _$$AuthorImplCopyWith<_$AuthorImpl> get copyWith => + throw _privateConstructorUsedError; +} + +DailySchedule _$DailyScheduleFromJson(Map json) { + return _DailySchedule.fromJson(json); +} + +/// @nodoc +mixin _$DailySchedule { + @JsonKey(name: "name") + String get name => throw _privateConstructorUsedError; + @JsonKey(name: "uniq") + String get uniq => throw _privateConstructorUsedError; + @JsonKey(name: "portion") + Portion get portion => throw _privateConstructorUsedError; + @JsonKey(name: "quantity") + int get quantity => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $DailyScheduleCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DailyScheduleCopyWith<$Res> { + factory $DailyScheduleCopyWith( + DailySchedule value, $Res Function(DailySchedule) then) = + _$DailyScheduleCopyWithImpl<$Res, DailySchedule>; + @useResult + $Res call( + {@JsonKey(name: "name") String name, + @JsonKey(name: "uniq") String uniq, + @JsonKey(name: "portion") Portion portion, + @JsonKey(name: "quantity") int quantity}); +} + +/// @nodoc +class _$DailyScheduleCopyWithImpl<$Res, $Val extends DailySchedule> + implements $DailyScheduleCopyWith<$Res> { + _$DailyScheduleCopyWithImpl(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? uniq = null, + Object? portion = null, + Object? quantity = null, + }) { + return _then(_value.copyWith( + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + uniq: null == uniq + ? _value.uniq + : uniq // ignore: cast_nullable_to_non_nullable + as String, + portion: null == portion + ? _value.portion + : portion // ignore: cast_nullable_to_non_nullable + as Portion, + quantity: null == quantity + ? _value.quantity + : quantity // ignore: cast_nullable_to_non_nullable + as int, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$DailyScheduleImplCopyWith<$Res> + implements $DailyScheduleCopyWith<$Res> { + factory _$$DailyScheduleImplCopyWith( + _$DailyScheduleImpl value, $Res Function(_$DailyScheduleImpl) then) = + __$$DailyScheduleImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {@JsonKey(name: "name") String name, + @JsonKey(name: "uniq") String uniq, + @JsonKey(name: "portion") Portion portion, + @JsonKey(name: "quantity") int quantity}); +} + +/// @nodoc +class __$$DailyScheduleImplCopyWithImpl<$Res> + extends _$DailyScheduleCopyWithImpl<$Res, _$DailyScheduleImpl> + implements _$$DailyScheduleImplCopyWith<$Res> { + __$$DailyScheduleImplCopyWithImpl( + _$DailyScheduleImpl _value, $Res Function(_$DailyScheduleImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? name = null, + Object? uniq = null, + Object? portion = null, + Object? quantity = null, + }) { + return _then(_$DailyScheduleImpl( + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + uniq: null == uniq + ? _value.uniq + : uniq // ignore: cast_nullable_to_non_nullable + as String, + portion: null == portion + ? _value.portion + : portion // ignore: cast_nullable_to_non_nullable + as Portion, + quantity: null == quantity + ? _value.quantity + : quantity // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$DailyScheduleImpl implements _DailySchedule { + const _$DailyScheduleImpl( + {@JsonKey(name: "name") required this.name, + @JsonKey(name: "uniq") required this.uniq, + @JsonKey(name: "portion") required this.portion, + @JsonKey(name: "quantity") required this.quantity}); + + factory _$DailyScheduleImpl.fromJson(Map json) => + _$$DailyScheduleImplFromJson(json); + + @override + @JsonKey(name: "name") + final String name; + @override + @JsonKey(name: "uniq") + final String uniq; + @override + @JsonKey(name: "portion") + final Portion portion; + @override + @JsonKey(name: "quantity") + final int quantity; + + @override + String toString() { + return 'DailySchedule(name: $name, uniq: $uniq, portion: $portion, quantity: $quantity)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DailyScheduleImpl && + (identical(other.name, name) || other.name == name) && + (identical(other.uniq, uniq) || other.uniq == uniq) && + (identical(other.portion, portion) || other.portion == portion) && + (identical(other.quantity, quantity) || + other.quantity == quantity)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, name, uniq, portion, quantity); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$DailyScheduleImplCopyWith<_$DailyScheduleImpl> get copyWith => + __$$DailyScheduleImplCopyWithImpl<_$DailyScheduleImpl>(this, _$identity); + + @override + Map toJson() { + return _$$DailyScheduleImplToJson( + this, + ); + } +} + +abstract class _DailySchedule implements DailySchedule { + const factory _DailySchedule( + {@JsonKey(name: "name") required final String name, + @JsonKey(name: "uniq") required final String uniq, + @JsonKey(name: "portion") required final Portion portion, + @JsonKey(name: "quantity") required final int quantity}) = + _$DailyScheduleImpl; + + factory _DailySchedule.fromJson(Map json) = + _$DailyScheduleImpl.fromJson; + + @override + @JsonKey(name: "name") + String get name; + @override + @JsonKey(name: "uniq") + String get uniq; + @override + @JsonKey(name: "portion") + Portion get portion; + @override + @JsonKey(name: "quantity") + int get quantity; + @override + @JsonKey(ignore: true) + _$$DailyScheduleImplCopyWith<_$DailyScheduleImpl> get copyWith => + throw _privateConstructorUsedError; +} + +Type _$TypeFromJson(Map json) { + return _Type.fromJson(json); +} + +/// @nodoc +mixin _$Type { + @JsonKey(name: "alko") + bool? get alko => throw _privateConstructorUsedError; + @JsonKey(name: "veg") + bool? get veg => throw _privateConstructorUsedError; + @JsonKey(name: "corb") + bool? get corb => throw _privateConstructorUsedError; + @JsonKey(name: "meat") + bool? get meat => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $TypeCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $TypeCopyWith<$Res> { + factory $TypeCopyWith(Type value, $Res Function(Type) then) = + _$TypeCopyWithImpl<$Res, Type>; + @useResult + $Res call( + {@JsonKey(name: "alko") bool? alko, + @JsonKey(name: "veg") bool? veg, + @JsonKey(name: "corb") bool? corb, + @JsonKey(name: "meat") bool? meat}); +} + +/// @nodoc +class _$TypeCopyWithImpl<$Res, $Val extends Type> + implements $TypeCopyWith<$Res> { + _$TypeCopyWithImpl(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? alko = freezed, + Object? veg = freezed, + Object? corb = freezed, + Object? meat = freezed, + }) { + return _then(_value.copyWith( + alko: freezed == alko + ? _value.alko + : alko // ignore: cast_nullable_to_non_nullable + as bool?, + veg: freezed == veg + ? _value.veg + : veg // ignore: cast_nullable_to_non_nullable + as bool?, + corb: freezed == corb + ? _value.corb + : corb // ignore: cast_nullable_to_non_nullable + as bool?, + meat: freezed == meat + ? _value.meat + : meat // ignore: cast_nullable_to_non_nullable + as bool?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$TypeImplCopyWith<$Res> implements $TypeCopyWith<$Res> { + factory _$$TypeImplCopyWith( + _$TypeImpl value, $Res Function(_$TypeImpl) then) = + __$$TypeImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {@JsonKey(name: "alko") bool? alko, + @JsonKey(name: "veg") bool? veg, + @JsonKey(name: "corb") bool? corb, + @JsonKey(name: "meat") bool? meat}); +} + +/// @nodoc +class __$$TypeImplCopyWithImpl<$Res> + extends _$TypeCopyWithImpl<$Res, _$TypeImpl> + implements _$$TypeImplCopyWith<$Res> { + __$$TypeImplCopyWithImpl(_$TypeImpl _value, $Res Function(_$TypeImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? alko = freezed, + Object? veg = freezed, + Object? corb = freezed, + Object? meat = freezed, + }) { + return _then(_$TypeImpl( + alko: freezed == alko + ? _value.alko + : alko // ignore: cast_nullable_to_non_nullable + as bool?, + veg: freezed == veg + ? _value.veg + : veg // ignore: cast_nullable_to_non_nullable + as bool?, + corb: freezed == corb + ? _value.corb + : corb // ignore: cast_nullable_to_non_nullable + as bool?, + meat: freezed == meat + ? _value.meat + : meat // ignore: cast_nullable_to_non_nullable + as bool?, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$TypeImpl implements _Type { + const _$TypeImpl( + {@JsonKey(name: "alko") this.alko, + @JsonKey(name: "veg") this.veg, + @JsonKey(name: "corb") this.corb, + @JsonKey(name: "meat") this.meat}); + + factory _$TypeImpl.fromJson(Map json) => + _$$TypeImplFromJson(json); + + @override + @JsonKey(name: "alko") + final bool? alko; + @override + @JsonKey(name: "veg") + final bool? veg; + @override + @JsonKey(name: "corb") + final bool? corb; + @override + @JsonKey(name: "meat") + final bool? meat; + + @override + String toString() { + return 'Type(alko: $alko, veg: $veg, corb: $corb, meat: $meat)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$TypeImpl && + (identical(other.alko, alko) || other.alko == alko) && + (identical(other.veg, veg) || other.veg == veg) && + (identical(other.corb, corb) || other.corb == corb) && + (identical(other.meat, meat) || other.meat == meat)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, alko, veg, corb, meat); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$TypeImplCopyWith<_$TypeImpl> get copyWith => + __$$TypeImplCopyWithImpl<_$TypeImpl>(this, _$identity); + + @override + Map toJson() { + return _$$TypeImplToJson( + this, + ); + } +} + +abstract class _Type implements Type { + const factory _Type( + {@JsonKey(name: "alko") final bool? alko, + @JsonKey(name: "veg") final bool? veg, + @JsonKey(name: "corb") final bool? corb, + @JsonKey(name: "meat") final bool? meat}) = _$TypeImpl; + + factory _Type.fromJson(Map json) = _$TypeImpl.fromJson; + + @override + @JsonKey(name: "alko") + bool? get alko; + @override + @JsonKey(name: "veg") + bool? get veg; + @override + @JsonKey(name: "corb") + bool? get corb; + @override + @JsonKey(name: "meat") + bool? get meat; + @override + @JsonKey(ignore: true) + _$$TypeImplCopyWith<_$TypeImpl> get copyWith => + throw _privateConstructorUsedError; +} + +Links _$LinksFromJson(Map json) { + return _Links.fromJson(json); +} + +/// @nodoc +mixin _$Links { + @JsonKey(name: "first") + String get first => throw _privateConstructorUsedError; + @JsonKey(name: "last") + String get last => throw _privateConstructorUsedError; + @JsonKey(name: "prev") + dynamic get prev => throw _privateConstructorUsedError; + @JsonKey(name: "next") + dynamic get next => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $LinksCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $LinksCopyWith<$Res> { + factory $LinksCopyWith(Links value, $Res Function(Links) then) = + _$LinksCopyWithImpl<$Res, Links>; + @useResult + $Res call( + {@JsonKey(name: "first") String first, + @JsonKey(name: "last") String last, + @JsonKey(name: "prev") dynamic prev, + @JsonKey(name: "next") dynamic next}); +} + +/// @nodoc +class _$LinksCopyWithImpl<$Res, $Val extends Links> + implements $LinksCopyWith<$Res> { + _$LinksCopyWithImpl(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? first = null, + Object? last = null, + Object? prev = freezed, + Object? next = freezed, + }) { + return _then(_value.copyWith( + first: null == first + ? _value.first + : first // ignore: cast_nullable_to_non_nullable + as String, + last: null == last + ? _value.last + : last // ignore: cast_nullable_to_non_nullable + as String, + prev: freezed == prev + ? _value.prev + : prev // ignore: cast_nullable_to_non_nullable + as dynamic, + next: freezed == next + ? _value.next + : next // ignore: cast_nullable_to_non_nullable + as dynamic, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$LinksImplCopyWith<$Res> implements $LinksCopyWith<$Res> { + factory _$$LinksImplCopyWith( + _$LinksImpl value, $Res Function(_$LinksImpl) then) = + __$$LinksImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {@JsonKey(name: "first") String first, + @JsonKey(name: "last") String last, + @JsonKey(name: "prev") dynamic prev, + @JsonKey(name: "next") dynamic next}); +} + +/// @nodoc +class __$$LinksImplCopyWithImpl<$Res> + extends _$LinksCopyWithImpl<$Res, _$LinksImpl> + implements _$$LinksImplCopyWith<$Res> { + __$$LinksImplCopyWithImpl( + _$LinksImpl _value, $Res Function(_$LinksImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? first = null, + Object? last = null, + Object? prev = freezed, + Object? next = freezed, + }) { + return _then(_$LinksImpl( + first: null == first + ? _value.first + : first // ignore: cast_nullable_to_non_nullable + as String, + last: null == last + ? _value.last + : last // ignore: cast_nullable_to_non_nullable + as String, + prev: freezed == prev + ? _value.prev + : prev // ignore: cast_nullable_to_non_nullable + as dynamic, + next: freezed == next + ? _value.next + : next // ignore: cast_nullable_to_non_nullable + as dynamic, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$LinksImpl implements _Links { + const _$LinksImpl( + {@JsonKey(name: "first") required this.first, + @JsonKey(name: "last") required this.last, + @JsonKey(name: "prev") required this.prev, + @JsonKey(name: "next") required this.next}); + + factory _$LinksImpl.fromJson(Map json) => + _$$LinksImplFromJson(json); + + @override + @JsonKey(name: "first") + final String first; + @override + @JsonKey(name: "last") + final String last; + @override + @JsonKey(name: "prev") + final dynamic prev; + @override + @JsonKey(name: "next") + final dynamic next; + + @override + String toString() { + return 'Links(first: $first, last: $last, prev: $prev, next: $next)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LinksImpl && + (identical(other.first, first) || other.first == first) && + (identical(other.last, last) || other.last == last) && + const DeepCollectionEquality().equals(other.prev, prev) && + const DeepCollectionEquality().equals(other.next, next)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, + first, + last, + const DeepCollectionEquality().hash(prev), + const DeepCollectionEquality().hash(next)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$LinksImplCopyWith<_$LinksImpl> get copyWith => + __$$LinksImplCopyWithImpl<_$LinksImpl>(this, _$identity); + + @override + Map toJson() { + return _$$LinksImplToJson( + this, + ); + } +} + +abstract class _Links implements Links { + const factory _Links( + {@JsonKey(name: "first") required final String first, + @JsonKey(name: "last") required final String last, + @JsonKey(name: "prev") required final dynamic prev, + @JsonKey(name: "next") required final dynamic next}) = _$LinksImpl; + + factory _Links.fromJson(Map json) = _$LinksImpl.fromJson; + + @override + @JsonKey(name: "first") + String get first; + @override + @JsonKey(name: "last") + String get last; + @override + @JsonKey(name: "prev") + dynamic get prev; + @override + @JsonKey(name: "next") + dynamic get next; + @override + @JsonKey(ignore: true) + _$$LinksImplCopyWith<_$LinksImpl> get copyWith => + throw _privateConstructorUsedError; +} + +Meta _$MetaFromJson(Map json) { + return _Meta.fromJson(json); +} + +/// @nodoc +mixin _$Meta { + @JsonKey(name: "current_page") + int get currentPage => throw _privateConstructorUsedError; + @JsonKey(name: "from") + int get from => throw _privateConstructorUsedError; + @JsonKey(name: "last_page") + int get lastPage => throw _privateConstructorUsedError; + @JsonKey(name: "links") + List get links => throw _privateConstructorUsedError; + @JsonKey(name: "path") + String get path => throw _privateConstructorUsedError; + @JsonKey(name: "per_page") + int get perPage => throw _privateConstructorUsedError; + @JsonKey(name: "to") + int get to => throw _privateConstructorUsedError; + @JsonKey(name: "total") + int get total => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $MetaCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $MetaCopyWith<$Res> { + factory $MetaCopyWith(Meta value, $Res Function(Meta) then) = + _$MetaCopyWithImpl<$Res, Meta>; + @useResult + $Res call( + {@JsonKey(name: "current_page") int currentPage, + @JsonKey(name: "from") int from, + @JsonKey(name: "last_page") int lastPage, + @JsonKey(name: "links") List links, + @JsonKey(name: "path") String path, + @JsonKey(name: "per_page") int perPage, + @JsonKey(name: "to") int to, + @JsonKey(name: "total") int total}); +} + +/// @nodoc +class _$MetaCopyWithImpl<$Res, $Val extends Meta> + implements $MetaCopyWith<$Res> { + _$MetaCopyWithImpl(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? currentPage = null, + Object? from = null, + Object? lastPage = null, + Object? links = null, + Object? path = null, + Object? perPage = null, + Object? to = null, + Object? total = null, + }) { + return _then(_value.copyWith( + currentPage: null == currentPage + ? _value.currentPage + : currentPage // ignore: cast_nullable_to_non_nullable + as int, + from: null == from + ? _value.from + : from // ignore: cast_nullable_to_non_nullable + as int, + lastPage: null == lastPage + ? _value.lastPage + : lastPage // ignore: cast_nullable_to_non_nullable + as int, + links: null == links + ? _value.links + : links // ignore: cast_nullable_to_non_nullable + as List, + path: null == path + ? _value.path + : path // ignore: cast_nullable_to_non_nullable + as String, + perPage: null == perPage + ? _value.perPage + : perPage // ignore: cast_nullable_to_non_nullable + as int, + to: null == to + ? _value.to + : to // ignore: cast_nullable_to_non_nullable + as int, + total: null == total + ? _value.total + : total // ignore: cast_nullable_to_non_nullable + as int, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$MetaImplCopyWith<$Res> implements $MetaCopyWith<$Res> { + factory _$$MetaImplCopyWith( + _$MetaImpl value, $Res Function(_$MetaImpl) then) = + __$$MetaImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {@JsonKey(name: "current_page") int currentPage, + @JsonKey(name: "from") int from, + @JsonKey(name: "last_page") int lastPage, + @JsonKey(name: "links") List links, + @JsonKey(name: "path") String path, + @JsonKey(name: "per_page") int perPage, + @JsonKey(name: "to") int to, + @JsonKey(name: "total") int total}); +} + +/// @nodoc +class __$$MetaImplCopyWithImpl<$Res> + extends _$MetaCopyWithImpl<$Res, _$MetaImpl> + implements _$$MetaImplCopyWith<$Res> { + __$$MetaImplCopyWithImpl(_$MetaImpl _value, $Res Function(_$MetaImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? currentPage = null, + Object? from = null, + Object? lastPage = null, + Object? links = null, + Object? path = null, + Object? perPage = null, + Object? to = null, + Object? total = null, + }) { + return _then(_$MetaImpl( + currentPage: null == currentPage + ? _value.currentPage + : currentPage // ignore: cast_nullable_to_non_nullable + as int, + from: null == from + ? _value.from + : from // ignore: cast_nullable_to_non_nullable + as int, + lastPage: null == lastPage + ? _value.lastPage + : lastPage // ignore: cast_nullable_to_non_nullable + as int, + links: null == links + ? _value._links + : links // ignore: cast_nullable_to_non_nullable + as List, + path: null == path + ? _value.path + : path // ignore: cast_nullable_to_non_nullable + as String, + perPage: null == perPage + ? _value.perPage + : perPage // ignore: cast_nullable_to_non_nullable + as int, + to: null == to + ? _value.to + : to // ignore: cast_nullable_to_non_nullable + as int, + total: null == total + ? _value.total + : total // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$MetaImpl implements _Meta { + const _$MetaImpl( + {@JsonKey(name: "current_page") required this.currentPage, + @JsonKey(name: "from") required this.from, + @JsonKey(name: "last_page") required this.lastPage, + @JsonKey(name: "links") required final List links, + @JsonKey(name: "path") required this.path, + @JsonKey(name: "per_page") required this.perPage, + @JsonKey(name: "to") required this.to, + @JsonKey(name: "total") required this.total}) + : _links = links; + + factory _$MetaImpl.fromJson(Map json) => + _$$MetaImplFromJson(json); + + @override + @JsonKey(name: "current_page") + final int currentPage; + @override + @JsonKey(name: "from") + final int from; + @override + @JsonKey(name: "last_page") + final int lastPage; + final List _links; + @override + @JsonKey(name: "links") + List get links { + if (_links is EqualUnmodifiableListView) return _links; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_links); + } + + @override + @JsonKey(name: "path") + final String path; + @override + @JsonKey(name: "per_page") + final int perPage; + @override + @JsonKey(name: "to") + final int to; + @override + @JsonKey(name: "total") + final int total; + + @override + String toString() { + return 'Meta(currentPage: $currentPage, from: $from, lastPage: $lastPage, links: $links, path: $path, perPage: $perPage, to: $to, total: $total)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$MetaImpl && + (identical(other.currentPage, currentPage) || + other.currentPage == currentPage) && + (identical(other.from, from) || other.from == from) && + (identical(other.lastPage, lastPage) || + other.lastPage == lastPage) && + const DeepCollectionEquality().equals(other._links, _links) && + (identical(other.path, path) || other.path == path) && + (identical(other.perPage, perPage) || other.perPage == perPage) && + (identical(other.to, to) || other.to == to) && + (identical(other.total, total) || other.total == total)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, currentPage, from, lastPage, + const DeepCollectionEquality().hash(_links), path, perPage, to, total); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$MetaImplCopyWith<_$MetaImpl> get copyWith => + __$$MetaImplCopyWithImpl<_$MetaImpl>(this, _$identity); + + @override + Map toJson() { + return _$$MetaImplToJson( + this, + ); + } +} + +abstract class _Meta implements Meta { + const factory _Meta( + {@JsonKey(name: "current_page") required final int currentPage, + @JsonKey(name: "from") required final int from, + @JsonKey(name: "last_page") required final int lastPage, + @JsonKey(name: "links") required final List links, + @JsonKey(name: "path") required final String path, + @JsonKey(name: "per_page") required final int perPage, + @JsonKey(name: "to") required final int to, + @JsonKey(name: "total") required final int total}) = _$MetaImpl; + + factory _Meta.fromJson(Map json) = _$MetaImpl.fromJson; + + @override + @JsonKey(name: "current_page") + int get currentPage; + @override + @JsonKey(name: "from") + int get from; + @override + @JsonKey(name: "last_page") + int get lastPage; + @override + @JsonKey(name: "links") + List get links; + @override + @JsonKey(name: "path") + String get path; + @override + @JsonKey(name: "per_page") + int get perPage; + @override + @JsonKey(name: "to") + int get to; + @override + @JsonKey(name: "total") + int get total; + @override + @JsonKey(ignore: true) + _$$MetaImplCopyWith<_$MetaImpl> get copyWith => + throw _privateConstructorUsedError; +} + +Link _$LinkFromJson(Map json) { + return _Link.fromJson(json); +} + +/// @nodoc +mixin _$Link { + @JsonKey(name: "url") + String? get url => throw _privateConstructorUsedError; + @JsonKey(name: "label") + String get label => throw _privateConstructorUsedError; + @JsonKey(name: "active") + bool get active => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $LinkCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $LinkCopyWith<$Res> { + factory $LinkCopyWith(Link value, $Res Function(Link) then) = + _$LinkCopyWithImpl<$Res, Link>; + @useResult + $Res call( + {@JsonKey(name: "url") String? url, + @JsonKey(name: "label") String label, + @JsonKey(name: "active") bool active}); +} + +/// @nodoc +class _$LinkCopyWithImpl<$Res, $Val extends Link> + implements $LinkCopyWith<$Res> { + _$LinkCopyWithImpl(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? url = freezed, + Object? label = null, + Object? active = null, + }) { + return _then(_value.copyWith( + url: freezed == url + ? _value.url + : url // ignore: cast_nullable_to_non_nullable + as String?, + label: null == label + ? _value.label + : label // ignore: cast_nullable_to_non_nullable + as String, + active: null == active + ? _value.active + : active // ignore: cast_nullable_to_non_nullable + as bool, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$LinkImplCopyWith<$Res> implements $LinkCopyWith<$Res> { + factory _$$LinkImplCopyWith( + _$LinkImpl value, $Res Function(_$LinkImpl) then) = + __$$LinkImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {@JsonKey(name: "url") String? url, + @JsonKey(name: "label") String label, + @JsonKey(name: "active") bool active}); +} + +/// @nodoc +class __$$LinkImplCopyWithImpl<$Res> + extends _$LinkCopyWithImpl<$Res, _$LinkImpl> + implements _$$LinkImplCopyWith<$Res> { + __$$LinkImplCopyWithImpl(_$LinkImpl _value, $Res Function(_$LinkImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? url = freezed, + Object? label = null, + Object? active = null, + }) { + return _then(_$LinkImpl( + url: freezed == url + ? _value.url + : url // ignore: cast_nullable_to_non_nullable + as String?, + label: null == label + ? _value.label + : label // ignore: cast_nullable_to_non_nullable + as String, + active: null == active + ? _value.active + : active // ignore: cast_nullable_to_non_nullable + as bool, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$LinkImpl implements _Link { + const _$LinkImpl( + {@JsonKey(name: "url") required this.url, + @JsonKey(name: "label") required this.label, + @JsonKey(name: "active") required this.active}); + + factory _$LinkImpl.fromJson(Map json) => + _$$LinkImplFromJson(json); + + @override + @JsonKey(name: "url") + final String? url; + @override + @JsonKey(name: "label") + final String label; + @override + @JsonKey(name: "active") + final bool active; + + @override + String toString() { + return 'Link(url: $url, label: $label, active: $active)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LinkImpl && + (identical(other.url, url) || other.url == url) && + (identical(other.label, label) || other.label == label) && + (identical(other.active, active) || other.active == active)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, url, label, active); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$LinkImplCopyWith<_$LinkImpl> get copyWith => + __$$LinkImplCopyWithImpl<_$LinkImpl>(this, _$identity); + + @override + Map toJson() { + return _$$LinkImplToJson( + this, + ); + } +} + +abstract class _Link implements Link { + const factory _Link( + {@JsonKey(name: "url") required final String? url, + @JsonKey(name: "label") required final String label, + @JsonKey(name: "active") required final bool active}) = _$LinkImpl; + + factory _Link.fromJson(Map json) = _$LinkImpl.fromJson; + + @override + @JsonKey(name: "url") + String? get url; + @override + @JsonKey(name: "label") + String get label; + @override + @JsonKey(name: "active") + bool get active; + @override + @JsonKey(ignore: true) + _$$LinkImplCopyWith<_$LinkImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/feed/models/diets_pagination_model.g.dart b/lib/features/feed/models/diets_pagination_model.g.dart new file mode 100644 index 0000000..0a74509 --- /dev/null +++ b/lib/features/feed/models/diets_pagination_model.g.dart @@ -0,0 +1,167 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'diets_pagination_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$DietsPaginationImpl _$$DietsPaginationImplFromJson( + Map json) => + _$DietsPaginationImpl( + data: (json['data'] as List) + .map((e) => Datum.fromJson(e as Map)) + .toList(), + links: Links.fromJson(json['links'] as Map), + meta: Meta.fromJson(json['meta'] as Map), + ); + +Map _$$DietsPaginationImplToJson( + _$DietsPaginationImpl instance) => + { + 'data': instance.data, + 'links': instance.links, + 'meta': instance.meta, + }; + +_$DatumImpl _$$DatumImplFromJson(Map json) => _$DatumImpl( + id: (json['id'] as num).toInt(), + name: json['name'] as String, + image: json['image'] as String, + duration: (json['duration'] as num).toInt(), + state: json['state'] as String, + type: Type.fromJson(json['type'] as Map), + details: json['details'] as String, + dailySchedule: (json['daily_schedule'] as List) + .map((e) => (e as List) + .map((e) => (e as List) + .map((e) => DailySchedule.fromJson(e as Map)) + .toList()) + .toList()) + .toList(), + author: Author.fromJson(json['author'] as Map), + totalLikes: (json['total_likes'] as num).toInt(), + totalViews: (json['total_views'] as num).toInt(), + totalComments: (json['total_comments'] as num).toInt(), + ); + +Map _$$DatumImplToJson(_$DatumImpl instance) => + { + 'id': instance.id, + 'name': instance.name, + 'image': instance.image, + 'duration': instance.duration, + 'state': instance.state, + 'type': instance.type, + 'details': instance.details, + 'daily_schedule': instance.dailySchedule, + 'author': instance.author, + 'total_likes': instance.totalLikes, + 'total_views': instance.totalViews, + 'total_comments': instance.totalComments, + }; + +_$AuthorImpl _$$AuthorImplFromJson(Map json) => _$AuthorImpl( + authorSlug: json['author_slug'] as String, + authorName: json['author_name'] as String, + authorProfileIcon: json['author_profile_icon'] as String, + authorIsMe: json['author_is_me'] as bool, + ); + +Map _$$AuthorImplToJson(_$AuthorImpl instance) => + { + 'author_slug': instance.authorSlug, + 'author_name': instance.authorName, + 'author_profile_icon': instance.authorProfileIcon, + 'author_is_me': instance.authorIsMe, + }; + +_$DailyScheduleImpl _$$DailyScheduleImplFromJson(Map json) => + _$DailyScheduleImpl( + name: json['name'] as String, + uniq: json['uniq'] as String, + portion: $enumDecode(_$PortionEnumMap, json['portion']), + quantity: (json['quantity'] as num).toInt(), + ); + +Map _$$DailyScheduleImplToJson(_$DailyScheduleImpl instance) => + { + 'name': instance.name, + 'uniq': instance.uniq, + 'portion': _$PortionEnumMap[instance.portion]!, + 'quantity': instance.quantity, + }; + +const _$PortionEnumMap = { + Portion.GRAMS: 'grams', + Portion.MILLILITERS: 'milliliters', + Portion.PCS: 'pcs', +}; + +_$TypeImpl _$$TypeImplFromJson(Map json) => _$TypeImpl( + alko: json['alko'] as bool?, + veg: json['veg'] as bool?, + corb: json['corb'] as bool?, + meat: json['meat'] as bool?, + ); + +Map _$$TypeImplToJson(_$TypeImpl instance) => + { + 'alko': instance.alko, + 'veg': instance.veg, + 'corb': instance.corb, + 'meat': instance.meat, + }; + +_$LinksImpl _$$LinksImplFromJson(Map json) => _$LinksImpl( + first: json['first'] as String, + last: json['last'] as String, + prev: json['prev'], + next: json['next'], + ); + +Map _$$LinksImplToJson(_$LinksImpl instance) => + { + 'first': instance.first, + 'last': instance.last, + 'prev': instance.prev, + 'next': instance.next, + }; + +_$MetaImpl _$$MetaImplFromJson(Map json) => _$MetaImpl( + currentPage: (json['current_page'] as num).toInt(), + from: (json['from'] as num).toInt(), + lastPage: (json['last_page'] as num).toInt(), + links: (json['links'] as List) + .map((e) => Link.fromJson(e as Map)) + .toList(), + path: json['path'] as String, + perPage: (json['per_page'] as num).toInt(), + to: (json['to'] as num).toInt(), + total: (json['total'] as num).toInt(), + ); + +Map _$$MetaImplToJson(_$MetaImpl instance) => + { + 'current_page': instance.currentPage, + 'from': instance.from, + 'last_page': instance.lastPage, + 'links': instance.links, + 'path': instance.path, + 'per_page': instance.perPage, + 'to': instance.to, + 'total': instance.total, + }; + +_$LinkImpl _$$LinkImplFromJson(Map json) => _$LinkImpl( + url: json['url'] as String?, + label: json['label'] as String, + active: json['active'] as bool, + ); + +Map _$$LinkImplToJson(_$LinkImpl instance) => + { + 'url': instance.url, + 'label': instance.label, + 'active': instance.active, + }; diff --git a/lib/features/feed/models/feed_blog_post_model.freezed.dart b/lib/features/feed/models/feed_blog_post_model.freezed.dart index 425591a..4d753a1 100644 --- a/lib/features/feed/models/feed_blog_post_model.freezed.dart +++ b/lib/features/feed/models/feed_blog_post_model.freezed.dart @@ -21,34 +21,28 @@ FeedBlogPostModel _$FeedBlogPostModelFromJson(Map json) { /// @nodoc mixin _$FeedBlogPostModel { int get id => throw _privateConstructorUsedError; - String get state => throw _privateConstructorUsedError; - String get image => throw _privateConstructorUsedError; - String get description => throw _privateConstructorUsedError; - @JsonKey(name: "youtube_url") String get youtubeUrl => throw _privateConstructorUsedError; - @JsonKey(name: "created_at") DateTime get createdAt => throw _privateConstructorUsedError; - @JsonKey(name: "updated_at") DateTime get updatedAt => throw _privateConstructorUsedError; - String get title => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $FeedBlogPostModelCopyWith get copyWith => throw _privateConstructorUsedError; + $FeedBlogPostModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $FeedBlogPostModelCopyWith<$Res> { - factory $FeedBlogPostModelCopyWith(FeedBlogPostModel value, $Res Function(FeedBlogPostModel) then) = _$FeedBlogPostModelCopyWithImpl<$Res, FeedBlogPostModel>; - + factory $FeedBlogPostModelCopyWith( + FeedBlogPostModel value, $Res Function(FeedBlogPostModel) then) = + _$FeedBlogPostModelCopyWithImpl<$Res, FeedBlogPostModel>; @useResult $Res call( {int id, @@ -62,12 +56,12 @@ abstract class $FeedBlogPostModelCopyWith<$Res> { } /// @nodoc -class _$FeedBlogPostModelCopyWithImpl<$Res, $Val extends FeedBlogPostModel> implements $FeedBlogPostModelCopyWith<$Res> { +class _$FeedBlogPostModelCopyWithImpl<$Res, $Val extends FeedBlogPostModel> + implements $FeedBlogPostModelCopyWith<$Res> { _$FeedBlogPostModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -121,10 +115,11 @@ class _$FeedBlogPostModelCopyWithImpl<$Res, $Val extends FeedBlogPostModel> impl } /// @nodoc -abstract class _$$FeedBlogPostModelImplCopyWith<$Res> implements $FeedBlogPostModelCopyWith<$Res> { - factory _$$FeedBlogPostModelImplCopyWith(_$FeedBlogPostModelImpl value, $Res Function(_$FeedBlogPostModelImpl) then) = +abstract class _$$FeedBlogPostModelImplCopyWith<$Res> + implements $FeedBlogPostModelCopyWith<$Res> { + factory _$$FeedBlogPostModelImplCopyWith(_$FeedBlogPostModelImpl value, + $Res Function(_$FeedBlogPostModelImpl) then) = __$$FeedBlogPostModelImplCopyWithImpl<$Res>; - @override @useResult $Res call( @@ -139,9 +134,12 @@ abstract class _$$FeedBlogPostModelImplCopyWith<$Res> implements $FeedBlogPostMo } /// @nodoc -class __$$FeedBlogPostModelImplCopyWithImpl<$Res> extends _$FeedBlogPostModelCopyWithImpl<$Res, _$FeedBlogPostModelImpl> +class __$$FeedBlogPostModelImplCopyWithImpl<$Res> + extends _$FeedBlogPostModelCopyWithImpl<$Res, _$FeedBlogPostModelImpl> implements _$$FeedBlogPostModelImplCopyWith<$Res> { - __$$FeedBlogPostModelImplCopyWithImpl(_$FeedBlogPostModelImpl _value, $Res Function(_$FeedBlogPostModelImpl) _then) : super(_value, _then); + __$$FeedBlogPostModelImplCopyWithImpl(_$FeedBlogPostModelImpl _value, + $Res Function(_$FeedBlogPostModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -205,7 +203,8 @@ class _$FeedBlogPostModelImpl implements _FeedBlogPostModel { @JsonKey(name: "updated_at") required this.updatedAt, required this.title}); - factory _$FeedBlogPostModelImpl.fromJson(Map json) => _$$FeedBlogPostModelImplFromJson(json); + factory _$FeedBlogPostModelImpl.fromJson(Map json) => + _$$FeedBlogPostModelImplFromJson(json); @override final int id; @@ -240,21 +239,28 @@ class _$FeedBlogPostModelImpl implements _FeedBlogPostModel { (identical(other.id, id) || other.id == id) && (identical(other.state, state) || other.state == state) && (identical(other.image, image) || other.image == image) && - (identical(other.description, description) || other.description == description) && - (identical(other.youtubeUrl, youtubeUrl) || other.youtubeUrl == youtubeUrl) && - (identical(other.createdAt, createdAt) || other.createdAt == createdAt) && - (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt) && + (identical(other.description, description) || + other.description == description) && + (identical(other.youtubeUrl, youtubeUrl) || + other.youtubeUrl == youtubeUrl) && + (identical(other.createdAt, createdAt) || + other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt) && (identical(other.title, title) || other.title == title)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, state, image, description, youtubeUrl, createdAt, updatedAt, title); + int get hashCode => Object.hash(runtimeType, id, state, image, description, + youtubeUrl, createdAt, updatedAt, title); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => __$$FeedBlogPostModelImplCopyWithImpl<_$FeedBlogPostModelImpl>(this, _$identity); + _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => + __$$FeedBlogPostModelImplCopyWithImpl<_$FeedBlogPostModelImpl>( + this, _$identity); @override Map toJson() { @@ -275,36 +281,30 @@ abstract class _FeedBlogPostModel implements FeedBlogPostModel { @JsonKey(name: "updated_at") required final DateTime updatedAt, required final String title}) = _$FeedBlogPostModelImpl; - factory _FeedBlogPostModel.fromJson(Map json) = _$FeedBlogPostModelImpl.fromJson; + factory _FeedBlogPostModel.fromJson(Map json) = + _$FeedBlogPostModelImpl.fromJson; @override int get id; - @override String get state; - @override String get image; - @override String get description; - @override @JsonKey(name: "youtube_url") String get youtubeUrl; - @override @JsonKey(name: "created_at") DateTime get createdAt; - @override @JsonKey(name: "updated_at") DateTime get updatedAt; - @override String get title; - @override @JsonKey(ignore: true) - _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$FeedBlogPostModelImplCopyWith<_$FeedBlogPostModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/feed/models/feed_blog_post_model.g.dart b/lib/features/feed/models/feed_blog_post_model.g.dart index e680864..93cc70f 100644 --- a/lib/features/feed/models/feed_blog_post_model.g.dart +++ b/lib/features/feed/models/feed_blog_post_model.g.dart @@ -6,7 +6,9 @@ part of 'feed_blog_post_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$FeedBlogPostModelImpl _$$FeedBlogPostModelImplFromJson(Map json) => _$FeedBlogPostModelImpl( +_$FeedBlogPostModelImpl _$$FeedBlogPostModelImplFromJson( + Map json) => + _$FeedBlogPostModelImpl( id: (json['id'] as num).toInt(), state: json['state'] as String, image: json['image'] as String, @@ -17,7 +19,9 @@ _$FeedBlogPostModelImpl _$$FeedBlogPostModelImplFromJson(Map js title: json['title'] as String, ); -Map _$$FeedBlogPostModelImplToJson(_$FeedBlogPostModelImpl instance) => { +Map _$$FeedBlogPostModelImplToJson( + _$FeedBlogPostModelImpl instance) => + { 'id': instance.id, 'state': instance.state, 'image': instance.image, 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 index 7947d80..7fd8a12 100644 --- a/lib/features/feed/models/feed_blog_post_settings_model.freezed.dart +++ b/lib/features/feed/models/feed_blog_post_settings_model.freezed.dart @@ -14,37 +14,40 @@ 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) { +FeedBlogPostSettingsModel _$FeedBlogPostSettingsModelFromJson( + Map json) { return _FeedBlogPostSettingsModel.fromJson(json); } /// @nodoc mixin _$FeedBlogPostSettingsModel { @JsonKey(name: 'data') - List get feedBlogPostList => throw _privateConstructorUsedError; + List get feedBlogPostList => + throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $FeedBlogPostSettingsModelCopyWith get copyWith => throw _privateConstructorUsedError; + $FeedBlogPostSettingsModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $FeedBlogPostSettingsModelCopyWith<$Res> { - factory $FeedBlogPostSettingsModelCopyWith(FeedBlogPostSettingsModel value, $Res Function(FeedBlogPostSettingsModel) then) = + 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> { +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; @@ -63,19 +66,25 @@ class _$FeedBlogPostSettingsModelCopyWithImpl<$Res, $Val extends FeedBlogPostSet } /// @nodoc -abstract class _$$FeedBlogPostSettingsModelImplCopyWith<$Res> implements $FeedBlogPostSettingsModelCopyWith<$Res> { - factory _$$FeedBlogPostSettingsModelImplCopyWith(_$FeedBlogPostSettingsModelImpl value, $Res Function(_$FeedBlogPostSettingsModelImpl) then) = +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> +class __$$FeedBlogPostSettingsModelImplCopyWithImpl<$Res> + extends _$FeedBlogPostSettingsModelCopyWithImpl<$Res, + _$FeedBlogPostSettingsModelImpl> implements _$$FeedBlogPostSettingsModelImplCopyWith<$Res> { - __$$FeedBlogPostSettingsModelImplCopyWithImpl(_$FeedBlogPostSettingsModelImpl _value, $Res Function(_$FeedBlogPostSettingsModelImpl) _then) + __$$FeedBlogPostSettingsModelImplCopyWithImpl( + _$FeedBlogPostSettingsModelImpl _value, + $Res Function(_$FeedBlogPostSettingsModelImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @@ -95,17 +104,20 @@ class __$$FeedBlogPostSettingsModelImplCopyWithImpl<$Res> extends _$FeedBlogPost /// @nodoc @JsonSerializable() class _$FeedBlogPostSettingsModelImpl implements _FeedBlogPostSettingsModel { - const _$FeedBlogPostSettingsModelImpl({@JsonKey(name: 'data') required final List feedBlogPostList}) + const _$FeedBlogPostSettingsModelImpl( + {@JsonKey(name: 'data') + required final List feedBlogPostList}) : _feedBlogPostList = feedBlogPostList; - factory _$FeedBlogPostSettingsModelImpl.fromJson(Map json) => _$$FeedBlogPostSettingsModelImplFromJson(json); + factory _$FeedBlogPostSettingsModelImpl.fromJson(Map json) => + _$$FeedBlogPostSettingsModelImplFromJson(json); final List _feedBlogPostList; - @override @JsonKey(name: 'data') List get feedBlogPostList { - if (_feedBlogPostList is EqualUnmodifiableListView) return _feedBlogPostList; + if (_feedBlogPostList is EqualUnmodifiableListView) + return _feedBlogPostList; // ignore: implicit_dynamic_type return EqualUnmodifiableListView(_feedBlogPostList); } @@ -120,18 +132,21 @@ class _$FeedBlogPostSettingsModelImpl implements _FeedBlogPostSettingsModel { return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedBlogPostSettingsModelImpl && - const DeepCollectionEquality().equals(other._feedBlogPostList, _feedBlogPostList)); + const DeepCollectionEquality() + .equals(other._feedBlogPostList, _feedBlogPostList)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_feedBlogPostList)); + 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); + _$$FeedBlogPostSettingsModelImplCopyWith<_$FeedBlogPostSettingsModelImpl> + get copyWith => __$$FeedBlogPostSettingsModelImplCopyWithImpl< + _$FeedBlogPostSettingsModelImpl>(this, _$identity); @override Map toJson() { @@ -142,15 +157,19 @@ class _$FeedBlogPostSettingsModelImpl implements _FeedBlogPostSettingsModel { } abstract class _FeedBlogPostSettingsModel implements FeedBlogPostSettingsModel { - const factory _FeedBlogPostSettingsModel({@JsonKey(name: 'data') required final List feedBlogPostList}) = _$FeedBlogPostSettingsModelImpl; + const factory _FeedBlogPostSettingsModel( + {@JsonKey(name: 'data') + required final List feedBlogPostList}) = + _$FeedBlogPostSettingsModelImpl; - factory _FeedBlogPostSettingsModel.fromJson(Map json) = _$FeedBlogPostSettingsModelImpl.fromJson; + factory _FeedBlogPostSettingsModel.fromJson(Map json) = + _$FeedBlogPostSettingsModelImpl.fromJson; @override @JsonKey(name: 'data') List get feedBlogPostList; - @override @JsonKey(ignore: true) - _$$FeedBlogPostSettingsModelImplCopyWith<_$FeedBlogPostSettingsModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$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 index 90c6b0e..3f48be1 100644 --- a/lib/features/feed/models/feed_blog_post_settings_model.g.dart +++ b/lib/features/feed/models/feed_blog_post_settings_model.g.dart @@ -6,14 +6,16 @@ part of 'feed_blog_post_settings_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$FeedBlogPostSettingsModelImpl _$$FeedBlogPostSettingsModelImplFromJson(Map json) => +_$FeedBlogPostSettingsModelImpl _$$FeedBlogPostSettingsModelImplFromJson( + Map json) => _$FeedBlogPostSettingsModelImpl( feedBlogPostList: (json['data'] as List) .map((e) => FeedBlogPostModel.fromJson(e as Map)) .toList(), ); -Map _$$FeedBlogPostSettingsModelImplToJson(_$FeedBlogPostSettingsModelImpl instance) => +Map _$$FeedBlogPostSettingsModelImplToJson( + _$FeedBlogPostSettingsModelImpl instance) => { 'data': instance.feedBlogPostList, }; diff --git a/lib/features/feed/models/recipes_model.dart b/lib/features/feed/models/recipes_model.dart index d654faf..1bc93d3 100644 --- a/lib/features/feed/models/recipes_model.dart +++ b/lib/features/feed/models/recipes_model.dart @@ -9,17 +9,19 @@ class Recipes with _$Recipes { required int id, required String image, required String state, - @JsonKey(name: "cooking_time") required int cookingTime, + @JsonKey(name: 'cooking_time') required int cookingTime, required List ingredients, required String description, required List steps, - @JsonKey(name: "video_url") required String videoUrl, - @JsonKey(name: "created_at") required DateTime createdAt, - @JsonKey(name: "updated_at") required DateTime updatedAt, + @JsonKey(name: 'video_url') required String videoUrl, + @JsonKey(name: 'created_at') required DateTime createdAt, + @JsonKey(name: 'updated_at') required DateTime updatedAt, required String title, required String type, required String slug, - @JsonKey(name: "comments_count") required int commentsCount, + @JsonKey(name: 'total_comments') required int commentsCount, + @JsonKey(name: 'total_likes') required int likesCount, + @JsonKey(name: 'total_views') required int viewsCount, }) = _Recipes; factory Recipes.fromJson(Map json) => _$RecipesFromJson(json); diff --git a/lib/features/feed/models/recipes_model.freezed.dart b/lib/features/feed/models/recipes_model.freezed.dart index 9557c03..9843651 100644 --- a/lib/features/feed/models/recipes_model.freezed.dart +++ b/lib/features/feed/models/recipes_model.freezed.dart @@ -21,73 +21,65 @@ Recipes _$RecipesFromJson(Map json) { /// @nodoc mixin _$Recipes { int get id => throw _privateConstructorUsedError; - String get image => throw _privateConstructorUsedError; - String get state => throw _privateConstructorUsedError; - - @JsonKey(name: "cooking_time") + @JsonKey(name: 'cooking_time') int get cookingTime => throw _privateConstructorUsedError; - List get ingredients => throw _privateConstructorUsedError; - String get description => throw _privateConstructorUsedError; - List get steps => throw _privateConstructorUsedError; - - @JsonKey(name: "video_url") + @JsonKey(name: 'video_url') String get videoUrl => throw _privateConstructorUsedError; - - @JsonKey(name: "created_at") + @JsonKey(name: 'created_at') DateTime get createdAt => throw _privateConstructorUsedError; - - @JsonKey(name: "updated_at") + @JsonKey(name: 'updated_at') DateTime get updatedAt => throw _privateConstructorUsedError; - String get title => throw _privateConstructorUsedError; - String get type => throw _privateConstructorUsedError; - String get slug => throw _privateConstructorUsedError; - - @JsonKey(name: "comments_count") + @JsonKey(name: 'total_comments') int get commentsCount => throw _privateConstructorUsedError; + @JsonKey(name: 'total_likes') + int get likesCount => throw _privateConstructorUsedError; + @JsonKey(name: 'total_views') + int get viewsCount => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) $RecipesCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $RecipesCopyWith<$Res> { - factory $RecipesCopyWith(Recipes value, $Res Function(Recipes) then) = _$RecipesCopyWithImpl<$Res, Recipes>; - + factory $RecipesCopyWith(Recipes value, $Res Function(Recipes) then) = + _$RecipesCopyWithImpl<$Res, Recipes>; @useResult $Res call( {int id, String image, String state, - @JsonKey(name: "cooking_time") int cookingTime, + @JsonKey(name: 'cooking_time') int cookingTime, List ingredients, String description, List steps, - @JsonKey(name: "video_url") String videoUrl, - @JsonKey(name: "created_at") DateTime createdAt, - @JsonKey(name: "updated_at") DateTime updatedAt, + @JsonKey(name: 'video_url') String videoUrl, + @JsonKey(name: 'created_at') DateTime createdAt, + @JsonKey(name: 'updated_at') DateTime updatedAt, String title, String type, String slug, - @JsonKey(name: "comments_count") int commentsCount}); + @JsonKey(name: 'total_comments') int commentsCount, + @JsonKey(name: 'total_likes') int likesCount, + @JsonKey(name: 'total_views') int viewsCount}); } /// @nodoc -class _$RecipesCopyWithImpl<$Res, $Val extends Recipes> implements $RecipesCopyWith<$Res> { +class _$RecipesCopyWithImpl<$Res, $Val extends Recipes> + implements $RecipesCopyWith<$Res> { _$RecipesCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -108,6 +100,8 @@ class _$RecipesCopyWithImpl<$Res, $Val extends Recipes> implements $RecipesCopyW Object? type = null, Object? slug = null, Object? commentsCount = null, + Object? likesCount = null, + Object? viewsCount = null, }) { return _then(_value.copyWith( id: null == id @@ -166,36 +160,51 @@ class _$RecipesCopyWithImpl<$Res, $Val extends Recipes> implements $RecipesCopyW ? _value.commentsCount : commentsCount // ignore: cast_nullable_to_non_nullable as int, + likesCount: null == likesCount + ? _value.likesCount + : likesCount // ignore: cast_nullable_to_non_nullable + as int, + viewsCount: null == viewsCount + ? _value.viewsCount + : viewsCount // ignore: cast_nullable_to_non_nullable + as int, ) as $Val); } } /// @nodoc abstract class _$$RecipesImplCopyWith<$Res> implements $RecipesCopyWith<$Res> { - factory _$$RecipesImplCopyWith(_$RecipesImpl value, $Res Function(_$RecipesImpl) then) = __$$RecipesImplCopyWithImpl<$Res>; - + factory _$$RecipesImplCopyWith( + _$RecipesImpl value, $Res Function(_$RecipesImpl) then) = + __$$RecipesImplCopyWithImpl<$Res>; @override @useResult $Res call( {int id, String image, String state, - @JsonKey(name: "cooking_time") int cookingTime, + @JsonKey(name: 'cooking_time') int cookingTime, List ingredients, String description, List steps, - @JsonKey(name: "video_url") String videoUrl, - @JsonKey(name: "created_at") DateTime createdAt, - @JsonKey(name: "updated_at") DateTime updatedAt, + @JsonKey(name: 'video_url') String videoUrl, + @JsonKey(name: 'created_at') DateTime createdAt, + @JsonKey(name: 'updated_at') DateTime updatedAt, String title, String type, String slug, - @JsonKey(name: "comments_count") int commentsCount}); + @JsonKey(name: 'total_comments') int commentsCount, + @JsonKey(name: 'total_likes') int likesCount, + @JsonKey(name: 'total_views') int viewsCount}); } /// @nodoc -class __$$RecipesImplCopyWithImpl<$Res> extends _$RecipesCopyWithImpl<$Res, _$RecipesImpl> implements _$$RecipesImplCopyWith<$Res> { - __$$RecipesImplCopyWithImpl(_$RecipesImpl _value, $Res Function(_$RecipesImpl) _then) : super(_value, _then); +class __$$RecipesImplCopyWithImpl<$Res> + extends _$RecipesCopyWithImpl<$Res, _$RecipesImpl> + implements _$$RecipesImplCopyWith<$Res> { + __$$RecipesImplCopyWithImpl( + _$RecipesImpl _value, $Res Function(_$RecipesImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -214,6 +223,8 @@ class __$$RecipesImplCopyWithImpl<$Res> extends _$RecipesCopyWithImpl<$Res, _$Re Object? type = null, Object? slug = null, Object? commentsCount = null, + Object? likesCount = null, + Object? viewsCount = null, }) { return _then(_$RecipesImpl( id: null == id @@ -272,6 +283,14 @@ class __$$RecipesImplCopyWithImpl<$Res> extends _$RecipesCopyWithImpl<$Res, _$Re ? _value.commentsCount : commentsCount // ignore: cast_nullable_to_non_nullable as int, + likesCount: null == likesCount + ? _value.likesCount + : likesCount // ignore: cast_nullable_to_non_nullable + as int, + viewsCount: null == viewsCount + ? _value.viewsCount + : viewsCount // ignore: cast_nullable_to_non_nullable + as int, )); } } @@ -283,21 +302,24 @@ class _$RecipesImpl implements _Recipes { {required this.id, required this.image, required this.state, - @JsonKey(name: "cooking_time") required this.cookingTime, + @JsonKey(name: 'cooking_time') required this.cookingTime, required final List ingredients, required this.description, required final List steps, - @JsonKey(name: "video_url") required this.videoUrl, - @JsonKey(name: "created_at") required this.createdAt, - @JsonKey(name: "updated_at") required this.updatedAt, + @JsonKey(name: 'video_url') required this.videoUrl, + @JsonKey(name: 'created_at') required this.createdAt, + @JsonKey(name: 'updated_at') required this.updatedAt, required this.title, required this.type, required this.slug, - @JsonKey(name: "comments_count") required this.commentsCount}) + @JsonKey(name: 'total_comments') required this.commentsCount, + @JsonKey(name: 'total_likes') required this.likesCount, + @JsonKey(name: 'total_views') required this.viewsCount}) : _ingredients = ingredients, _steps = steps; - factory _$RecipesImpl.fromJson(Map json) => _$$RecipesImplFromJson(json); + factory _$RecipesImpl.fromJson(Map json) => + _$$RecipesImplFromJson(json); @override final int id; @@ -306,10 +328,9 @@ class _$RecipesImpl implements _Recipes { @override final String state; @override - @JsonKey(name: "cooking_time") + @JsonKey(name: 'cooking_time') final int cookingTime; final List _ingredients; - @override List get ingredients { if (_ingredients is EqualUnmodifiableListView) return _ingredients; @@ -320,7 +341,6 @@ class _$RecipesImpl implements _Recipes { @override final String description; final List _steps; - @override List get steps { if (_steps is EqualUnmodifiableListView) return _steps; @@ -329,13 +349,13 @@ class _$RecipesImpl implements _Recipes { } @override - @JsonKey(name: "video_url") + @JsonKey(name: 'video_url') final String videoUrl; @override - @JsonKey(name: "created_at") + @JsonKey(name: 'created_at') final DateTime createdAt; @override - @JsonKey(name: "updated_at") + @JsonKey(name: 'updated_at') final DateTime updatedAt; @override final String title; @@ -344,12 +364,18 @@ class _$RecipesImpl implements _Recipes { @override final String slug; @override - @JsonKey(name: "comments_count") + @JsonKey(name: 'total_comments') final int commentsCount; + @override + @JsonKey(name: 'total_likes') + final int likesCount; + @override + @JsonKey(name: 'total_views') + final int viewsCount; @override String toString() { - return 'Recipes(id: $id, image: $image, state: $state, cookingTime: $cookingTime, ingredients: $ingredients, description: $description, steps: $steps, videoUrl: $videoUrl, createdAt: $createdAt, updatedAt: $updatedAt, title: $title, type: $type, slug: $slug, commentsCount: $commentsCount)'; + return 'Recipes(id: $id, image: $image, state: $state, cookingTime: $cookingTime, ingredients: $ingredients, description: $description, steps: $steps, videoUrl: $videoUrl, createdAt: $createdAt, updatedAt: $updatedAt, title: $title, type: $type, slug: $slug, commentsCount: $commentsCount, likesCount: $likesCount, viewsCount: $viewsCount)'; } @override @@ -360,28 +386,56 @@ class _$RecipesImpl implements _Recipes { (identical(other.id, id) || other.id == id) && (identical(other.image, image) || other.image == image) && (identical(other.state, state) || other.state == state) && - (identical(other.cookingTime, cookingTime) || other.cookingTime == cookingTime) && - const DeepCollectionEquality().equals(other._ingredients, _ingredients) && - (identical(other.description, description) || other.description == description) && + (identical(other.cookingTime, cookingTime) || + other.cookingTime == cookingTime) && + const DeepCollectionEquality() + .equals(other._ingredients, _ingredients) && + (identical(other.description, description) || + other.description == description) && const DeepCollectionEquality().equals(other._steps, _steps) && - (identical(other.videoUrl, videoUrl) || other.videoUrl == videoUrl) && - (identical(other.createdAt, createdAt) || other.createdAt == createdAt) && - (identical(other.updatedAt, updatedAt) || other.updatedAt == updatedAt) && + (identical(other.videoUrl, videoUrl) || + other.videoUrl == videoUrl) && + (identical(other.createdAt, createdAt) || + other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt) && (identical(other.title, title) || other.title == title) && (identical(other.type, type) || other.type == type) && (identical(other.slug, slug) || other.slug == slug) && - (identical(other.commentsCount, commentsCount) || other.commentsCount == commentsCount)); + (identical(other.commentsCount, commentsCount) || + other.commentsCount == commentsCount) && + (identical(other.likesCount, likesCount) || + other.likesCount == likesCount) && + (identical(other.viewsCount, viewsCount) || + other.viewsCount == viewsCount)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, id, image, state, cookingTime, const DeepCollectionEquality().hash(_ingredients), description, - const DeepCollectionEquality().hash(_steps), videoUrl, createdAt, updatedAt, title, type, slug, commentsCount); + int get hashCode => Object.hash( + runtimeType, + id, + image, + state, + cookingTime, + const DeepCollectionEquality().hash(_ingredients), + description, + const DeepCollectionEquality().hash(_steps), + videoUrl, + createdAt, + updatedAt, + title, + type, + slug, + commentsCount, + likesCount, + viewsCount); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$RecipesImplCopyWith<_$RecipesImpl> get copyWith => __$$RecipesImplCopyWithImpl<_$RecipesImpl>(this, _$identity); + _$$RecipesImplCopyWith<_$RecipesImpl> get copyWith => + __$$RecipesImplCopyWithImpl<_$RecipesImpl>(this, _$identity); @override Map toJson() { @@ -393,73 +447,69 @@ class _$RecipesImpl implements _Recipes { abstract class _Recipes implements Recipes { const factory _Recipes( - {required final int id, - required final String image, - required final String state, - @JsonKey(name: "cooking_time") required final int cookingTime, - required final List ingredients, - required final String description, - required final List steps, - @JsonKey(name: "video_url") required final String videoUrl, - @JsonKey(name: "created_at") required final DateTime createdAt, - @JsonKey(name: "updated_at") required final DateTime updatedAt, - required final String title, - required final String type, - required final String slug, - @JsonKey(name: "comments_count") required final int commentsCount}) = _$RecipesImpl; + {required final int id, + required final String image, + required final String state, + @JsonKey(name: 'cooking_time') required final int cookingTime, + required final List ingredients, + required final String description, + required final List steps, + @JsonKey(name: 'video_url') required final String videoUrl, + @JsonKey(name: 'created_at') required final DateTime createdAt, + @JsonKey(name: 'updated_at') required final DateTime updatedAt, + required final String title, + required final String type, + required final String slug, + @JsonKey(name: 'total_comments') required final int commentsCount, + @JsonKey(name: 'total_likes') required final int likesCount, + @JsonKey(name: 'total_views') required final int viewsCount}) = + _$RecipesImpl; factory _Recipes.fromJson(Map json) = _$RecipesImpl.fromJson; @override int get id; - @override String get image; - @override String get state; - @override - @JsonKey(name: "cooking_time") + @JsonKey(name: 'cooking_time') int get cookingTime; - @override List get ingredients; - @override String get description; - @override List get steps; - @override - @JsonKey(name: "video_url") + @JsonKey(name: 'video_url') String get videoUrl; - @override - @JsonKey(name: "created_at") + @JsonKey(name: 'created_at') DateTime get createdAt; - @override - @JsonKey(name: "updated_at") + @JsonKey(name: 'updated_at') DateTime get updatedAt; - @override String get title; - @override String get type; - @override String get slug; - @override - @JsonKey(name: "comments_count") + @JsonKey(name: 'total_comments') int get commentsCount; - + @override + @JsonKey(name: 'total_likes') + int get likesCount; + @override + @JsonKey(name: 'total_views') + int get viewsCount; @override @JsonKey(ignore: true) - _$$RecipesImplCopyWith<_$RecipesImpl> get copyWith => throw _privateConstructorUsedError; + _$$RecipesImplCopyWith<_$RecipesImpl> get copyWith => + throw _privateConstructorUsedError; } Ingredient _$IngredientFromJson(Map json) { @@ -469,32 +519,31 @@ Ingredient _$IngredientFromJson(Map json) { /// @nodoc mixin _$Ingredient { String get name => throw _privateConstructorUsedError; - String? get unit => throw _privateConstructorUsedError; - String get portion => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $IngredientCopyWith get copyWith => throw _privateConstructorUsedError; + $IngredientCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $IngredientCopyWith<$Res> { - factory $IngredientCopyWith(Ingredient value, $Res Function(Ingredient) then) = _$IngredientCopyWithImpl<$Res, Ingredient>; - + factory $IngredientCopyWith( + Ingredient value, $Res Function(Ingredient) then) = + _$IngredientCopyWithImpl<$Res, Ingredient>; @useResult $Res call({String name, String? unit, String portion}); } /// @nodoc -class _$IngredientCopyWithImpl<$Res, $Val extends Ingredient> implements $IngredientCopyWith<$Res> { +class _$IngredientCopyWithImpl<$Res, $Val extends Ingredient> + implements $IngredientCopyWith<$Res> { _$IngredientCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -523,17 +572,23 @@ class _$IngredientCopyWithImpl<$Res, $Val extends Ingredient> implements $Ingred } /// @nodoc -abstract class _$$IngredientImplCopyWith<$Res> implements $IngredientCopyWith<$Res> { - factory _$$IngredientImplCopyWith(_$IngredientImpl value, $Res Function(_$IngredientImpl) then) = __$$IngredientImplCopyWithImpl<$Res>; - +abstract class _$$IngredientImplCopyWith<$Res> + implements $IngredientCopyWith<$Res> { + factory _$$IngredientImplCopyWith( + _$IngredientImpl value, $Res Function(_$IngredientImpl) then) = + __$$IngredientImplCopyWithImpl<$Res>; @override @useResult $Res call({String name, String? unit, String portion}); } /// @nodoc -class __$$IngredientImplCopyWithImpl<$Res> extends _$IngredientCopyWithImpl<$Res, _$IngredientImpl> implements _$$IngredientImplCopyWith<$Res> { - __$$IngredientImplCopyWithImpl(_$IngredientImpl _value, $Res Function(_$IngredientImpl) _then) : super(_value, _then); +class __$$IngredientImplCopyWithImpl<$Res> + extends _$IngredientCopyWithImpl<$Res, _$IngredientImpl> + implements _$$IngredientImplCopyWith<$Res> { + __$$IngredientImplCopyWithImpl( + _$IngredientImpl _value, $Res Function(_$IngredientImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -562,9 +617,11 @@ class __$$IngredientImplCopyWithImpl<$Res> extends _$IngredientCopyWithImpl<$Res /// @nodoc @JsonSerializable() class _$IngredientImpl implements _Ingredient { - const _$IngredientImpl({required this.name, this.unit, required this.portion}); + const _$IngredientImpl( + {required this.name, this.unit, required this.portion}); - factory _$IngredientImpl.fromJson(Map json) => _$$IngredientImplFromJson(json); + factory _$IngredientImpl.fromJson(Map json) => + _$$IngredientImplFromJson(json); @override final String name; @@ -595,7 +652,8 @@ class _$IngredientImpl implements _Ingredient { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$IngredientImplCopyWith<_$IngredientImpl> get copyWith => __$$IngredientImplCopyWithImpl<_$IngredientImpl>(this, _$identity); + _$$IngredientImplCopyWith<_$IngredientImpl> get copyWith => + __$$IngredientImplCopyWithImpl<_$IngredientImpl>(this, _$identity); @override Map toJson() { @@ -606,22 +664,24 @@ class _$IngredientImpl implements _Ingredient { } abstract class _Ingredient implements Ingredient { - const factory _Ingredient({required final String name, final String? unit, required final String portion}) = _$IngredientImpl; + const factory _Ingredient( + {required final String name, + final String? unit, + required final String portion}) = _$IngredientImpl; - factory _Ingredient.fromJson(Map json) = _$IngredientImpl.fromJson; + factory _Ingredient.fromJson(Map json) = + _$IngredientImpl.fromJson; @override String get name; - @override String? get unit; - @override String get portion; - @override @JsonKey(ignore: true) - _$$IngredientImplCopyWith<_$IngredientImpl> get copyWith => throw _privateConstructorUsedError; + _$$IngredientImplCopyWith<_$IngredientImpl> get copyWith => + throw _privateConstructorUsedError; } Step _$StepFromJson(Map json) { @@ -631,30 +691,28 @@ Step _$StepFromJson(Map json) { /// @nodoc mixin _$Step { String get image => throw _privateConstructorUsedError; - String get description => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) $StepCopyWith get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $StepCopyWith<$Res> { - factory $StepCopyWith(Step value, $Res Function(Step) then) = _$StepCopyWithImpl<$Res, Step>; - + factory $StepCopyWith(Step value, $Res Function(Step) then) = + _$StepCopyWithImpl<$Res, Step>; @useResult $Res call({String image, String description}); } /// @nodoc -class _$StepCopyWithImpl<$Res, $Val extends Step> implements $StepCopyWith<$Res> { +class _$StepCopyWithImpl<$Res, $Val extends Step> + implements $StepCopyWith<$Res> { _$StepCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -679,16 +737,20 @@ class _$StepCopyWithImpl<$Res, $Val extends Step> implements $StepCopyWith<$Res> /// @nodoc abstract class _$$StepImplCopyWith<$Res> implements $StepCopyWith<$Res> { - factory _$$StepImplCopyWith(_$StepImpl value, $Res Function(_$StepImpl) then) = __$$StepImplCopyWithImpl<$Res>; - + factory _$$StepImplCopyWith( + _$StepImpl value, $Res Function(_$StepImpl) then) = + __$$StepImplCopyWithImpl<$Res>; @override @useResult $Res call({String image, String description}); } /// @nodoc -class __$$StepImplCopyWithImpl<$Res> extends _$StepCopyWithImpl<$Res, _$StepImpl> implements _$$StepImplCopyWith<$Res> { - __$$StepImplCopyWithImpl(_$StepImpl _value, $Res Function(_$StepImpl) _then) : super(_value, _then); +class __$$StepImplCopyWithImpl<$Res> + extends _$StepCopyWithImpl<$Res, _$StepImpl> + implements _$$StepImplCopyWith<$Res> { + __$$StepImplCopyWithImpl(_$StepImpl _value, $Res Function(_$StepImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -714,7 +776,8 @@ class __$$StepImplCopyWithImpl<$Res> extends _$StepCopyWithImpl<$Res, _$StepImpl class _$StepImpl implements _Step { const _$StepImpl({required this.image, required this.description}); - factory _$StepImpl.fromJson(Map json) => _$$StepImplFromJson(json); + factory _$StepImpl.fromJson(Map json) => + _$$StepImplFromJson(json); @override final String image; @@ -732,7 +795,8 @@ class _$StepImpl implements _Step { (other.runtimeType == runtimeType && other is _$StepImpl && (identical(other.image, image) || other.image == image) && - (identical(other.description, description) || other.description == description)); + (identical(other.description, description) || + other.description == description)); } @JsonKey(ignore: true) @@ -742,7 +806,8 @@ class _$StepImpl implements _Step { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$StepImplCopyWith<_$StepImpl> get copyWith => __$$StepImplCopyWithImpl<_$StepImpl>(this, _$identity); + _$$StepImplCopyWith<_$StepImpl> get copyWith => + __$$StepImplCopyWithImpl<_$StepImpl>(this, _$identity); @override Map toJson() { @@ -753,17 +818,18 @@ class _$StepImpl implements _Step { } abstract class _Step implements Step { - const factory _Step({required final String image, required final String description}) = _$StepImpl; + const factory _Step( + {required final String image, + required final String description}) = _$StepImpl; factory _Step.fromJson(Map json) = _$StepImpl.fromJson; @override String get image; - @override String get description; - @override @JsonKey(ignore: true) - _$$StepImplCopyWith<_$StepImpl> get copyWith => throw _privateConstructorUsedError; + _$$StepImplCopyWith<_$StepImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/feed/models/recipes_model.g.dart b/lib/features/feed/models/recipes_model.g.dart index e905d77..edb4ed6 100644 --- a/lib/features/feed/models/recipes_model.g.dart +++ b/lib/features/feed/models/recipes_model.g.dart @@ -6,24 +6,32 @@ part of 'recipes_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$RecipesImpl _$$RecipesImplFromJson(Map json) => _$RecipesImpl( +_$RecipesImpl _$$RecipesImplFromJson(Map json) => + _$RecipesImpl( id: (json['id'] as num).toInt(), image: json['image'] as String, state: json['state'] as String, cookingTime: (json['cooking_time'] as num).toInt(), - ingredients: (json['ingredients'] as List).map((e) => Ingredient.fromJson(e as Map)).toList(), + ingredients: (json['ingredients'] as List) + .map((e) => Ingredient.fromJson(e as Map)) + .toList(), description: json['description'] as String, - steps: (json['steps'] as List).map((e) => Step.fromJson(e as Map)).toList(), + steps: (json['steps'] as List) + .map((e) => Step.fromJson(e as Map)) + .toList(), videoUrl: json['video_url'] as String, createdAt: DateTime.parse(json['created_at'] as String), updatedAt: DateTime.parse(json['updated_at'] as String), title: json['title'] as String, type: json['type'] as String, slug: json['slug'] as String, - commentsCount: (json['comments_count'] as num).toInt(), + commentsCount: (json['total_comments'] as num).toInt(), + likesCount: (json['total_likes'] as num).toInt(), + viewsCount: (json['total_views'] as num).toInt(), ); -Map _$$RecipesImplToJson(_$RecipesImpl instance) => { +Map _$$RecipesImplToJson(_$RecipesImpl instance) => + { 'id': instance.id, 'image': instance.image, 'state': instance.state, @@ -37,16 +45,20 @@ Map _$$RecipesImplToJson(_$RecipesImpl instance) => json) => _$IngredientImpl( +_$IngredientImpl _$$IngredientImplFromJson(Map json) => + _$IngredientImpl( name: json['name'] as String, unit: json['unit'] as String?, portion: json['portion'] as String, ); -Map _$$IngredientImplToJson(_$IngredientImpl instance) => { +Map _$$IngredientImplToJson(_$IngredientImpl instance) => + { 'name': instance.name, 'unit': instance.unit, 'portion': instance.portion, @@ -57,7 +69,8 @@ _$StepImpl _$$StepImplFromJson(Map json) => _$StepImpl( description: json['description'] as String, ); -Map _$$StepImplToJson(_$StepImpl instance) => { +Map _$$StepImplToJson(_$StepImpl instance) => + { 'image': instance.image, 'description': instance.description, }; diff --git a/lib/features/feed/models/recipes_pagination_model.dart b/lib/features/feed/models/recipes_pagination_model.dart index 316cf81..0d2abdc 100644 --- a/lib/features/feed/models/recipes_pagination_model.dart +++ b/lib/features/feed/models/recipes_pagination_model.dart @@ -8,17 +8,17 @@ part 'recipes_pagination_model.g.dart'; class RecipesPagination with _$RecipesPagination { const factory RecipesPagination({ @JsonKey(name: 'data') required List recipesList, - @JsonKey(name: "current_page") required int currentPage, - @JsonKey(name: "first_page_url") required String firstPageUrl, - required int from, - @JsonKey(name: "last_page") required int lastPage, - @JsonKey(name: "last_page_url") required String lastPageUrl, - @JsonKey(name: "next_page_url") required String nextPageUrl, - required String path, - @JsonKey(name: "per_page") required int perPage, - @JsonKey(name: "prev_page_url") required dynamic prevPageUrl, - required int to, - required int total, + // @JsonKey(name: "current_page") required int currentPage, + // @JsonKey(name: "first_page_url") required String firstPageUrl, + // required int from, + // @JsonKey(name: "last_page") required int lastPage, + // @JsonKey(name: "last_page_url") required String lastPageUrl, + // @JsonKey(name: "next_page_url") required String nextPageUrl, + // required String path, + // @JsonKey(name: "per_page") required int perPage, + // @JsonKey(name: "prev_page_url") required dynamic prevPageUrl, + // required int to, + // required int total, }) = _RecipesPagination; factory RecipesPagination.fromJson(Map json) => _$RecipesPaginationFromJson(json); diff --git a/lib/features/feed/models/recipes_pagination_model.freezed.dart b/lib/features/feed/models/recipes_pagination_model.freezed.dart index a79dcf0..2f0d43f 100644 --- a/lib/features/feed/models/recipes_pagination_model.freezed.dart +++ b/lib/features/feed/models/recipes_pagination_model.freezed.dart @@ -23,68 +23,28 @@ mixin _$RecipesPagination { @JsonKey(name: 'data') List get recipesList => throw _privateConstructorUsedError; - @JsonKey(name: "current_page") - int get currentPage => throw _privateConstructorUsedError; - - @JsonKey(name: "first_page_url") - String get firstPageUrl => throw _privateConstructorUsedError; - - int get from => throw _privateConstructorUsedError; - - @JsonKey(name: "last_page") - int get lastPage => throw _privateConstructorUsedError; - - @JsonKey(name: "last_page_url") - String get lastPageUrl => throw _privateConstructorUsedError; - - @JsonKey(name: "next_page_url") - String get nextPageUrl => throw _privateConstructorUsedError; - - String get path => throw _privateConstructorUsedError; - - @JsonKey(name: "per_page") - int get perPage => throw _privateConstructorUsedError; - - @JsonKey(name: "prev_page_url") - dynamic get prevPageUrl => throw _privateConstructorUsedError; - - int get to => throw _privateConstructorUsedError; - - int get total => throw _privateConstructorUsedError; - Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $RecipesPaginationCopyWith get copyWith => throw _privateConstructorUsedError; + $RecipesPaginationCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $RecipesPaginationCopyWith<$Res> { - factory $RecipesPaginationCopyWith(RecipesPagination value, $Res Function(RecipesPagination) then) = _$RecipesPaginationCopyWithImpl<$Res, RecipesPagination>; - + factory $RecipesPaginationCopyWith( + RecipesPagination value, $Res Function(RecipesPagination) then) = + _$RecipesPaginationCopyWithImpl<$Res, RecipesPagination>; @useResult - $Res call( - {@JsonKey(name: 'data') List recipesList, - @JsonKey(name: "current_page") int currentPage, - @JsonKey(name: "first_page_url") String firstPageUrl, - int from, - @JsonKey(name: "last_page") int lastPage, - @JsonKey(name: "last_page_url") String lastPageUrl, - @JsonKey(name: "next_page_url") String nextPageUrl, - String path, - @JsonKey(name: "per_page") int perPage, - @JsonKey(name: "prev_page_url") dynamic prevPageUrl, - int to, - int total}); + $Res call({@JsonKey(name: 'data') List recipesList}); } /// @nodoc -class _$RecipesPaginationCopyWithImpl<$Res, $Val extends RecipesPagination> implements $RecipesPaginationCopyWith<$Res> { +class _$RecipesPaginationCopyWithImpl<$Res, $Val extends RecipesPagination> + implements $RecipesPaginationCopyWith<$Res> { _$RecipesPaginationCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -92,163 +52,45 @@ class _$RecipesPaginationCopyWithImpl<$Res, $Val extends RecipesPagination> impl @override $Res call({ Object? recipesList = null, - Object? currentPage = null, - Object? firstPageUrl = null, - Object? from = null, - Object? lastPage = null, - Object? lastPageUrl = null, - Object? nextPageUrl = null, - Object? path = null, - Object? perPage = null, - Object? prevPageUrl = freezed, - Object? to = null, - Object? total = null, }) { return _then(_value.copyWith( recipesList: null == recipesList ? _value.recipesList : recipesList // ignore: cast_nullable_to_non_nullable as List, - currentPage: null == currentPage - ? _value.currentPage - : currentPage // ignore: cast_nullable_to_non_nullable - as int, - firstPageUrl: null == firstPageUrl - ? _value.firstPageUrl - : firstPageUrl // ignore: cast_nullable_to_non_nullable - as String, - from: null == from - ? _value.from - : from // ignore: cast_nullable_to_non_nullable - as int, - lastPage: null == lastPage - ? _value.lastPage - : lastPage // ignore: cast_nullable_to_non_nullable - as int, - lastPageUrl: null == lastPageUrl - ? _value.lastPageUrl - : lastPageUrl // ignore: cast_nullable_to_non_nullable - as String, - nextPageUrl: null == nextPageUrl - ? _value.nextPageUrl - : nextPageUrl // ignore: cast_nullable_to_non_nullable - as String, - path: null == path - ? _value.path - : path // ignore: cast_nullable_to_non_nullable - as String, - perPage: null == perPage - ? _value.perPage - : perPage // ignore: cast_nullable_to_non_nullable - as int, - prevPageUrl: freezed == prevPageUrl - ? _value.prevPageUrl - : prevPageUrl // ignore: cast_nullable_to_non_nullable - as dynamic, - to: null == to - ? _value.to - : to // ignore: cast_nullable_to_non_nullable - as int, - total: null == total - ? _value.total - : total // ignore: cast_nullable_to_non_nullable - as int, ) as $Val); } } /// @nodoc -abstract class _$$RecipesPaginationImplCopyWith<$Res> implements $RecipesPaginationCopyWith<$Res> { - factory _$$RecipesPaginationImplCopyWith(_$RecipesPaginationImpl value, $Res Function(_$RecipesPaginationImpl) then) = +abstract class _$$RecipesPaginationImplCopyWith<$Res> + implements $RecipesPaginationCopyWith<$Res> { + factory _$$RecipesPaginationImplCopyWith(_$RecipesPaginationImpl value, + $Res Function(_$RecipesPaginationImpl) then) = __$$RecipesPaginationImplCopyWithImpl<$Res>; - @override @useResult - $Res call( - {@JsonKey(name: 'data') List recipesList, - @JsonKey(name: "current_page") int currentPage, - @JsonKey(name: "first_page_url") String firstPageUrl, - int from, - @JsonKey(name: "last_page") int lastPage, - @JsonKey(name: "last_page_url") String lastPageUrl, - @JsonKey(name: "next_page_url") String nextPageUrl, - String path, - @JsonKey(name: "per_page") int perPage, - @JsonKey(name: "prev_page_url") dynamic prevPageUrl, - int to, - int total}); + $Res call({@JsonKey(name: 'data') List recipesList}); } /// @nodoc -class __$$RecipesPaginationImplCopyWithImpl<$Res> extends _$RecipesPaginationCopyWithImpl<$Res, _$RecipesPaginationImpl> +class __$$RecipesPaginationImplCopyWithImpl<$Res> + extends _$RecipesPaginationCopyWithImpl<$Res, _$RecipesPaginationImpl> implements _$$RecipesPaginationImplCopyWith<$Res> { - __$$RecipesPaginationImplCopyWithImpl(_$RecipesPaginationImpl _value, $Res Function(_$RecipesPaginationImpl) _then) : super(_value, _then); + __$$RecipesPaginationImplCopyWithImpl(_$RecipesPaginationImpl _value, + $Res Function(_$RecipesPaginationImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override $Res call({ Object? recipesList = null, - Object? currentPage = null, - Object? firstPageUrl = null, - Object? from = null, - Object? lastPage = null, - Object? lastPageUrl = null, - Object? nextPageUrl = null, - Object? path = null, - Object? perPage = null, - Object? prevPageUrl = freezed, - Object? to = null, - Object? total = null, }) { return _then(_$RecipesPaginationImpl( recipesList: null == recipesList ? _value._recipesList : recipesList // ignore: cast_nullable_to_non_nullable as List, - currentPage: null == currentPage - ? _value.currentPage - : currentPage // ignore: cast_nullable_to_non_nullable - as int, - firstPageUrl: null == firstPageUrl - ? _value.firstPageUrl - : firstPageUrl // ignore: cast_nullable_to_non_nullable - as String, - from: null == from - ? _value.from - : from // ignore: cast_nullable_to_non_nullable - as int, - lastPage: null == lastPage - ? _value.lastPage - : lastPage // ignore: cast_nullable_to_non_nullable - as int, - lastPageUrl: null == lastPageUrl - ? _value.lastPageUrl - : lastPageUrl // ignore: cast_nullable_to_non_nullable - as String, - nextPageUrl: null == nextPageUrl - ? _value.nextPageUrl - : nextPageUrl // ignore: cast_nullable_to_non_nullable - as String, - path: null == path - ? _value.path - : path // ignore: cast_nullable_to_non_nullable - as String, - perPage: null == perPage - ? _value.perPage - : perPage // ignore: cast_nullable_to_non_nullable - as int, - prevPageUrl: freezed == prevPageUrl - ? _value.prevPageUrl - : prevPageUrl // ignore: cast_nullable_to_non_nullable - as dynamic, - to: null == to - ? _value.to - : to // ignore: cast_nullable_to_non_nullable - as int, - total: null == total - ? _value.total - : total // ignore: cast_nullable_to_non_nullable - as int, )); } } @@ -257,24 +99,13 @@ class __$$RecipesPaginationImplCopyWithImpl<$Res> extends _$RecipesPaginationCop @JsonSerializable() class _$RecipesPaginationImpl implements _RecipesPagination { const _$RecipesPaginationImpl( - {@JsonKey(name: 'data') required final List recipesList, - @JsonKey(name: "current_page") required this.currentPage, - @JsonKey(name: "first_page_url") required this.firstPageUrl, - required this.from, - @JsonKey(name: "last_page") required this.lastPage, - @JsonKey(name: "last_page_url") required this.lastPageUrl, - @JsonKey(name: "next_page_url") required this.nextPageUrl, - required this.path, - @JsonKey(name: "per_page") required this.perPage, - @JsonKey(name: "prev_page_url") required this.prevPageUrl, - required this.to, - required this.total}) + {@JsonKey(name: 'data') required final List recipesList}) : _recipesList = recipesList; - factory _$RecipesPaginationImpl.fromJson(Map json) => _$$RecipesPaginationImplFromJson(json); + factory _$RecipesPaginationImpl.fromJson(Map json) => + _$$RecipesPaginationImplFromJson(json); final List _recipesList; - @override @JsonKey(name: 'data') List get recipesList { @@ -283,39 +114,9 @@ class _$RecipesPaginationImpl implements _RecipesPagination { return EqualUnmodifiableListView(_recipesList); } - @override - @JsonKey(name: "current_page") - final int currentPage; - @override - @JsonKey(name: "first_page_url") - final String firstPageUrl; - @override - final int from; - @override - @JsonKey(name: "last_page") - final int lastPage; - @override - @JsonKey(name: "last_page_url") - final String lastPageUrl; - @override - @JsonKey(name: "next_page_url") - final String nextPageUrl; - @override - final String path; - @override - @JsonKey(name: "per_page") - final int perPage; - @override - @JsonKey(name: "prev_page_url") - final dynamic prevPageUrl; - @override - final int to; - @override - final int total; - @override String toString() { - return 'RecipesPagination(recipesList: $recipesList, currentPage: $currentPage, firstPageUrl: $firstPageUrl, from: $from, lastPage: $lastPage, lastPageUrl: $lastPageUrl, nextPageUrl: $nextPageUrl, path: $path, perPage: $perPage, prevPageUrl: $prevPageUrl, to: $to, total: $total)'; + return 'RecipesPagination(recipesList: $recipesList)'; } @override @@ -323,29 +124,21 @@ class _$RecipesPaginationImpl implements _RecipesPagination { return identical(this, other) || (other.runtimeType == runtimeType && other is _$RecipesPaginationImpl && - const DeepCollectionEquality().equals(other._recipesList, _recipesList) && - (identical(other.currentPage, currentPage) || other.currentPage == currentPage) && - (identical(other.firstPageUrl, firstPageUrl) || other.firstPageUrl == firstPageUrl) && - (identical(other.from, from) || other.from == from) && - (identical(other.lastPage, lastPage) || other.lastPage == lastPage) && - (identical(other.lastPageUrl, lastPageUrl) || other.lastPageUrl == lastPageUrl) && - (identical(other.nextPageUrl, nextPageUrl) || other.nextPageUrl == nextPageUrl) && - (identical(other.path, path) || other.path == path) && - (identical(other.perPage, perPage) || other.perPage == perPage) && - const DeepCollectionEquality().equals(other.prevPageUrl, prevPageUrl) && - (identical(other.to, to) || other.to == to) && - (identical(other.total, total) || other.total == total)); + const DeepCollectionEquality() + .equals(other._recipesList, _recipesList)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_recipesList), currentPage, firstPageUrl, from, lastPage, lastPageUrl, - nextPageUrl, path, perPage, const DeepCollectionEquality().hash(prevPageUrl), to, total); + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_recipesList)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$RecipesPaginationImplCopyWith<_$RecipesPaginationImpl> get copyWith => __$$RecipesPaginationImplCopyWithImpl<_$RecipesPaginationImpl>(this, _$identity); + _$$RecipesPaginationImplCopyWith<_$RecipesPaginationImpl> get copyWith => + __$$RecipesPaginationImplCopyWithImpl<_$RecipesPaginationImpl>( + this, _$identity); @override Map toJson() { @@ -357,66 +150,17 @@ class _$RecipesPaginationImpl implements _RecipesPagination { abstract class _RecipesPagination implements RecipesPagination { const factory _RecipesPagination( - {@JsonKey(name: 'data') required final List recipesList, - @JsonKey(name: "current_page") required final int currentPage, - @JsonKey(name: "first_page_url") required final String firstPageUrl, - required final int from, - @JsonKey(name: "last_page") required final int lastPage, - @JsonKey(name: "last_page_url") required final String lastPageUrl, - @JsonKey(name: "next_page_url") required final String nextPageUrl, - required final String path, - @JsonKey(name: "per_page") required final int perPage, - @JsonKey(name: "prev_page_url") required final dynamic prevPageUrl, - required final int to, - required final int total}) = _$RecipesPaginationImpl; + {@JsonKey(name: 'data') required final List recipesList}) = + _$RecipesPaginationImpl; - factory _RecipesPagination.fromJson(Map json) = _$RecipesPaginationImpl.fromJson; + factory _RecipesPagination.fromJson(Map json) = + _$RecipesPaginationImpl.fromJson; @override @JsonKey(name: 'data') List get recipesList; - - @override - @JsonKey(name: "current_page") - int get currentPage; - - @override - @JsonKey(name: "first_page_url") - String get firstPageUrl; - - @override - int get from; - - @override - @JsonKey(name: "last_page") - int get lastPage; - - @override - @JsonKey(name: "last_page_url") - String get lastPageUrl; - - @override - @JsonKey(name: "next_page_url") - String get nextPageUrl; - - @override - String get path; - - @override - @JsonKey(name: "per_page") - int get perPage; - - @override - @JsonKey(name: "prev_page_url") - dynamic get prevPageUrl; - - @override - int get to; - - @override - int get total; - @override @JsonKey(ignore: true) - _$$RecipesPaginationImplCopyWith<_$RecipesPaginationImpl> get copyWith => throw _privateConstructorUsedError; + _$$RecipesPaginationImplCopyWith<_$RecipesPaginationImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/feed/models/recipes_pagination_model.g.dart b/lib/features/feed/models/recipes_pagination_model.g.dart index fd36d17..109f39d 100644 --- a/lib/features/feed/models/recipes_pagination_model.g.dart +++ b/lib/features/feed/models/recipes_pagination_model.g.dart @@ -6,32 +6,16 @@ part of 'recipes_pagination_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$RecipesPaginationImpl _$$RecipesPaginationImplFromJson(Map json) => _$RecipesPaginationImpl( - recipesList: (json['data'] as List).map((e) => Recipes.fromJson(e as Map)).toList(), - currentPage: (json['current_page'] as num).toInt(), - firstPageUrl: json['first_page_url'] as String, - from: (json['from'] as num).toInt(), - lastPage: (json['last_page'] as num).toInt(), - lastPageUrl: json['last_page_url'] as String, - nextPageUrl: json['next_page_url'] as String, - path: json['path'] as String, - perPage: (json['per_page'] as num).toInt(), - prevPageUrl: json['prev_page_url'], - to: (json['to'] as num).toInt(), - total: (json['total'] as num).toInt(), +_$RecipesPaginationImpl _$$RecipesPaginationImplFromJson( + Map json) => + _$RecipesPaginationImpl( + recipesList: (json['data'] as List) + .map((e) => Recipes.fromJson(e as Map)) + .toList(), ); -Map _$$RecipesPaginationImplToJson(_$RecipesPaginationImpl instance) => { +Map _$$RecipesPaginationImplToJson( + _$RecipesPaginationImpl instance) => + { 'data': instance.recipesList, - 'current_page': instance.currentPage, - 'first_page_url': instance.firstPageUrl, - 'from': instance.from, - 'last_page': instance.lastPage, - 'last_page_url': instance.lastPageUrl, - 'next_page_url': instance.nextPageUrl, - 'path': instance.path, - 'per_page': instance.perPage, - 'prev_page_url': instance.prevPageUrl, - 'to': instance.to, - 'total': instance.total, }; diff --git a/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart b/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart index 1bb34c3..ab3385f 100644 --- a/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart +++ b/lib/features/feed/presentation/bloc/feed_cubit/feed_state.freezed.dart @@ -24,7 +24,6 @@ mixin _$FeedState { required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; - @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { @@ -71,28 +70,35 @@ mixin _$FeedState { /// @nodoc abstract class $FeedStateCopyWith<$Res> { - factory $FeedStateCopyWith(FeedState value, $Res Function(FeedState) then) = _$FeedStateCopyWithImpl<$Res, FeedState>; + factory $FeedStateCopyWith(FeedState value, $Res Function(FeedState) then) = + _$FeedStateCopyWithImpl<$Res, FeedState>; } /// @nodoc -class _$FeedStateCopyWithImpl<$Res, $Val extends FeedState> implements $FeedStateCopyWith<$Res> { +class _$FeedStateCopyWithImpl<$Res, $Val extends FeedState> + implements $FeedStateCopyWith<$Res> { _$FeedStateCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; } /// @nodoc abstract class _$$FeedStateImplCopyWith<$Res> { - factory _$$FeedStateImplCopyWith(_$FeedStateImpl value, $Res Function(_$FeedStateImpl) then) = __$$FeedStateImplCopyWithImpl<$Res>; + factory _$$FeedStateImplCopyWith( + _$FeedStateImpl value, $Res Function(_$FeedStateImpl) then) = + __$$FeedStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$FeedStateImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateImpl> implements _$$FeedStateImplCopyWith<$Res> { - __$$FeedStateImplCopyWithImpl(_$FeedStateImpl _value, $Res Function(_$FeedStateImpl) _then) : super(_value, _then); +class __$$FeedStateImplCopyWithImpl<$Res> + extends _$FeedStateCopyWithImpl<$Res, _$FeedStateImpl> + implements _$$FeedStateImplCopyWith<$Res> { + __$$FeedStateImplCopyWithImpl( + _$FeedStateImpl _value, $Res Function(_$FeedStateImpl) _then) + : super(_value, _then); } /// @nodoc @@ -107,7 +113,8 @@ class _$FeedStateImpl implements _FeedState { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$FeedStateImpl); } @override @@ -194,14 +201,18 @@ abstract class _FeedState implements FeedState { /// @nodoc abstract class _$$FeedStateLoadingImplCopyWith<$Res> { - factory _$$FeedStateLoadingImplCopyWith(_$FeedStateLoadingImpl value, $Res Function(_$FeedStateLoadingImpl) then) = + factory _$$FeedStateLoadingImplCopyWith(_$FeedStateLoadingImpl value, + $Res Function(_$FeedStateLoadingImpl) then) = __$$FeedStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$FeedStateLoadingImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadingImpl> +class __$$FeedStateLoadingImplCopyWithImpl<$Res> + extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadingImpl> implements _$$FeedStateLoadingImplCopyWith<$Res> { - __$$FeedStateLoadingImplCopyWithImpl(_$FeedStateLoadingImpl _value, $Res Function(_$FeedStateLoadingImpl) _then) : super(_value, _then); + __$$FeedStateLoadingImplCopyWithImpl(_$FeedStateLoadingImpl _value, + $Res Function(_$FeedStateLoadingImpl) _then) + : super(_value, _then); } /// @nodoc @@ -216,7 +227,8 @@ class _$FeedStateLoadingImpl implements FeedStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateLoadingImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$FeedStateLoadingImpl); } @override @@ -303,15 +315,20 @@ abstract class FeedStateLoading implements FeedState { /// @nodoc abstract class _$$FeedStateLoadedImplCopyWith<$Res> { - factory _$$FeedStateLoadedImplCopyWith(_$FeedStateLoadedImpl value, $Res Function(_$FeedStateLoadedImpl) then) = __$$FeedStateLoadedImplCopyWithImpl<$Res>; - + factory _$$FeedStateLoadedImplCopyWith(_$FeedStateLoadedImpl value, + $Res Function(_$FeedStateLoadedImpl) then) = + __$$FeedStateLoadedImplCopyWithImpl<$Res>; @useResult $Res call({List feedBlogPostList}); } /// @nodoc -class __$$FeedStateLoadedImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadedImpl> implements _$$FeedStateLoadedImplCopyWith<$Res> { - __$$FeedStateLoadedImplCopyWithImpl(_$FeedStateLoadedImpl _value, $Res Function(_$FeedStateLoadedImpl) _then) : super(_value, _then); +class __$$FeedStateLoadedImplCopyWithImpl<$Res> + extends _$FeedStateCopyWithImpl<$Res, _$FeedStateLoadedImpl> + implements _$$FeedStateLoadedImplCopyWith<$Res> { + __$$FeedStateLoadedImplCopyWithImpl( + _$FeedStateLoadedImpl _value, $Res Function(_$FeedStateLoadedImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -330,13 +347,15 @@ class __$$FeedStateLoadedImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl< /// @nodoc class _$FeedStateLoadedImpl implements FeedStateLoaded { - const _$FeedStateLoadedImpl({required final List feedBlogPostList}) : _feedBlogPostList = feedBlogPostList; + const _$FeedStateLoadedImpl( + {required final List feedBlogPostList}) + : _feedBlogPostList = feedBlogPostList; final List _feedBlogPostList; - @override List get feedBlogPostList { - if (_feedBlogPostList is EqualUnmodifiableListView) return _feedBlogPostList; + if (_feedBlogPostList is EqualUnmodifiableListView) + return _feedBlogPostList; // ignore: implicit_dynamic_type return EqualUnmodifiableListView(_feedBlogPostList); } @@ -351,16 +370,20 @@ class _$FeedStateLoadedImpl implements FeedStateLoaded { return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateLoadedImpl && - const DeepCollectionEquality().equals(other._feedBlogPostList, _feedBlogPostList)); + const DeepCollectionEquality() + .equals(other._feedBlogPostList, _feedBlogPostList)); } @override - int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_feedBlogPostList)); + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_feedBlogPostList)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => __$$FeedStateLoadedImplCopyWithImpl<_$FeedStateLoadedImpl>(this, _$identity); + _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => + __$$FeedStateLoadedImplCopyWithImpl<_$FeedStateLoadedImpl>( + this, _$identity); @override @optionalTypeArgs @@ -438,25 +461,32 @@ class _$FeedStateLoadedImpl implements FeedStateLoaded { } abstract class FeedStateLoaded implements FeedState { - const factory FeedStateLoaded({required final List feedBlogPostList}) = _$FeedStateLoadedImpl; + const factory FeedStateLoaded( + {required final List feedBlogPostList}) = + _$FeedStateLoadedImpl; List get feedBlogPostList; - @JsonKey(ignore: true) - _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; + _$$FeedStateLoadedImplCopyWith<_$FeedStateLoadedImpl> get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class _$$FeedStateErrorImplCopyWith<$Res> { - factory _$$FeedStateErrorImplCopyWith(_$FeedStateErrorImpl value, $Res Function(_$FeedStateErrorImpl) then) = __$$FeedStateErrorImplCopyWithImpl<$Res>; - + factory _$$FeedStateErrorImplCopyWith(_$FeedStateErrorImpl value, + $Res Function(_$FeedStateErrorImpl) then) = + __$$FeedStateErrorImplCopyWithImpl<$Res>; @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$FeedStateErrorImplCopyWithImpl<$Res> extends _$FeedStateCopyWithImpl<$Res, _$FeedStateErrorImpl> implements _$$FeedStateErrorImplCopyWith<$Res> { - __$$FeedStateErrorImplCopyWithImpl(_$FeedStateErrorImpl _value, $Res Function(_$FeedStateErrorImpl) _then) : super(_value, _then); +class __$$FeedStateErrorImplCopyWithImpl<$Res> + extends _$FeedStateCopyWithImpl<$Res, _$FeedStateErrorImpl> + implements _$$FeedStateErrorImplCopyWith<$Res> { + __$$FeedStateErrorImplCopyWithImpl( + _$FeedStateErrorImpl _value, $Res Function(_$FeedStateErrorImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -490,7 +520,8 @@ class _$FeedStateErrorImpl implements FeedStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$FeedStateErrorImpl && - (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); } @override @@ -499,7 +530,9 @@ class _$FeedStateErrorImpl implements FeedStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => __$$FeedStateErrorImplCopyWithImpl<_$FeedStateErrorImpl>(this, _$identity); + _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => + __$$FeedStateErrorImplCopyWithImpl<_$FeedStateErrorImpl>( + this, _$identity); @override @optionalTypeArgs @@ -577,10 +610,11 @@ class _$FeedStateErrorImpl implements FeedStateError { } abstract class FeedStateError implements FeedState { - const factory FeedStateError({required final String errorMessage}) = _$FeedStateErrorImpl; + const factory FeedStateError({required final String errorMessage}) = + _$FeedStateErrorImpl; String get errorMessage; - @JsonKey(ignore: true) - _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => throw _privateConstructorUsedError; + _$$FeedStateErrorImplCopyWith<_$FeedStateErrorImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.freezed.dart b/lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.freezed.dart index 928221e..e8aa88e 100644 --- a/lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.freezed.dart +++ b/lib/features/feed/presentation/bloc/recipes_cubit/recipes_state.freezed.dart @@ -24,7 +24,6 @@ mixin _$RecipesState { required TResult Function(String errorMessage) error, }) => throw _privateConstructorUsedError; - @optionalTypeArgs TResult? whenOrNull( TResult? Function()? $default, { @@ -71,28 +70,36 @@ mixin _$RecipesState { /// @nodoc abstract class $RecipesStateCopyWith<$Res> { - factory $RecipesStateCopyWith(RecipesState value, $Res Function(RecipesState) then) = _$RecipesStateCopyWithImpl<$Res, RecipesState>; + factory $RecipesStateCopyWith( + RecipesState value, $Res Function(RecipesState) then) = + _$RecipesStateCopyWithImpl<$Res, RecipesState>; } /// @nodoc -class _$RecipesStateCopyWithImpl<$Res, $Val extends RecipesState> implements $RecipesStateCopyWith<$Res> { +class _$RecipesStateCopyWithImpl<$Res, $Val extends RecipesState> + implements $RecipesStateCopyWith<$Res> { _$RecipesStateCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; } /// @nodoc abstract class _$$RecipesStateImplCopyWith<$Res> { - factory _$$RecipesStateImplCopyWith(_$RecipesStateImpl value, $Res Function(_$RecipesStateImpl) then) = __$$RecipesStateImplCopyWithImpl<$Res>; + factory _$$RecipesStateImplCopyWith( + _$RecipesStateImpl value, $Res Function(_$RecipesStateImpl) then) = + __$$RecipesStateImplCopyWithImpl<$Res>; } /// @nodoc -class __$$RecipesStateImplCopyWithImpl<$Res> extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateImpl> implements _$$RecipesStateImplCopyWith<$Res> { - __$$RecipesStateImplCopyWithImpl(_$RecipesStateImpl _value, $Res Function(_$RecipesStateImpl) _then) : super(_value, _then); +class __$$RecipesStateImplCopyWithImpl<$Res> + extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateImpl> + implements _$$RecipesStateImplCopyWith<$Res> { + __$$RecipesStateImplCopyWithImpl( + _$RecipesStateImpl _value, $Res Function(_$RecipesStateImpl) _then) + : super(_value, _then); } /// @nodoc @@ -107,7 +114,8 @@ class _$RecipesStateImpl implements _RecipesState { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$RecipesStateImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$RecipesStateImpl); } @override @@ -194,14 +202,18 @@ abstract class _RecipesState implements RecipesState { /// @nodoc abstract class _$$RecipesStateLoadingImplCopyWith<$Res> { - factory _$$RecipesStateLoadingImplCopyWith(_$RecipesStateLoadingImpl value, $Res Function(_$RecipesStateLoadingImpl) then) = + factory _$$RecipesStateLoadingImplCopyWith(_$RecipesStateLoadingImpl value, + $Res Function(_$RecipesStateLoadingImpl) then) = __$$RecipesStateLoadingImplCopyWithImpl<$Res>; } /// @nodoc -class __$$RecipesStateLoadingImplCopyWithImpl<$Res> extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateLoadingImpl> +class __$$RecipesStateLoadingImplCopyWithImpl<$Res> + extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateLoadingImpl> implements _$$RecipesStateLoadingImplCopyWith<$Res> { - __$$RecipesStateLoadingImplCopyWithImpl(_$RecipesStateLoadingImpl _value, $Res Function(_$RecipesStateLoadingImpl) _then) : super(_value, _then); + __$$RecipesStateLoadingImplCopyWithImpl(_$RecipesStateLoadingImpl _value, + $Res Function(_$RecipesStateLoadingImpl) _then) + : super(_value, _then); } /// @nodoc @@ -216,7 +228,9 @@ class _$RecipesStateLoadingImpl implements RecipesStateLoading { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType && other is _$RecipesStateLoadingImpl); + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$RecipesStateLoadingImpl); } @override @@ -303,17 +317,20 @@ abstract class RecipesStateLoading implements RecipesState { /// @nodoc abstract class _$$RecipesStateLoadedImplCopyWith<$Res> { - factory _$$RecipesStateLoadedImplCopyWith(_$RecipesStateLoadedImpl value, $Res Function(_$RecipesStateLoadedImpl) then) = + factory _$$RecipesStateLoadedImplCopyWith(_$RecipesStateLoadedImpl value, + $Res Function(_$RecipesStateLoadedImpl) then) = __$$RecipesStateLoadedImplCopyWithImpl<$Res>; - @useResult $Res call({List recipesList}); } /// @nodoc -class __$$RecipesStateLoadedImplCopyWithImpl<$Res> extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateLoadedImpl> +class __$$RecipesStateLoadedImplCopyWithImpl<$Res> + extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateLoadedImpl> implements _$$RecipesStateLoadedImplCopyWith<$Res> { - __$$RecipesStateLoadedImplCopyWithImpl(_$RecipesStateLoadedImpl _value, $Res Function(_$RecipesStateLoadedImpl) _then) : super(_value, _then); + __$$RecipesStateLoadedImplCopyWithImpl(_$RecipesStateLoadedImpl _value, + $Res Function(_$RecipesStateLoadedImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -332,10 +349,10 @@ class __$$RecipesStateLoadedImplCopyWithImpl<$Res> extends _$RecipesStateCopyWit /// @nodoc class _$RecipesStateLoadedImpl implements RecipesStateLoaded { - const _$RecipesStateLoadedImpl({required final List recipesList}) : _recipesList = recipesList; + const _$RecipesStateLoadedImpl({required final List recipesList}) + : _recipesList = recipesList; final List _recipesList; - @override List get recipesList { if (_recipesList is EqualUnmodifiableListView) return _recipesList; @@ -351,17 +368,22 @@ class _$RecipesStateLoadedImpl implements RecipesStateLoaded { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && other is _$RecipesStateLoadedImpl && const DeepCollectionEquality().equals(other._recipesList, _recipesList)); + (other.runtimeType == runtimeType && + other is _$RecipesStateLoadedImpl && + const DeepCollectionEquality() + .equals(other._recipesList, _recipesList)); } @override - int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_recipesList)); + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_recipesList)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$RecipesStateLoadedImplCopyWith<_$RecipesStateLoadedImpl> get copyWith => - __$$RecipesStateLoadedImplCopyWithImpl<_$RecipesStateLoadedImpl>(this, _$identity); + __$$RecipesStateLoadedImplCopyWithImpl<_$RecipesStateLoadedImpl>( + this, _$identity); @override @optionalTypeArgs @@ -439,27 +461,31 @@ class _$RecipesStateLoadedImpl implements RecipesStateLoaded { } abstract class RecipesStateLoaded implements RecipesState { - const factory RecipesStateLoaded({required final List recipesList}) = _$RecipesStateLoadedImpl; + const factory RecipesStateLoaded({required final List recipesList}) = + _$RecipesStateLoadedImpl; List get recipesList; - @JsonKey(ignore: true) - _$$RecipesStateLoadedImplCopyWith<_$RecipesStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; + _$$RecipesStateLoadedImplCopyWith<_$RecipesStateLoadedImpl> get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class _$$RecipesStateErrorImplCopyWith<$Res> { - factory _$$RecipesStateErrorImplCopyWith(_$RecipesStateErrorImpl value, $Res Function(_$RecipesStateErrorImpl) then) = + factory _$$RecipesStateErrorImplCopyWith(_$RecipesStateErrorImpl value, + $Res Function(_$RecipesStateErrorImpl) then) = __$$RecipesStateErrorImplCopyWithImpl<$Res>; - @useResult $Res call({String errorMessage}); } /// @nodoc -class __$$RecipesStateErrorImplCopyWithImpl<$Res> extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateErrorImpl> +class __$$RecipesStateErrorImplCopyWithImpl<$Res> + extends _$RecipesStateCopyWithImpl<$Res, _$RecipesStateErrorImpl> implements _$$RecipesStateErrorImplCopyWith<$Res> { - __$$RecipesStateErrorImplCopyWithImpl(_$RecipesStateErrorImpl _value, $Res Function(_$RecipesStateErrorImpl) _then) : super(_value, _then); + __$$RecipesStateErrorImplCopyWithImpl(_$RecipesStateErrorImpl _value, + $Res Function(_$RecipesStateErrorImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -493,7 +519,8 @@ class _$RecipesStateErrorImpl implements RecipesStateError { return identical(this, other) || (other.runtimeType == runtimeType && other is _$RecipesStateErrorImpl && - (identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage)); + (identical(other.errorMessage, errorMessage) || + other.errorMessage == errorMessage)); } @override @@ -502,7 +529,9 @@ class _$RecipesStateErrorImpl implements RecipesStateError { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$RecipesStateErrorImplCopyWith<_$RecipesStateErrorImpl> get copyWith => __$$RecipesStateErrorImplCopyWithImpl<_$RecipesStateErrorImpl>(this, _$identity); + _$$RecipesStateErrorImplCopyWith<_$RecipesStateErrorImpl> get copyWith => + __$$RecipesStateErrorImplCopyWithImpl<_$RecipesStateErrorImpl>( + this, _$identity); @override @optionalTypeArgs @@ -580,10 +609,11 @@ class _$RecipesStateErrorImpl implements RecipesStateError { } abstract class RecipesStateError implements RecipesState { - const factory RecipesStateError({required final String errorMessage}) = _$RecipesStateErrorImpl; + const factory RecipesStateError({required final String errorMessage}) = + _$RecipesStateErrorImpl; String get errorMessage; - @JsonKey(ignore: true) - _$$RecipesStateErrorImplCopyWith<_$RecipesStateErrorImpl> get copyWith => throw _privateConstructorUsedError; + _$$RecipesStateErrorImplCopyWith<_$RecipesStateErrorImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/feed/presentation/pages/feed_screen.dart b/lib/features/feed/presentation/pages/feed_screen.dart index 5cfa100..ab7bf32 100644 --- a/lib/features/feed/presentation/pages/feed_screen.dart +++ b/lib/features/feed/presentation/pages/feed_screen.dart @@ -55,7 +55,14 @@ class _FeedScreenState extends State { ), ]; }, - body: _selectedChipIndex == 0 ? _buildAllBlogPosts() : _buildAllRecipes(), + body: Builder( + builder: (BuildContext context) { + if (_selectedChipIndex == 0) + return _buildAllBlogPosts(); + else + return _buildAllRecipes(); + }, + ), ), ); } diff --git a/lib/features/feed/repositories/feed_repository.dart b/lib/features/feed/repositories/feed_repository.dart index 60cd1df..0d2476f 100644 --- a/lib/features/feed/repositories/feed_repository.dart +++ b/lib/features/feed/repositories/feed_repository.dart @@ -1,3 +1,4 @@ +import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; import 'package:eatvio_app/features/feed/models/recipes_model.dart'; import 'package:eatvio_app/features/feed/services/feed_service.dart'; @@ -22,4 +23,12 @@ class FeedRepository { rethrow; } } + + Future getDiets() async { + try { + return (await feedService.getDiets()); + } catch (e) { + rethrow; + } + } } diff --git a/lib/features/feed/services/feed_service.dart b/lib/features/feed/services/feed_service.dart index d9bf881..0d848a5 100644 --- a/lib/features/feed/services/feed_service.dart +++ b/lib/features/feed/services/feed_service.dart @@ -1,4 +1,5 @@ import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/feed/models/feed_blog_post_settings_model.dart'; import 'package:eatvio_app/features/feed/models/recipes_pagination_model.dart'; import 'package:retrofit/retrofit.dart'; @@ -14,4 +15,7 @@ abstract class FeedService { @GET('/api/recipes/index') Future getRecipes(); + + @GET('/api/diets/index') + Future getDiets(); } diff --git a/lib/features/feed/services/feed_service.g.dart b/lib/features/feed/services/feed_service.g.dart index a8d9ec0..77b6577 100644 --- a/lib/features/feed/services/feed_service.g.dart +++ b/lib/features/feed/services/feed_service.g.dart @@ -24,22 +24,23 @@ class _FeedService implements FeedService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio.fetch>( + _setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/blogPosts/index', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/blogPosts/index', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = FeedBlogPostSettingsModel.fromJson(_result.data!); return _value; } @@ -50,28 +51,58 @@ class _FeedService implements FeedService { final queryParameters = {}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio + .fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/recipes/index', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/recipes/index', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = RecipesPagination.fromJson(_result.data!); return _value; } + @override + Future getDiets() async { + final _extra = {}; + final queryParameters = {}; + final _headers = {}; + const Map? _data = null; + final _result = await _dio + .fetch>(_setStreamType(Options( + method: 'GET', + headers: _headers, + extra: _extra, + ) + .compose( + _dio.options, + '/api/diets/index', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); + final _value = DietsPagination.fromJson(_result.data!); + return _value; + } + RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && + !(requestOptions.responseType == ResponseType.bytes || + requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { diff --git a/lib/features/recipes/presentation/pages/about_recipes_screen.dart b/lib/features/recipes/presentation/pages/about_recipes_screen.dart index 27d69e3..fb4ae6b 100644 --- a/lib/features/recipes/presentation/pages/about_recipes_screen.dart +++ b/lib/features/recipes/presentation/pages/about_recipes_screen.dart @@ -65,14 +65,55 @@ class AboutRecipesScreen extends StatelessWidget { imageUrl: baseUrl + '/storage/' + recipes.image, ), SizedBox(height: 12), - Text(recipes.ingredients.toString()), - Text('Пошаговый рецепт'), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + 'Ингредиенты', + style: TextStyle( + color: Colors.black, + fontSize: 16, + fontWeight: FontWeight.w500, + height: 1, + ), + ), + ), + SizedBox(height: 12), + ListView.separated( + padding: const EdgeInsets.symmetric(horizontal: 16), + shrinkWrap: true, + physics: NeverScrollableScrollPhysics(), + itemBuilder: (context, index) => _ingredient(recipes.ingredients[index]), + separatorBuilder: (context, index) => SizedBox(height: 4), + itemCount: recipes.ingredients.length, + ), + SizedBox(height: 12), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + 'Пошаговый рецепт', + style: TextStyle( + color: Colors.black, + fontSize: 16, + fontWeight: FontWeight.w500, + height: 1, + ), + ), + ), + SizedBox(height: 12), ListView.separated( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), - itemBuilder: (context, index) => - _step(recipes.steps[index], index + 1), - separatorBuilder: (context, index) => SizedBox(height: 16), + itemBuilder: (context, index) => _step(recipes.steps[index], index + 1), + separatorBuilder: (context, index) => Padding( + padding: const EdgeInsets.all(16), + child: Container( + height: 0.4, + decoration: BoxDecoration( + color: Colors.grey, + borderRadius: BorderRadius.circular(16), + ), + ), + ), itemCount: recipes.steps.length, ), ], @@ -81,14 +122,26 @@ class AboutRecipesScreen extends StatelessWidget { ); } - _step(step.Step step, int stepNubmer) { + _ingredient(Ingredient ingredient) { + return Text( + '• '+ ingredient.name + ' ' + ingredient.portion + ' ' + (ingredient.unit ?? ''), + style: TextStyle( + color: Colors.black, + fontSize: 14, + fontWeight: FontWeight.w400, + height: 1.2, + ), + ); + } + + _step(step.Step step, int stepNumber) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: 16), child: Text( - 'Шаг ' + stepNubmer.toString(), + 'Шаг ' + stepNumber.toString(), style: TextStyle( color: Colors.black54, fontSize: 14, @@ -112,7 +165,13 @@ class AboutRecipesScreen extends StatelessWidget { ), SizedBox(height: 8), if (step.image.length > 1) - CachedNetworkImage(imageUrl: baseUrl + '/storage/' + step.image), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: ClipRRect( + borderRadius: BorderRadius.circular(16), + child: CachedNetworkImage(imageUrl: baseUrl + '/storage/' + step.image), + ), + ) ], ); } diff --git a/lib/features/registration/models/location_model.freezed.dart b/lib/features/registration/models/location_model.freezed.dart index 852b5f2..f640ca2 100644 --- a/lib/features/registration/models/location_model.freezed.dart +++ b/lib/features/registration/models/location_model.freezed.dart @@ -21,31 +21,33 @@ LocationModel _$LocationModelFromJson(Map json) { /// @nodoc mixin _$LocationModel { List get locations => throw _privateConstructorUsedError; - @JsonKey(name: 'response_body') String get responseBody => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; - @JsonKey(ignore: true) - $LocationModelCopyWith get copyWith => throw _privateConstructorUsedError; + $LocationModelCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $LocationModelCopyWith<$Res> { - factory $LocationModelCopyWith(LocationModel value, $Res Function(LocationModel) then) = _$LocationModelCopyWithImpl<$Res, LocationModel>; - + factory $LocationModelCopyWith( + LocationModel value, $Res Function(LocationModel) then) = + _$LocationModelCopyWithImpl<$Res, LocationModel>; @useResult - $Res call({List locations, @JsonKey(name: 'response_body') String responseBody}); + $Res call( + {List locations, + @JsonKey(name: 'response_body') String responseBody}); } /// @nodoc -class _$LocationModelCopyWithImpl<$Res, $Val extends LocationModel> implements $LocationModelCopyWith<$Res> { +class _$LocationModelCopyWithImpl<$Res, $Val extends LocationModel> + implements $LocationModelCopyWith<$Res> { _$LocationModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; - // ignore: unused_field final $Res Function($Val) _then; @@ -69,17 +71,25 @@ class _$LocationModelCopyWithImpl<$Res, $Val extends LocationModel> implements $ } /// @nodoc -abstract class _$$LocationModelImplCopyWith<$Res> implements $LocationModelCopyWith<$Res> { - factory _$$LocationModelImplCopyWith(_$LocationModelImpl value, $Res Function(_$LocationModelImpl) then) = __$$LocationModelImplCopyWithImpl<$Res>; - +abstract class _$$LocationModelImplCopyWith<$Res> + implements $LocationModelCopyWith<$Res> { + factory _$$LocationModelImplCopyWith( + _$LocationModelImpl value, $Res Function(_$LocationModelImpl) then) = + __$$LocationModelImplCopyWithImpl<$Res>; @override @useResult - $Res call({List locations, @JsonKey(name: 'response_body') String responseBody}); + $Res call( + {List locations, + @JsonKey(name: 'response_body') String responseBody}); } /// @nodoc -class __$$LocationModelImplCopyWithImpl<$Res> extends _$LocationModelCopyWithImpl<$Res, _$LocationModelImpl> implements _$$LocationModelImplCopyWith<$Res> { - __$$LocationModelImplCopyWithImpl(_$LocationModelImpl _value, $Res Function(_$LocationModelImpl) _then) : super(_value, _then); +class __$$LocationModelImplCopyWithImpl<$Res> + extends _$LocationModelCopyWithImpl<$Res, _$LocationModelImpl> + implements _$$LocationModelImplCopyWith<$Res> { + __$$LocationModelImplCopyWithImpl( + _$LocationModelImpl _value, $Res Function(_$LocationModelImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -103,12 +113,15 @@ class __$$LocationModelImplCopyWithImpl<$Res> extends _$LocationModelCopyWithImp /// @nodoc @JsonSerializable() class _$LocationModelImpl implements _LocationModel { - const _$LocationModelImpl({required final List locations, @JsonKey(name: 'response_body') required this.responseBody}) : _locations = locations; + const _$LocationModelImpl( + {required final List locations, + @JsonKey(name: 'response_body') required this.responseBody}) + : _locations = locations; - factory _$LocationModelImpl.fromJson(Map json) => _$$LocationModelImplFromJson(json); + factory _$LocationModelImpl.fromJson(Map json) => + _$$LocationModelImplFromJson(json); final List _locations; - @override List get locations { if (_locations is EqualUnmodifiableListView) return _locations; @@ -130,18 +143,22 @@ class _$LocationModelImpl implements _LocationModel { return identical(this, other) || (other.runtimeType == runtimeType && other is _$LocationModelImpl && - const DeepCollectionEquality().equals(other._locations, _locations) && - (identical(other.responseBody, responseBody) || other.responseBody == responseBody)); + const DeepCollectionEquality() + .equals(other._locations, _locations) && + (identical(other.responseBody, responseBody) || + other.responseBody == responseBody)); } @JsonKey(ignore: true) @override - int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_locations), responseBody); + int get hashCode => Object.hash(runtimeType, + const DeepCollectionEquality().hash(_locations), responseBody); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$LocationModelImplCopyWith<_$LocationModelImpl> get copyWith => __$$LocationModelImplCopyWithImpl<_$LocationModelImpl>(this, _$identity); + _$$LocationModelImplCopyWith<_$LocationModelImpl> get copyWith => + __$$LocationModelImplCopyWithImpl<_$LocationModelImpl>(this, _$identity); @override Map toJson() { @@ -152,19 +169,21 @@ class _$LocationModelImpl implements _LocationModel { } abstract class _LocationModel implements LocationModel { - const factory _LocationModel({required final List locations, @JsonKey(name: 'response_body') required final String responseBody}) = + const factory _LocationModel( + {required final List locations, + @JsonKey(name: 'response_body') required final String responseBody}) = _$LocationModelImpl; - factory _LocationModel.fromJson(Map json) = _$LocationModelImpl.fromJson; + factory _LocationModel.fromJson(Map json) = + _$LocationModelImpl.fromJson; @override List get locations; - @override @JsonKey(name: 'response_body') String get responseBody; - @override @JsonKey(ignore: true) - _$$LocationModelImplCopyWith<_$LocationModelImpl> get copyWith => throw _privateConstructorUsedError; + _$$LocationModelImplCopyWith<_$LocationModelImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/registration/models/location_model.g.dart b/lib/features/registration/models/location_model.g.dart index da69ba9..449630a 100644 --- a/lib/features/registration/models/location_model.g.dart +++ b/lib/features/registration/models/location_model.g.dart @@ -6,12 +6,15 @@ part of 'location_model.dart'; // JsonSerializableGenerator // ************************************************************************** -_$LocationModelImpl _$$LocationModelImplFromJson(Map json) => _$LocationModelImpl( - locations: (json['locations'] as List).map((e) => e as String).toList(), +_$LocationModelImpl _$$LocationModelImplFromJson(Map json) => + _$LocationModelImpl( + locations: + (json['locations'] as List).map((e) => e as String).toList(), responseBody: json['response_body'] as String, ); -Map _$$LocationModelImplToJson(_$LocationModelImpl instance) => { +Map _$$LocationModelImplToJson(_$LocationModelImpl instance) => + { 'locations': instance.locations, 'response_body': instance.responseBody, }; 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 index 63ae2c0..dcb4923 100644 --- a/lib/features/registration/presentation/bloc/registration_cubit/registration_state.freezed.dart +++ b/lib/features/registration/presentation/bloc/registration_cubit/registration_state.freezed.dart @@ -19,13 +19,15 @@ mixin _$RegistrationState { UserRegistrationSheet get sheet => throw _privateConstructorUsedError; @JsonKey(ignore: true) - $RegistrationStateCopyWith get copyWith => throw _privateConstructorUsedError; + $RegistrationStateCopyWith get copyWith => + throw _privateConstructorUsedError; } /// @nodoc abstract class $RegistrationStateCopyWith<$Res> { - factory $RegistrationStateCopyWith(RegistrationState value, $Res Function(RegistrationState) then) = _$RegistrationStateCopyWithImpl<$Res, RegistrationState>; - + factory $RegistrationStateCopyWith( + RegistrationState value, $Res Function(RegistrationState) then) = + _$RegistrationStateCopyWithImpl<$Res, RegistrationState>; @useResult $Res call({UserRegistrationSheet sheet}); @@ -33,12 +35,12 @@ abstract class $RegistrationStateCopyWith<$Res> { } /// @nodoc -class _$RegistrationStateCopyWithImpl<$Res, $Val extends RegistrationState> implements $RegistrationStateCopyWith<$Res> { +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; @@ -65,10 +67,11 @@ class _$RegistrationStateCopyWithImpl<$Res, $Val extends RegistrationState> impl } /// @nodoc -abstract class _$$RegistrationStateImplCopyWith<$Res> implements $RegistrationStateCopyWith<$Res> { - factory _$$RegistrationStateImplCopyWith(_$RegistrationStateImpl value, $Res Function(_$RegistrationStateImpl) then) = +abstract class _$$RegistrationStateImplCopyWith<$Res> + implements $RegistrationStateCopyWith<$Res> { + factory _$$RegistrationStateImplCopyWith(_$RegistrationStateImpl value, + $Res Function(_$RegistrationStateImpl) then) = __$$RegistrationStateImplCopyWithImpl<$Res>; - @override @useResult $Res call({UserRegistrationSheet sheet}); @@ -78,9 +81,12 @@ abstract class _$$RegistrationStateImplCopyWith<$Res> implements $RegistrationSt } /// @nodoc -class __$$RegistrationStateImplCopyWithImpl<$Res> extends _$RegistrationStateCopyWithImpl<$Res, _$RegistrationStateImpl> +class __$$RegistrationStateImplCopyWithImpl<$Res> + extends _$RegistrationStateCopyWithImpl<$Res, _$RegistrationStateImpl> implements _$$RegistrationStateImplCopyWith<$Res> { - __$$RegistrationStateImplCopyWithImpl(_$RegistrationStateImpl _value, $Res Function(_$RegistrationStateImpl) _then) : super(_value, _then); + __$$RegistrationStateImplCopyWithImpl(_$RegistrationStateImpl _value, + $Res Function(_$RegistrationStateImpl) _then) + : super(_value, _then); @pragma('vm:prefer-inline') @override @@ -112,7 +118,9 @@ class _$RegistrationStateImpl implements _RegistrationState { @override bool operator ==(Object other) { return identical(this, other) || - (other.runtimeType == runtimeType && other is _$RegistrationStateImpl && (identical(other.sheet, sheet) || other.sheet == sheet)); + (other.runtimeType == runtimeType && + other is _$RegistrationStateImpl && + (identical(other.sheet, sheet) || other.sheet == sheet)); } @override @@ -121,16 +129,19 @@ class _$RegistrationStateImpl implements _RegistrationState { @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => __$$RegistrationStateImplCopyWithImpl<_$RegistrationStateImpl>(this, _$identity); + _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => + __$$RegistrationStateImplCopyWithImpl<_$RegistrationStateImpl>( + this, _$identity); } abstract class _RegistrationState implements RegistrationState { - const factory _RegistrationState({required final UserRegistrationSheet sheet}) = _$RegistrationStateImpl; + const factory _RegistrationState( + {required final UserRegistrationSheet sheet}) = _$RegistrationStateImpl; @override UserRegistrationSheet get sheet; - @override @JsonKey(ignore: true) - _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => throw _privateConstructorUsedError; + _$$RegistrationStateImplCopyWith<_$RegistrationStateImpl> get copyWith => + throw _privateConstructorUsedError; } diff --git a/lib/features/registration/services/registration_service.g.dart b/lib/features/registration/services/registration_service.g.dart index d37f0f3..9820fd3 100644 --- a/lib/features/registration/services/registration_service.g.dart +++ b/lib/features/registration/services/registration_service.g.dart @@ -19,28 +19,30 @@ class _RegistrationService implements RegistrationService { String? baseUrl; @override - Future> register({required Map sheet}) async { + Future> register( + {required Map sheet}) async { final _extra = {}; final queryParameters = {}; final _headers = {}; final _data = {}; _data.addAll(sheet); - final _result = await _dio.fetch>(_setStreamType>(Options( + 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, - )))); + .compose( + _dio.options, + '/api/register', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = _result.data!.cast(); return _value; } @@ -51,22 +53,23 @@ class _RegistrationService implements RegistrationService { final queryParameters = {r'user_address': query}; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio + .fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/location_by_address', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/location_by_address', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = LocationModel.fromJson(_result.data!); return _value; } @@ -83,28 +86,31 @@ class _RegistrationService implements RegistrationService { }; final _headers = {}; const Map? _data = null; - final _result = await _dio.fetch>(_setStreamType(Options( + final _result = await _dio + .fetch>(_setStreamType(Options( method: 'GET', headers: _headers, extra: _extra, ) - .compose( - _dio.options, - '/api/location_by_coordinate', - queryParameters: queryParameters, - data: _data, - ) - .copyWith( - baseUrl: _combineBaseUrls( - _dio.options.baseUrl, - baseUrl, - )))); + .compose( + _dio.options, + '/api/location_by_coordinate', + queryParameters: queryParameters, + data: _data, + ) + .copyWith( + baseUrl: _combineBaseUrls( + _dio.options.baseUrl, + baseUrl, + )))); final _value = LocationModel.fromJson(_result.data!); return _value; } RequestOptions _setStreamType(RequestOptions requestOptions) { - if (T != dynamic && !(requestOptions.responseType == ResponseType.bytes || requestOptions.responseType == ResponseType.stream)) { + if (T != dynamic && + !(requestOptions.responseType == ResponseType.bytes || + requestOptions.responseType == ResponseType.stream)) { if (T == String) { requestOptions.responseType = ResponseType.plain; } else { diff --git a/lib/presentation/profile/my_profile_screen/my_profile_screen.dart b/lib/presentation/profile/my_profile_screen/my_profile_screen.dart index 3aa1f64..d10b70a 100644 --- a/lib/presentation/profile/my_profile_screen/my_profile_screen.dart +++ b/lib/presentation/profile/my_profile_screen/my_profile_screen.dart @@ -2,7 +2,7 @@ import 'dart:convert'; import 'dart:math'; import 'package:cached_network_image/cached_network_image.dart'; -import 'package:carousel_slider/carousel_slider.dart'; +import 'package:carousel_slider_plus/carousel_slider_plus.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'; diff --git a/lib/theme/theme_helper.dart b/lib/theme/theme_helper.dart index e202a86..b33d056 100644 --- a/lib/theme/theme_helper.dart +++ b/lib/theme/theme_helper.dart @@ -91,10 +91,14 @@ class ThemeHelper { colorScheme: colorScheme, scaffoldBackgroundColor: colorScheme.onPrimary, appBarTheme: AppBarTheme( + scrolledUnderElevation: 0, + elevation: 0, systemOverlayStyle: SystemUiOverlayStyle( statusBarIconBrightness: Brightness.dark, statusBarBrightness: Brightness.light, systemNavigationBarColor: Colors.white, + statusBarColor: Colors.white, + systemNavigationBarIconBrightness: Brightness.dark, ), ), outlinedButtonTheme: OutlinedButtonThemeData( diff --git a/pubspec.yaml b/pubspec.yaml index 21520bf..5939ba1 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -27,7 +27,7 @@ dependencies: path_provider: ^2.1.3 fl_chart: ^0.68.0 flutter_spinkit: ^5.2.1 - carousel_slider: ^4.2.1 + carousel_slider_plus: ^7.0.0 flutter_form_builder: ^9.3.0 image_picker: ^1.1.2 flutter_typeahead: ^5.2.0 @@ -36,7 +36,7 @@ dependencies: retrofit: ^4.1.0 get_it: ^7.7.0 dio: ^5.5.0 - dart_pusher_channels: ^1.2.2 + dart_pusher_channels: ^1.2.2+1 photo_view: ^0.15.0 dismissible_page: ^1.0.2 url_launcher: ^6.3.0 @@ -45,7 +45,7 @@ dependencies: badges: ^3.1.2 google_fonts: ^6.2.1 location: ^7.0.0 - syncfusion_flutter_charts: ^26.1.42 + syncfusion_flutter_charts: ^26.2.8 table_calendar: ^3.1.2 dev_dependencies: -- 2.49.1 From a2ea8dd2ba25cceea6b9f7536256b045d7697faf Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 8 Aug 2024 12:22:15 +0300 Subject: [PATCH 104/110] feat(calendar): Diet days marked in calendar, diet preview page added --- .../calendar/models/calendar_entry_model.dart | 4 + .../calendar/models/calendar_model.dart | 1 + .../models/calendar_model.freezed.dart | 51 +++++- .../calendar/models/calendar_model.g.dart | 5 + .../presentation/pages/calendar_screen.dart | 163 +++++++----------- .../pages/diary_recommendations_scree.dart | 91 ++++++++++ .../presentation/pages/diary_screen.dart | 5 - 7 files changed, 205 insertions(+), 115 deletions(-) create mode 100644 lib/features/diary/presentation/pages/diary_recommendations_scree.dart diff --git a/lib/features/calendar/models/calendar_entry_model.dart b/lib/features/calendar/models/calendar_entry_model.dart index e0ce0d5..0973f97 100644 --- a/lib/features/calendar/models/calendar_entry_model.dart +++ b/lib/features/calendar/models/calendar_entry_model.dart @@ -5,14 +5,18 @@ class CalendarEntryModel { String? date; String? status; String id; + bool is_current_day_included_in_the_chosen_diet_progression; CalendarEntryModel({ this.date, this.status, required this.id, + required this.is_current_day_included_in_the_chosen_diet_progression, }) { date = date; status = status; id = id; + is_current_day_included_in_the_chosen_diet_progression = + is_current_day_included_in_the_chosen_diet_progression; } } diff --git a/lib/features/calendar/models/calendar_model.dart b/lib/features/calendar/models/calendar_model.dart index c13d5c5..65fc834 100644 --- a/lib/features/calendar/models/calendar_model.dart +++ b/lib/features/calendar/models/calendar_model.dart @@ -7,6 +7,7 @@ part 'calendar_model.g.dart'; class CalendarModel with _$CalendarModel { const factory CalendarModel({ required String date, + required bool is_current_day_included_in_the_chosen_diet_progression, Object? diary, }) = _CalendarModel; diff --git a/lib/features/calendar/models/calendar_model.freezed.dart b/lib/features/calendar/models/calendar_model.freezed.dart index fd8f7ea..5e47f84 100644 --- a/lib/features/calendar/models/calendar_model.freezed.dart +++ b/lib/features/calendar/models/calendar_model.freezed.dart @@ -21,6 +21,8 @@ CalendarModel _$CalendarModelFromJson(Map json) { /// @nodoc mixin _$CalendarModel { String get date => throw _privateConstructorUsedError; + bool get is_current_day_included_in_the_chosen_diet_progression => + throw _privateConstructorUsedError; Object? get diary => throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @@ -35,7 +37,10 @@ abstract class $CalendarModelCopyWith<$Res> { CalendarModel value, $Res Function(CalendarModel) then) = _$CalendarModelCopyWithImpl<$Res, CalendarModel>; @useResult - $Res call({String date, Object? diary}); + $Res call( + {String date, + bool is_current_day_included_in_the_chosen_diet_progression, + Object? diary}); } /// @nodoc @@ -52,6 +57,7 @@ class _$CalendarModelCopyWithImpl<$Res, $Val extends CalendarModel> @override $Res call({ Object? date = null, + Object? is_current_day_included_in_the_chosen_diet_progression = null, Object? diary = freezed, }) { return _then(_value.copyWith( @@ -59,6 +65,11 @@ class _$CalendarModelCopyWithImpl<$Res, $Val extends CalendarModel> ? _value.date : date // ignore: cast_nullable_to_non_nullable as String, + is_current_day_included_in_the_chosen_diet_progression: null == + is_current_day_included_in_the_chosen_diet_progression + ? _value.is_current_day_included_in_the_chosen_diet_progression + : is_current_day_included_in_the_chosen_diet_progression // ignore: cast_nullable_to_non_nullable + as bool, diary: freezed == diary ? _value.diary : diary, ) as $Val); } @@ -72,7 +83,10 @@ abstract class _$$CalendarModelImplCopyWith<$Res> __$$CalendarModelImplCopyWithImpl<$Res>; @override @useResult - $Res call({String date, Object? diary}); + $Res call( + {String date, + bool is_current_day_included_in_the_chosen_diet_progression, + Object? diary}); } /// @nodoc @@ -87,6 +101,7 @@ class __$$CalendarModelImplCopyWithImpl<$Res> @override $Res call({ Object? date = null, + Object? is_current_day_included_in_the_chosen_diet_progression = null, Object? diary = freezed, }) { return _then(_$CalendarModelImpl( @@ -94,6 +109,11 @@ class __$$CalendarModelImplCopyWithImpl<$Res> ? _value.date : date // ignore: cast_nullable_to_non_nullable as String, + is_current_day_included_in_the_chosen_diet_progression: null == + is_current_day_included_in_the_chosen_diet_progression + ? _value.is_current_day_included_in_the_chosen_diet_progression + : is_current_day_included_in_the_chosen_diet_progression // ignore: cast_nullable_to_non_nullable + as bool, diary: freezed == diary ? _value.diary : diary, )); } @@ -102,7 +122,10 @@ class __$$CalendarModelImplCopyWithImpl<$Res> /// @nodoc @JsonSerializable() class _$CalendarModelImpl implements _CalendarModel { - const _$CalendarModelImpl({required this.date, this.diary}); + const _$CalendarModelImpl( + {required this.date, + required this.is_current_day_included_in_the_chosen_diet_progression, + this.diary}); factory _$CalendarModelImpl.fromJson(Map json) => _$$CalendarModelImplFromJson(json); @@ -110,11 +133,13 @@ class _$CalendarModelImpl implements _CalendarModel { @override final String date; @override + final bool is_current_day_included_in_the_chosen_diet_progression; + @override final Object? diary; @override String toString() { - return 'CalendarModel(date: $date, diary: $diary)'; + return 'CalendarModel(date: $date, is_current_day_included_in_the_chosen_diet_progression: $is_current_day_included_in_the_chosen_diet_progression, diary: $diary)'; } @override @@ -123,13 +148,22 @@ class _$CalendarModelImpl implements _CalendarModel { (other.runtimeType == runtimeType && other is _$CalendarModelImpl && (identical(other.date, date) || other.date == date) && + (identical( + other + .is_current_day_included_in_the_chosen_diet_progression, + is_current_day_included_in_the_chosen_diet_progression) || + other.is_current_day_included_in_the_chosen_diet_progression == + is_current_day_included_in_the_chosen_diet_progression) && const DeepCollectionEquality().equals(other.diary, diary)); } @JsonKey(ignore: true) @override int get hashCode => Object.hash( - runtimeType, date, const DeepCollectionEquality().hash(diary)); + runtimeType, + date, + is_current_day_included_in_the_chosen_diet_progression, + const DeepCollectionEquality().hash(diary)); @JsonKey(ignore: true) @override @@ -147,7 +181,10 @@ class _$CalendarModelImpl implements _CalendarModel { abstract class _CalendarModel implements CalendarModel { const factory _CalendarModel( - {required final String date, final Object? diary}) = _$CalendarModelImpl; + {required final String date, + required final bool + is_current_day_included_in_the_chosen_diet_progression, + final Object? diary}) = _$CalendarModelImpl; factory _CalendarModel.fromJson(Map json) = _$CalendarModelImpl.fromJson; @@ -155,6 +192,8 @@ abstract class _CalendarModel implements CalendarModel { @override String get date; @override + bool get is_current_day_included_in_the_chosen_diet_progression; + @override Object? get diary; @override @JsonKey(ignore: true) diff --git a/lib/features/calendar/models/calendar_model.g.dart b/lib/features/calendar/models/calendar_model.g.dart index c12dd96..65fd006 100644 --- a/lib/features/calendar/models/calendar_model.g.dart +++ b/lib/features/calendar/models/calendar_model.g.dart @@ -9,11 +9,16 @@ part of 'calendar_model.dart'; _$CalendarModelImpl _$$CalendarModelImplFromJson(Map json) => _$CalendarModelImpl( date: json['date'] as String, + is_current_day_included_in_the_chosen_diet_progression: + json['is_current_day_included_in_the_chosen_diet_progression'] + as bool, diary: json['diary'], ); Map _$$CalendarModelImplToJson(_$CalendarModelImpl instance) => { 'date': instance.date, + 'is_current_day_included_in_the_chosen_diet_progression': + instance.is_current_day_included_in_the_chosen_diet_progression, 'diary': instance.diary, }; diff --git a/lib/features/calendar/presentation/pages/calendar_screen.dart b/lib/features/calendar/presentation/pages/calendar_screen.dart index 320ad2c..bcd365c 100644 --- a/lib/features/calendar/presentation/pages/calendar_screen.dart +++ b/lib/features/calendar/presentation/pages/calendar_screen.dart @@ -102,7 +102,10 @@ class CalendarScreen extends StatelessWidget { padding: EdgeInsets.all(8), decoration: BoxDecoration( borderRadius: BorderRadiusStyle.circleBorder8, - color: getBackgroundColor(diary['state']), + color: state.calendarList[index] + .is_current_day_included_in_the_chosen_diet_progression + ? Color.fromRGBO(59, 130, 246, .2) + : Color.fromRGBO(126, 136, 151, .1), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, @@ -117,57 +120,24 @@ class CalendarScreen extends StatelessWidget { style: theme.textTheme.titleMedium, ), SizedBox(height: 2.v), - if (diary['state'] != null) - Row(children: [ - Container( - padding: EdgeInsets.all( - 4.0), // Отступы внутри контейнера - decoration: BoxDecoration( - color: diary['state'] == 'finished' - ? Color.fromRGBO(1, 154, 62, 1) - : Color.fromRGBO(154, 74, 1, 1), - borderRadius: BorderRadius.circular( - 24.0), // Закругленные углы - ), - child: Text( - _getStateText(diary['state'] ?? ''), - style: CustomTextStyles - .titleSmallBold, // Предполагается, что текст белый - ), + if (state.calendarList[index] + .is_current_day_included_in_the_chosen_diet_progression) + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(13, 110, 253, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы ), - SizedBox(width: 4), - if (diary['state'] == 'started') - Container( - padding: EdgeInsets.all( - 4.0), // Отступы внутри контейнера - decoration: BoxDecoration( - color: Color.fromRGBO(13, 110, 253, 1), - borderRadius: BorderRadius.circular( - 24.0), // Закругленные углы - ), - child: Text( - 'Заполнить отчет', - style: CustomTextStyles - .titleSmallBold, // Предполагается, что текст белый - ), - ), - if (diary['state'] == 'finished') - Container( - padding: EdgeInsets.all( - 4.0), // Отступы внутри контейнера - decoration: BoxDecoration( - color: Color.fromRGBO(13, 110, 253, 1), - borderRadius: BorderRadius.circular( - 24.0), // Закругленные углы - ), - child: Text( - 'Изменить отчет', - style: CustomTextStyles - .titleSmallBold, // Предполагается, что текст белый - ), - ), - ]), - if (state.calendarList[index].diary is List) + child: Text( + 'Посмотреть диету на день', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + if (!state.calendarList[index] + .is_current_day_included_in_the_chosen_diet_progression) Container( padding: EdgeInsets.all( 4.0), // Отступы внутри контейнера @@ -191,6 +161,7 @@ class CalendarScreen extends StatelessWidget { ); } else { diary = state.calendarList[index].diary as Map; + print(state.calendarList[index]); return InkWell( borderRadius: BorderRadiusStyle.circleBorder8, onTap: () => GoRouter.of(context).go( @@ -216,71 +187,55 @@ class CalendarScreen extends StatelessWidget { style: theme.textTheme.titleMedium, ), SizedBox(height: 2.v), - if (diary['state'] != null) - Row(children: [ - Container( - padding: EdgeInsets.all( - 4.0), // Отступы внутри контейнера - decoration: BoxDecoration( - color: diary['state'] == 'finished' - ? Color.fromRGBO(1, 154, 62, 1) - : Color.fromRGBO(154, 74, 1, 1), - borderRadius: BorderRadius.circular( - 24.0), // Закругленные углы - ), - child: Text( - _getStateText(diary['state'] ?? ''), - style: CustomTextStyles - .titleSmallBold, // Предполагается, что текст белый - ), - ), - SizedBox(width: 4), - if (diary['state'] == 'started') - Container( - padding: EdgeInsets.all( - 4.0), // Отступы внутри контейнера - decoration: BoxDecoration( - color: Color.fromRGBO(13, 110, 253, 1), - borderRadius: BorderRadius.circular( - 24.0), // Закругленные углы - ), - child: Text( - 'Заполнить отчет', - style: CustomTextStyles - .titleSmallBold, // Предполагается, что текст белый - ), - ), - if (diary['state'] == 'finished') - Container( - padding: EdgeInsets.all( - 4.0), // Отступы внутри контейнера - decoration: BoxDecoration( - color: Color.fromRGBO(13, 110, 253, 1), - borderRadius: BorderRadius.circular( - 24.0), // Закругленные углы - ), - child: Text( - 'Изменить отчет', - style: CustomTextStyles - .titleSmallBold, // Предполагается, что текст белый - ), - ), - ]), - if (state.calendarList[index].diary is List) + Row(children: [ Container( padding: EdgeInsets.all( 4.0), // Отступы внутри контейнера decoration: BoxDecoration( - color: Color.fromRGBO(108, 117, 125, 1), + color: diary['state'] == 'finished' + ? Color.fromRGBO(1, 154, 62, 1) + : Color.fromRGBO(154, 74, 1, 1), borderRadius: BorderRadius.circular( 24.0), // Закругленные углы ), child: Text( - 'Cкоро', + _getStateText(diary['state'] ?? ''), style: CustomTextStyles .titleSmallBold, // Предполагается, что текст белый ), ), + SizedBox(width: 4), + if (diary['state'] == 'started') + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(13, 110, 253, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Заполнить отчет', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + if (diary['state'] == 'finished') + Container( + padding: EdgeInsets.all( + 4.0), // Отступы внутри контейнера + decoration: BoxDecoration( + color: Color.fromRGBO(13, 110, 253, 1), + borderRadius: BorderRadius.circular( + 24.0), // Закругленные углы + ), + child: Text( + 'Изменить отчет', + style: CustomTextStyles + .titleSmallBold, // Предполагается, что текст белый + ), + ), + ]), ], ), ), diff --git a/lib/features/diary/presentation/pages/diary_recommendations_scree.dart b/lib/features/diary/presentation/pages/diary_recommendations_scree.dart new file mode 100644 index 0000000..6c5dea7 --- /dev/null +++ b/lib/features/diary/presentation/pages/diary_recommendations_scree.dart @@ -0,0 +1,91 @@ +// ignore_for_file: unused_local_variable + +import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.dart'; +import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; +import 'package:eatvio_app/core/app_export.dart'; + +import 'package:flutter/material.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; + +// ignore: must_be_immutable +class DiaryRecommendationsScreen extends StatelessWidget { + final String? diary_recommendationsID; + + const DiaryRecommendationsScreen({ + this.diary_recommendationsID, + super.key, + }); + + Widget build(BuildContext context) { + if (diary_recommendationsID != "0") { + context.read().add(LoadDiaryById(diary_recommendationsID)); + } + return BlocBuilder( + builder: (context, state) { + if (state is DiaryStateLoaded) { + return _buildDiaryRecommendations(context, state); + } else if (state is DiaryStateLoading) { + return Scaffold( + body: Center( + child: CupertinoActivityIndicator(), + ), + ); + } else if (state is DiaryStateError) { + return Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: Center( + child: Text(state.errorMessage), + ), + ), + ); + } else + return Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: Center( + child: Text("Неопределенная ошибка"), + ), + ), + ); + }, + ); + } + + Widget _buildDiaryRecommendations( + BuildContext context, DiaryStateLoaded state) { + return Stack( + alignment: Alignment.bottomCenter, + children: [ + FormBuilder( + child: Scaffold( + appBar: AppBar( + toolbarHeight: 0, + automaticallyImplyLeading: false, + ), + backgroundColor: Color.fromARGB(255, 240, 242, 245), + resizeToAvoidBottomInset: true, + body: SizedBox( + width: double.maxFinite, + child: Column( + children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.only(bottom: 5.v), + child: Column( + children: [], + ), + ), + ), + ), + ], + ), + ), + ), + ), + ], + ); + } +} diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index 047dc64..2b9cf6e 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -250,11 +250,6 @@ class DiaryScreen extends StatelessWidget { style: CustomTextStyles.titleMediumBlack, ), ), - SizedBox(height: 2.v), - Text( - state.diary.date.toString(), - style: CustomTextStyles.bodyMediumBluegray800, - ), ], ), ), -- 2.49.1 From 1e8b94c6f632b73badc7e9e2bd2230158008edc2 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 8 Aug 2024 13:34:35 +0300 Subject: [PATCH 105/110] feat(diary): new layouts for diary --- .../diary/presentation/bloc/diary_bloc.dart | 6 +- .../diary/presentation/bloc/diary_state.dart | 3 +- .../bloc/diary_state.freezed.dart | 108 +++++++---- .../presentation/pages/diary_screen.dart | 171 ++++++++---------- 4 files changed, 151 insertions(+), 137 deletions(-) diff --git a/lib/features/diary/presentation/bloc/diary_bloc.dart b/lib/features/diary/presentation/bloc/diary_bloc.dart index 379aaea..7803117 100644 --- a/lib/features/diary/presentation/bloc/diary_bloc.dart +++ b/lib/features/diary/presentation/bloc/diary_bloc.dart @@ -110,7 +110,8 @@ class DiaryBloc extends Bloc { portionList: portionList, portionController: portionList[0], mealList: mealList, - chartData: chartDataCounted, + chartData: chartData, + chartDataCounted: chartDataCounted, selectedMood: currentMeal.mood, selectedSatiety: currentMeal.satiety, wakeupController: TimeOfDay.now(), @@ -200,7 +201,8 @@ class DiaryBloc extends Bloc { portionList: portionList, portionController: portionList[0], mealList: mealList, - chartData: chartDataCounted, + chartData: chartData, + chartDataCounted: chartDataCounted, selectedMood: currentMeal.mood, selectedSatiety: currentMeal.satiety, wakeupController: TimeOfDay.now(), diff --git a/lib/features/diary/presentation/bloc/diary_state.dart b/lib/features/diary/presentation/bloc/diary_state.dart index 0725991..b0aebfb 100644 --- a/lib/features/diary/presentation/bloc/diary_state.dart +++ b/lib/features/diary/presentation/bloc/diary_state.dart @@ -26,6 +26,7 @@ abstract class DiaryState with _$DiaryState { required List mealList, required List portionList, required List autocompleteList, + required Map chartData, required Meal currentMeal, required SelectionPopupModel portionController, required TimeOfDay wakeupController, @@ -45,7 +46,7 @@ abstract class DiaryState with _$DiaryState { required bool moodExpanded, required bool isLoading, required bool isAdded, - List? chartData, + List? chartDataCounted, }) = DiaryStateLoaded; const factory DiaryState.error({ diff --git a/lib/features/diary/presentation/bloc/diary_state.freezed.dart b/lib/features/diary/presentation/bloc/diary_state.freezed.dart index 24dbb0a..5a9bbc1 100644 --- a/lib/features/diary/presentation/bloc/diary_state.freezed.dart +++ b/lib/features/diary/presentation/bloc/diary_state.freezed.dart @@ -29,6 +29,7 @@ mixin _$DiaryState { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -48,7 +49,7 @@ mixin _$DiaryState { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData) + List? chartDataCounted) loaded, required TResult Function(String errorMessage) error, }) => @@ -66,6 +67,7 @@ mixin _$DiaryState { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -85,7 +87,7 @@ mixin _$DiaryState { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData)? + List? chartDataCounted)? loaded, TResult? Function(String errorMessage)? error, }) => @@ -103,6 +105,7 @@ mixin _$DiaryState { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -122,7 +125,7 @@ mixin _$DiaryState { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData)? + List? chartDataCounted)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), @@ -222,6 +225,7 @@ class _$DiaryStateImpl implements _DiaryState { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -241,7 +245,7 @@ class _$DiaryStateImpl implements _DiaryState { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData) + List? chartDataCounted) loaded, required TResult Function(String errorMessage) error, }) { @@ -262,6 +266,7 @@ class _$DiaryStateImpl implements _DiaryState { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -281,7 +286,7 @@ class _$DiaryStateImpl implements _DiaryState { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData)? + List? chartDataCounted)? loaded, TResult? Function(String errorMessage)? error, }) { @@ -302,6 +307,7 @@ class _$DiaryStateImpl implements _DiaryState { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -321,7 +327,7 @@ class _$DiaryStateImpl implements _DiaryState { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData)? + List? chartDataCounted)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), @@ -450,6 +456,7 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -469,7 +476,7 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData) + List? chartDataCounted) loaded, required TResult Function(String errorMessage) error, }) { @@ -490,6 +497,7 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -509,7 +517,7 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData)? + List? chartDataCounted)? loaded, TResult? Function(String errorMessage)? error, }) { @@ -530,6 +538,7 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -549,7 +558,7 @@ class _$DiaryStateLoadingImpl implements DiaryStateLoading { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData)? + List? chartDataCounted)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), @@ -622,6 +631,7 @@ abstract class _$$DiaryStateLoadedImplCopyWith<$Res> { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -641,7 +651,7 @@ abstract class _$$DiaryStateLoadedImplCopyWith<$Res> { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData}); + List? chartDataCounted}); $DiaryModelCopyWith<$Res> get diary; $MealCopyWith<$Res> get currentMeal; @@ -667,6 +677,7 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> Object? mealList = null, Object? portionList = null, Object? autocompleteList = null, + Object? chartData = null, Object? currentMeal = null, Object? portionController = null, Object? wakeupController = null, @@ -686,7 +697,7 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> Object? moodExpanded = null, Object? isLoading = null, Object? isAdded = null, - Object? chartData = freezed, + Object? chartDataCounted = freezed, }) { return _then(_$DiaryStateLoadedImpl( diary: null == diary @@ -721,6 +732,10 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> ? _value._autocompleteList : autocompleteList // ignore: cast_nullable_to_non_nullable as List, + chartData: null == chartData + ? _value._chartData + : chartData // ignore: cast_nullable_to_non_nullable + as Map, currentMeal: null == currentMeal ? _value.currentMeal : currentMeal // ignore: cast_nullable_to_non_nullable @@ -797,9 +812,9 @@ class __$$DiaryStateLoadedImplCopyWithImpl<$Res> ? _value.isAdded : isAdded // ignore: cast_nullable_to_non_nullable as bool, - chartData: freezed == chartData - ? _value._chartData - : chartData // ignore: cast_nullable_to_non_nullable + chartDataCounted: freezed == chartDataCounted + ? _value._chartDataCounted + : chartDataCounted // ignore: cast_nullable_to_non_nullable as List?, )); } @@ -842,6 +857,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { required final List mealList, required final List portionList, required final List autocompleteList, + required final Map chartData, required this.currentMeal, required this.portionController, required this.wakeupController, @@ -861,14 +877,15 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { required this.moodExpanded, required this.isLoading, required this.isAdded, - final List? chartData}) + final List? chartDataCounted}) : _recommendedChartValues = recommendedChartValues, _consumedChartValues = consumedChartValues, _portions = portions, _mealList = mealList, _portionList = portionList, _autocompleteList = autocompleteList, - _chartData = chartData; + _chartData = chartData, + _chartDataCounted = chartDataCounted; @override final DiaryModel diary; @@ -925,6 +942,14 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { return EqualUnmodifiableListView(_autocompleteList); } + final Map _chartData; + @override + Map get chartData { + if (_chartData is EqualUnmodifiableMapView) return _chartData; + // ignore: implicit_dynamic_type + return EqualUnmodifiableMapView(_chartData); + } + @override final Meal currentMeal; @override @@ -963,19 +988,20 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { final bool isLoading; @override final bool isAdded; - final List? _chartData; + final List? _chartDataCounted; @override - List? get chartData { - final value = _chartData; + List? get chartDataCounted { + final value = _chartDataCounted; if (value == null) return null; - if (_chartData is EqualUnmodifiableListView) return _chartData; + if (_chartDataCounted is EqualUnmodifiableListView) + return _chartDataCounted; // ignore: implicit_dynamic_type return EqualUnmodifiableListView(value); } @override String toString() { - return 'DiaryState.loaded(diary: $diary, diaryDate: $diaryDate, recommendedChartValues: $recommendedChartValues, consumedChartValues: $consumedChartValues, portions: $portions, mealList: $mealList, portionList: $portionList, autocompleteList: $autocompleteList, currentMeal: $currentMeal, portionController: $portionController, wakeupController: $wakeupController, retireController: $retireController, mealTimeController: $mealTimeController, commentController: $commentController, product_nameController: $product_nameController, productQuantityController: $productQuantityController, caloriesController: $caloriesController, fatsController: $fatsController, proteinsController: $proteinsController, carbsController: $carbsController, selectedMood: $selectedMood, selectedSatiety: $selectedSatiety, wakeupExpanded: $wakeupExpanded, moderationExpanded: $moderationExpanded, moodExpanded: $moodExpanded, isLoading: $isLoading, isAdded: $isAdded, chartData: $chartData)'; + return 'DiaryState.loaded(diary: $diary, diaryDate: $diaryDate, recommendedChartValues: $recommendedChartValues, consumedChartValues: $consumedChartValues, portions: $portions, mealList: $mealList, portionList: $portionList, autocompleteList: $autocompleteList, chartData: $chartData, currentMeal: $currentMeal, portionController: $portionController, wakeupController: $wakeupController, retireController: $retireController, mealTimeController: $mealTimeController, commentController: $commentController, product_nameController: $product_nameController, productQuantityController: $productQuantityController, caloriesController: $caloriesController, fatsController: $fatsController, proteinsController: $proteinsController, carbsController: $carbsController, selectedMood: $selectedMood, selectedSatiety: $selectedSatiety, wakeupExpanded: $wakeupExpanded, moderationExpanded: $moderationExpanded, moodExpanded: $moodExpanded, isLoading: $isLoading, isAdded: $isAdded, chartDataCounted: $chartDataCounted)'; } @override @@ -996,6 +1022,8 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { .equals(other._portionList, _portionList) && const DeepCollectionEquality() .equals(other._autocompleteList, _autocompleteList) && + const DeepCollectionEquality() + .equals(other._chartData, _chartData) && (identical(other.currentMeal, currentMeal) || other.currentMeal == currentMeal) && (identical(other.portionController, portionController) || @@ -1035,7 +1063,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { other.isLoading == isLoading) && (identical(other.isAdded, isAdded) || other.isAdded == isAdded) && const DeepCollectionEquality() - .equals(other._chartData, _chartData)); + .equals(other._chartDataCounted, _chartDataCounted)); } @override @@ -1049,6 +1077,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { const DeepCollectionEquality().hash(_mealList), const DeepCollectionEquality().hash(_portionList), const DeepCollectionEquality().hash(_autocompleteList), + const DeepCollectionEquality().hash(_chartData), currentMeal, portionController, wakeupController, @@ -1068,7 +1097,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { moodExpanded, isLoading, isAdded, - const DeepCollectionEquality().hash(_chartData) + const DeepCollectionEquality().hash(_chartDataCounted) ]); @JsonKey(ignore: true) @@ -1092,6 +1121,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -1111,7 +1141,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData) + List? chartDataCounted) loaded, required TResult Function(String errorMessage) error, }) { @@ -1124,6 +1154,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { mealList, portionList, autocompleteList, + chartData, currentMeal, portionController, wakeupController, @@ -1143,7 +1174,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { moodExpanded, isLoading, isAdded, - chartData); + chartDataCounted); } @override @@ -1160,6 +1191,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -1179,7 +1211,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData)? + List? chartDataCounted)? loaded, TResult? Function(String errorMessage)? error, }) { @@ -1192,6 +1224,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { mealList, portionList, autocompleteList, + chartData, currentMeal, portionController, wakeupController, @@ -1211,7 +1244,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { moodExpanded, isLoading, isAdded, - chartData); + chartDataCounted); } @override @@ -1228,6 +1261,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -1247,7 +1281,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData)? + List? chartDataCounted)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), @@ -1262,6 +1296,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { mealList, portionList, autocompleteList, + chartData, currentMeal, portionController, wakeupController, @@ -1281,7 +1316,7 @@ class _$DiaryStateLoadedImpl implements DiaryStateLoaded { moodExpanded, isLoading, isAdded, - chartData); + chartDataCounted); } return orElse(); } @@ -1334,6 +1369,7 @@ abstract class DiaryStateLoaded implements DiaryState { required final List mealList, required final List portionList, required final List autocompleteList, + required final Map chartData, required final Meal currentMeal, required final SelectionPopupModel portionController, required final TimeOfDay wakeupController, @@ -1353,7 +1389,7 @@ abstract class DiaryStateLoaded implements DiaryState { required final bool moodExpanded, required final bool isLoading, required final bool isAdded, - final List? chartData}) = _$DiaryStateLoadedImpl; + final List? chartDataCounted}) = _$DiaryStateLoadedImpl; DiaryModel get diary; String? get diaryDate; @@ -1363,6 +1399,7 @@ abstract class DiaryStateLoaded implements DiaryState { List get mealList; List get portionList; List get autocompleteList; + Map get chartData; Meal get currentMeal; SelectionPopupModel get portionController; TimeOfDay get wakeupController; @@ -1382,7 +1419,7 @@ abstract class DiaryStateLoaded implements DiaryState { bool get moodExpanded; bool get isLoading; bool get isAdded; - List? get chartData; + List? get chartDataCounted; @JsonKey(ignore: true) _$$DiaryStateLoadedImplCopyWith<_$DiaryStateLoadedImpl> get copyWith => throw _privateConstructorUsedError; @@ -1465,6 +1502,7 @@ class _$DiaryStateErrorImpl implements DiaryStateError { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -1484,7 +1522,7 @@ class _$DiaryStateErrorImpl implements DiaryStateError { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData) + List? chartDataCounted) loaded, required TResult Function(String errorMessage) error, }) { @@ -1505,6 +1543,7 @@ class _$DiaryStateErrorImpl implements DiaryStateError { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -1524,7 +1563,7 @@ class _$DiaryStateErrorImpl implements DiaryStateError { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData)? + List? chartDataCounted)? loaded, TResult? Function(String errorMessage)? error, }) { @@ -1545,6 +1584,7 @@ class _$DiaryStateErrorImpl implements DiaryStateError { List mealList, List portionList, List autocompleteList, + Map chartData, Meal currentMeal, SelectionPopupModel portionController, TimeOfDay wakeupController, @@ -1564,7 +1604,7 @@ class _$DiaryStateErrorImpl implements DiaryStateError { bool moodExpanded, bool isLoading, bool isAdded, - List? chartData)? + List? chartDataCounted)? loaded, TResult Function(String errorMessage)? error, required TResult orElse(), diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index 2b9cf6e..fc964c0 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -11,7 +11,6 @@ import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.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:flutter/material.dart'; @@ -91,16 +90,18 @@ class DiaryScreen extends StatelessWidget { child: Column( children: [ _buildHeaderRow(context, state), - SizedBox(height: 30.v), + SizedBox(height: 8.v), _buildWakupRetire(context, state), - SizedBox(height: 30.v), + SizedBox(height: 8.v), _buildMeal(context, state), - SizedBox(height: 20.v), + SizedBox(height: 8.v), _buildMood(context, state), - SizedBox(height: 20.v), + SizedBox(height: 8.v), _buildNutritionChart(context, state), - SizedBox(height: 30.v), - _buildComment(context, state), + SizedBox(height: 8.v), + // _buildComment(context, state), + // SizedBox(height: 8.v), + _buildEndDay(context), ], ), ), @@ -111,7 +112,6 @@ class DiaryScreen extends StatelessWidget { ), ), ), - _buildEndDay(context), ], ), ); @@ -119,30 +119,24 @@ class DiaryScreen extends StatelessWidget { _buildNutritionChart(BuildContext context, DiaryStateLoaded state) { return Container( - margin: EdgeInsets.symmetric(horizontal: 16.h, vertical: 16.h), padding: EdgeInsets.symmetric( horizontal: 24.h, vertical: 12.v, ), decoration: BoxDecoration( color: Colors.white, - borderRadius: const BorderRadius.all(Radius.circular(12)), - boxShadow: [ - BoxShadow( - color: Colors.grey.withOpacity(0.5), - spreadRadius: 2, - blurRadius: 5, - offset: Offset(0, 3), - ), - ], + borderRadius: const BorderRadius.all(Radius.circular(8)), ), child: Column( children: [ Text( - "График КБЖУ", + "Ваш КБЖУ", style: theme.textTheme.titleMedium, textAlign: TextAlign.center, ), + Text( + "от дневной суточной нормы", + ), Transform.rotate( angle: -1.5708, child: ClipRect( @@ -152,7 +146,7 @@ class DiaryScreen extends StatelessWidget { child: SfCircularChart( series: [ RadialBarSeries( - dataSource: state.chartData, + dataSource: state.chartDataCounted, xValueMapper: (NutritionData data, _) => data.category, yValueMapper: (NutritionData data, _) => data.nutrition, pointColorMapper: (NutritionData data, _) => data.color, @@ -167,23 +161,26 @@ class DiaryScreen extends StatelessWidget { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('Углеводы'), - Text('Жиры'), - Text('Белки'), - Text('Калории'), + Text(style: theme.textTheme.titleMedium, 'Углеводы'), + Text(style: theme.textTheme.titleMedium, 'Жиры'), + Text(style: theme.textTheme.titleMedium, 'Белки'), + Text(style: theme.textTheme.titleMedium, 'Калории'), ], ), Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( - '${state.chartData![3].nutrition.toStringAsFixed(0)}%'), // Калории + '${state.chartData['dailyNutritionIntake']['carbohydrates'].toStringAsFixed(1)} из ${state.chartData['dailyNutritionRecommendation']['carbohydrates'].toStringAsFixed(1)} грамм'), + SizedBox(height: 8.v), Text( - '${state.chartData![2].nutrition.toStringAsFixed(0)}%'), // Белки + '${state.chartData['dailyNutritionIntake']['fats'].toStringAsFixed(1)} из ${state.chartData['dailyNutritionRecommendation']['fats'].toStringAsFixed(1)} грамм'), + SizedBox(height: 8.v), Text( - '${state.chartData![1].nutrition.toStringAsFixed(0)}%'), // Жиры + '${state.chartData['dailyNutritionIntake']['proteins'].toStringAsFixed(1)} из ${state.chartData['dailyNutritionRecommendation']['proteins'].toStringAsFixed(1)} грамм'), + SizedBox(height: 8.v), Text( - '${state.chartData![0].nutrition.toStringAsFixed(0)}% '), // Углеводы + '${state.chartData['dailyNutritionIntake']['energy'].toStringAsFixed(1)} из ${state.chartData['dailyNutritionRecommendation']['energy'].toStringAsFixed(1)} Ккал'), ], ), ], @@ -194,18 +191,24 @@ class DiaryScreen extends StatelessWidget { } _buildEndDay(BuildContext context) { - return CustomOutlinedButton( - text: "Закончить день", - margin: EdgeInsets.only( - left: 16.h, - right: 16.h, - bottom: 16.v, + return Container( + height: 48, + width: MediaQuery.of(context).size.width, + padding: EdgeInsets.only(left: 4, right: 4), + child: FloatingActionButton.extended( + highlightElevation: 0, + elevation: 0, + focusElevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + backgroundColor: appTheme.blueA400, + onPressed: () => onFinishDayPressed, + label: Text( + 'Закончить день', + style: theme.textTheme.titleSmall, + ), ), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - decoration: BoxDecoration( - color: Colors.transparent, - ), - onPressed: onFinishDayPressed(context), ); } @@ -219,22 +222,13 @@ class DiaryScreen extends StatelessWidget { _buildHeaderRow(BuildContext context, DiaryStateLoaded state) { final day = state.diary.id; return Container( - margin: EdgeInsets.symmetric(horizontal: 16.h, vertical: 16.h), padding: EdgeInsets.symmetric( horizontal: 24.h, vertical: 12.v, ), decoration: BoxDecoration( color: Colors.white, - borderRadius: const BorderRadius.all(Radius.circular(12)), - boxShadow: [ - BoxShadow( - color: Colors.grey.withOpacity(0.5), - spreadRadius: 2, - blurRadius: 5, - offset: Offset(0, 3), - ), - ], + borderRadius: const BorderRadius.all(Radius.circular(8)), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, @@ -260,11 +254,24 @@ class DiaryScreen extends StatelessWidget { /// Section Widget _buildAddProduct(BuildContext context, DiaryState state) { - return CustomOutlinedButton( - text: "Добавить продукт", - margin: EdgeInsets.symmetric(horizontal: 10.h), - buttonStyle: CustomButtonStyles.outlinePrimaryTL15, - onPressed: addProduct(context), + return Container( + height: 48, + width: MediaQuery.of(context).size.width, + padding: EdgeInsets.only(left: 4, right: 4), + child: FloatingActionButton.extended( + highlightElevation: 0, + elevation: 0, + focusElevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + backgroundColor: appTheme.blueA400, + onPressed: () => addProduct, + label: Text( + 'Добавить продукт', + style: theme.textTheme.titleSmall, + ), + ), ); } @@ -354,22 +361,13 @@ class DiaryScreen extends StatelessWidget { state.autocompleteList.map((Product item) => item.name).toList(); FocusNode focusNodeName = FocusNode(); return Container( - margin: EdgeInsets.symmetric(horizontal: 16.h), padding: EdgeInsets.symmetric( horizontal: 24.h, vertical: 12.v, ), decoration: BoxDecoration( color: Colors.white, - borderRadius: const BorderRadius.all(Radius.circular(12)), - boxShadow: [ - BoxShadow( - color: Colors.grey.withOpacity(0.5), - spreadRadius: 2, - blurRadius: 5, - offset: Offset(0, 3), - ), - ], + borderRadius: const BorderRadius.all(Radius.circular(8)), ), child: Column( mainAxisSize: MainAxisSize.min, @@ -530,17 +528,17 @@ class DiaryScreen extends StatelessWidget { ), ), ), - SizedBox(height: 30.v), + SizedBox(height: 24.v), _buildAddProduct(context, state), - SizedBox(height: 30.v), + SizedBox(height: 24.v), ...state.portions .map((portion) => _buildProduct(context, portion)) .toList(), - SizedBox(height: 30.v), + SizedBox(height: 24.v), _buildCarousel(context, state), - SizedBox(height: 20.v), + SizedBox(height: 24.v), _buildAddPhoto(context, state), - SizedBox(height: 30.v), + SizedBox(height: 24.v), Text( "Ваша сытость после приёма пищи", style: CustomTextStyles.bodyMediumBlack900, @@ -736,7 +734,7 @@ class DiaryScreen extends StatelessWidget { return Text("Фото нет"); } else { return CarouselSlider( - options: CarouselOptions(height: 340.0), + options: CarouselOptions(height: 200.0), items: state.currentMeal.photos.map((photo) { return _buildPhoto(context, photo); }).toList(), @@ -846,22 +844,13 @@ class DiaryScreen extends StatelessWidget { _buildComment(BuildContext context, DiaryStateLoaded state) { return Container( - margin: EdgeInsets.symmetric(horizontal: 16.h), padding: EdgeInsets.symmetric( horizontal: 24.h, vertical: 12.v, ), decoration: BoxDecoration( color: Colors.white, - borderRadius: const BorderRadius.all(Radius.circular(12)), - boxShadow: [ - BoxShadow( - color: Colors.grey.withOpacity(0.5), - spreadRadius: 2, - blurRadius: 5, - offset: Offset(0, 3), - ), - ], + borderRadius: const BorderRadius.all(Radius.circular(8)), ), child: Column( mainAxisSize: MainAxisSize.min, @@ -890,22 +879,13 @@ class DiaryScreen extends StatelessWidget { _buildWakupRetire(BuildContext context, DiaryStateLoaded state) { return Container( - margin: EdgeInsets.symmetric(horizontal: 16.h), padding: EdgeInsets.symmetric( horizontal: 24.h, vertical: 12.v, ), decoration: BoxDecoration( color: Colors.white, - borderRadius: const BorderRadius.all(Radius.circular(12)), - boxShadow: [ - BoxShadow( - color: Colors.grey.withOpacity(0.5), - spreadRadius: 2, - blurRadius: 5, - offset: Offset(0, 3), - ), - ], + borderRadius: const BorderRadius.all(Radius.circular(8)), ), child: Column( children: [ @@ -1010,22 +990,13 @@ class DiaryScreen extends StatelessWidget { _buildMood(BuildContext context, DiaryStateLoaded state) { return Container( - margin: EdgeInsets.symmetric(horizontal: 16.h), padding: EdgeInsets.symmetric( horizontal: 24.h, vertical: 12.v, ), decoration: BoxDecoration( color: Colors.white, - borderRadius: const BorderRadius.all(Radius.circular(12)), - boxShadow: [ - BoxShadow( - color: Colors.grey.withOpacity(0.5), - spreadRadius: 2, - blurRadius: 5, - offset: Offset(0, 3), - ), - ], + borderRadius: const BorderRadius.all(Radius.circular(8)), ), child: Column( children: [ -- 2.49.1 From c3804bbb208f9ac99f07c18aa9c85309a34d504b Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 8 Aug 2024 13:35:10 +0300 Subject: [PATCH 106/110] feat(diary): new layouts for diary --- lib/features/diary/presentation/pages/diary_screen.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index fc964c0..ad4fb85 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -842,7 +842,7 @@ class DiaryScreen extends StatelessWidget { }; } - _buildComment(BuildContext context, DiaryStateLoaded state) { + /* _buildComment(BuildContext context, DiaryStateLoaded state) { return Container( padding: EdgeInsets.symmetric( horizontal: 24.h, @@ -875,7 +875,7 @@ class DiaryScreen extends StatelessWidget { ], ), ); - } + } */ _buildWakupRetire(BuildContext context, DiaryStateLoaded state) { return Container( -- 2.49.1 From c5c6ec0e9895761d5c2afd2279852d50ddb83b2c Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 8 Aug 2024 17:10:51 +0300 Subject: [PATCH 107/110] feat(diary): Remove photo is now an icon over the picture --- .../Release-iphonesimulator/FMDB.build/dgph | Bin 0 -> 94 bytes .../Release-iphonesimulator/Flutter.build/dgph | Bin 0 -> 94 bytes .../Release-iphonesimulator/Pods-Runner.build/dgph | Bin 0 -> 94 bytes .../flutter_keyboard_visibility.build/dgph | Bin 0 -> 94 bytes .../dgph | Bin 0 -> 94 bytes .../image_picker_ios.build/dgph | Bin 0 -> 94 bytes .../isar_flutter_libs.build/dgph | Bin 0 -> 94 bytes .../Release-iphonesimulator/location.build/dgph | Bin 0 -> 94 bytes .../dgph | Bin 0 -> 94 bytes .../path_provider_foundation.build/dgph | Bin 0 -> 94 bytes .../dgph | Bin 0 -> 94 bytes .../pointer_interceptor_ios.build/dgph | Bin 0 -> 94 bytes .../dgph | Bin 0 -> 94 bytes .../shared_preferences_foundation.build/dgph | Bin 0 -> 94 bytes .../sqflite-sqflite_ios_privacy.build/dgph | Bin 0 -> 94 bytes .../Release-iphonesimulator/sqflite.build/dgph | Bin 0 -> 94 bytes .../dgph | Bin 0 -> 94 bytes .../url_launcher_ios.build/dgph | Bin 0 -> 94 bytes 18 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/FMDB.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/Flutter.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/Pods-Runner.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/flutter_keyboard_visibility.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/image_picker_ios-image_picker_ios_privacy.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/image_picker_ios.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/isar_flutter_libs.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/location.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/path_provider_foundation-path_provider_foundation_privacy.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/path_provider_foundation.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/pointer_interceptor_ios-pointer_interceptor_ios_privacy.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/pointer_interceptor_ios.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/shared_preferences_foundation-shared_preferences_foundation_privacy.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/shared_preferences_foundation.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/sqflite-sqflite_ios_privacy.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/sqflite.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/url_launcher_ios-url_launcher_ios_privacy.build/dgph create mode 100644 ios/build/ios/Pods.build/Release-iphonesimulator/url_launcher_ios.build/dgph diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/FMDB.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/FMDB.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/Flutter.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/Flutter.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/Pods-Runner.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/Pods-Runner.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/flutter_keyboard_visibility.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/flutter_keyboard_visibility.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/image_picker_ios-image_picker_ios_privacy.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/image_picker_ios-image_picker_ios_privacy.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/image_picker_ios.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/image_picker_ios.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/isar_flutter_libs.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/isar_flutter_libs.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/location.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/location.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/path_provider_foundation-path_provider_foundation_privacy.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/path_provider_foundation-path_provider_foundation_privacy.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/path_provider_foundation.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/path_provider_foundation.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/pointer_interceptor_ios-pointer_interceptor_ios_privacy.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/pointer_interceptor_ios-pointer_interceptor_ios_privacy.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/pointer_interceptor_ios.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/pointer_interceptor_ios.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/shared_preferences_foundation-shared_preferences_foundation_privacy.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/shared_preferences_foundation-shared_preferences_foundation_privacy.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/shared_preferences_foundation.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/shared_preferences_foundation.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/sqflite-sqflite_ios_privacy.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/sqflite-sqflite_ios_privacy.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/sqflite.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/sqflite.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/url_launcher_ios-url_launcher_ios_privacy.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/url_launcher_ios-url_launcher_ios_privacy.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 diff --git a/ios/build/ios/Pods.build/Release-iphonesimulator/url_launcher_ios.build/dgph b/ios/build/ios/Pods.build/Release-iphonesimulator/url_launcher_ios.build/dgph new file mode 100644 index 0000000000000000000000000000000000000000..01c56549d5f0c33a35e2706f5f8fa6caa854ccc9 GIT binary patch literal 94 zcmZ>95AZP5Gce(HOHEQRv{W!MFf!pVGPE)^w=%S3XJBB|XJBLvElw>eW?*6|1=0-6 u+%BnQsX6%txv6<23@lu!i6v#3`SFPb1q`grnfb*GY%Br!DaDLH%?tqVfff7! literal 0 HcmV?d00001 -- 2.49.1 From 16d0863958c4590ab27d7cc40b3f5a129f6579c6 Mon Sep 17 00:00:00 2001 From: maxxkim Date: Thu, 8 Aug 2024 17:12:44 +0300 Subject: [PATCH 108/110] feat(diary): Remove photo is now an icon over the picture --- .../presentation/pages/diary_screen.dart | 201 +++++++++--------- 1 file changed, 99 insertions(+), 102 deletions(-) diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index ad4fb85..50853ea 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -284,61 +284,62 @@ class DiaryScreen extends StatelessWidget { /// Section Widget _buildAddPhoto(BuildContext context, DiaryStateLoaded state) { bool isLoading = state.isLoading; - return GestureDetector( - onTap: addImage(context, isLoading), - child: Stack( - children: [ - if (!isLoading) - Container( - margin: EdgeInsets.symmetric(horizontal: 10.h), - padding: EdgeInsets.symmetric( - horizontal: 40.h, - vertical: 80.v, - ), - decoration: AppDecoration.fillGray.copyWith( - borderRadius: BorderRadiusStyle.roundedBorder5, - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.end, - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: EdgeInsets.only( - left: 7.h, - top: 5.v, + if (state.currentMeal.photos.isEmpty) + return GestureDetector( + onTap: addImage(context, isLoading), + child: Stack( + children: [ + if (!isLoading) + Container( + margin: EdgeInsets.symmetric(horizontal: 10.h), + padding: EdgeInsets.symmetric( + horizontal: 40.h, + vertical: 80.v, + ), + decoration: AppDecoration.fillGray.copyWith( + borderRadius: BorderRadiusStyle.roundedBorder5, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: EdgeInsets.only( + left: 7.h, + top: 5.v, + ), + child: Text( + "Добавить фото", + selectionColor: appTheme.blueA400, + ), ), - child: Text( - "Добавить фото", - selectionColor: appTheme.blueA400, + Spacer(), + Icon( + Icons.photo_library, + color: appTheme.blueGray300, ), - ), - Spacer(), - Icon( - Icons.photo_library, - color: appTheme.blueGray300, - ), - ], + ], + ), ), - ), - if (isLoading) - Container( - margin: EdgeInsets.symmetric(horizontal: 10.h), - padding: EdgeInsets.symmetric( - horizontal: 40.h, - vertical: 80.v, + if (isLoading) + Container( + margin: EdgeInsets.symmetric(horizontal: 10.h), + padding: EdgeInsets.symmetric( + horizontal: 40.h, + vertical: 80.v, + ), + decoration: AppDecoration.fillGray.copyWith( + borderRadius: BorderRadiusStyle.roundedBorder5, + ), + child: Center( + child: CircularProgressIndicator(color: appTheme.blueGray300), // Замените на свой прелоадер при необходимости + ), ), - decoration: AppDecoration.fillGray.copyWith( - borderRadius: BorderRadiusStyle.roundedBorder5, - ), - child: Center( - child: CircularProgressIndicator( - color: appTheme - .blueGray300), // Замените на свой прелоадер при необходимости - ), - ), - ], - ), - ); + ], + ), + ); + else + return Container(); } addImage(BuildContext context, bool isLoading) { @@ -357,8 +358,7 @@ class DiaryScreen extends StatelessWidget { _buildMeal(BuildContext context, DiaryStateLoaded state) { final digitsOnly = FilteringTextInputFormatter.digitsOnly; - List _options = - state.autocompleteList.map((Product item) => item.name).toList(); + List _options = state.autocompleteList.map((Product item) => item.name).toList(); FocusNode focusNodeName = FocusNode(); return Container( padding: EdgeInsets.symmetric( @@ -393,9 +393,7 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectMealTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: state.mealTimeController - ?.format(context) - .toString(), + hintText: state.mealTimeController?.format(context).toString(), autofocus: false, ), ), @@ -531,9 +529,7 @@ class DiaryScreen extends StatelessWidget { SizedBox(height: 24.v), _buildAddProduct(context, state), SizedBox(height: 24.v), - ...state.portions - .map((portion) => _buildProduct(context, portion)) - .toList(), + ...state.portions.map((portion) => _buildProduct(context, portion)).toList(), SizedBox(height: 24.v), _buildCarousel(context, state), SizedBox(height: 24.v), @@ -682,8 +678,7 @@ class DiaryScreen extends StatelessWidget { popDialog(BuildContext dialogContext) { return () { - Navigator.of(dialogContext) - .pop(); // Dismiss the dialog on Cancel button press + Navigator.of(dialogContext).pop(); // Dismiss the dialog on Cancel button press }; } @@ -693,8 +688,7 @@ class DiaryScreen extends StatelessWidget { }; } - selectProduct(AutocompleteOnSelected onSelected, String option, - DiaryStateLoaded state) { + selectProduct(AutocompleteOnSelected onSelected, String option, DiaryStateLoaded state) { state.product_nameController.text = option; return () { onSelected(option); @@ -762,9 +756,7 @@ class DiaryScreen extends StatelessWidget { top: 5.v, ), child: Text( - portion.product_name.length > 8 - ? portion.product_name.substring(0, 8) - : portion.product_name, + portion.product_name.length > 8 ? portion.product_name.substring(0, 8) : portion.product_name, style: CustomTextStyles.titleMedium16, ), ), @@ -804,24 +796,42 @@ class DiaryScreen extends StatelessWidget { ), child: Image.network( baseUrl + '/storage/' + photo.path, + fit: BoxFit.cover, // Чтобы изображение занимало весь контейнер ), ), Positioned( - top: 5, - right: 5, - child: GestureDetector( - onTap: removePhoto(context, photo), - child: Container( - padding: EdgeInsets.all(5), - decoration: BoxDecoration( - shape: BoxShape.circle, - color: Colors.transparent, - ), - child: Icon( - Icons.close, - color: appTheme.blueGray300, + bottom: 0, + left: 0, + right: 0, + child: Container( + height: 50.h, // Высота затемненной области + decoration: BoxDecoration( + gradient: LinearGradient( + colors: [ + Colors.black.withOpacity(0.7), // Цвет затемнения + Colors.transparent, + ], + begin: Alignment.bottomCenter, + end: Alignment.topCenter, ), ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + IconButton( + icon: Icon(Icons.photo_outlined), + color: Colors.white, + onPressed: () { + // Ваш код для кнопки фотографии + }, + ), + IconButton( + icon: Icon(Icons.delete_outlined), + color: Colors.white, + onPressed: () => removePhoto(context, photo), + ), + ], + ), ), ), ], @@ -836,9 +846,7 @@ class DiaryScreen extends StatelessWidget { removePhoto(BuildContext context, Photo photo) { return () { - context - .read() - .add(RemoveImageEvent(photo.id.toString(), photo.path)); + context.read().add(RemoveImageEvent(photo.id.toString(), photo.path)); }; } @@ -898,9 +906,7 @@ class DiaryScreen extends StatelessWidget { r"Подъем \ отход ко сну", style: CustomTextStyles.bodyMediumBlack900, ), - Icon(state.wakeupExpanded - ? Icons.arrow_drop_up - : Icons.arrow_drop_down), + Icon(state.wakeupExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), ], ), ), @@ -914,8 +920,7 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectWakeupTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: - state.wakeupController.format(context).toString(), + hintText: state.wakeupController.format(context).toString(), prefix: Icon(Icons.sunny), autofocus: false, ), @@ -926,8 +931,7 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectRetireTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: - state.retireController.format(context).toString(), + hintText: state.retireController.format(context).toString(), prefix: Icon(Icons.bed), autofocus: false, ), @@ -974,8 +978,7 @@ class DiaryScreen extends StatelessWidget { }; } - Function() sendFinishDayData( - BuildContext dialogContext, BuildContext context) { + Function() sendFinishDayData(BuildContext dialogContext, BuildContext context) { return () { closeDialog(dialogContext); context.read().add(FinishDay()); @@ -1009,9 +1012,7 @@ class DiaryScreen extends StatelessWidget { "Ваше настроение после приема пищи", style: CustomTextStyles.bodyMediumBlack900, ), - Icon(state.moodExpanded - ? Icons.arrow_drop_up - : Icons.arrow_drop_down), + Icon(state.moodExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), ], ), ), @@ -1071,8 +1072,7 @@ class DiaryScreen extends StatelessWidget { }; } - Future _selectWakeupTime( - BuildContext context, DiaryStateLoaded state) async { + Future _selectWakeupTime(BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.wakeupController, @@ -1082,8 +1082,7 @@ class DiaryScreen extends StatelessWidget { } } - Future _selectRetireTime( - BuildContext context, DiaryStateLoaded state) async { + Future _selectRetireTime(BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.retireController, @@ -1093,8 +1092,7 @@ class DiaryScreen extends StatelessWidget { } } - Future _selectMealTime( - BuildContext context, DiaryStateLoaded state) async { + Future _selectMealTime(BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.mealTimeController ?? TimeOfDay.now(), @@ -1105,8 +1103,7 @@ class DiaryScreen extends StatelessWidget { } } -bool checkConsumedValues( - List recommendedValues, List consumedValues) { +bool checkConsumedValues(List recommendedValues, List consumedValues) { for (int i = 0; i < recommendedValues.length; i++) { if (consumedValues[i] > recommendedValues[i]) { // Если хотя бы одно потребленное значение превышает рекомендованное -- 2.49.1 From e72ecb5e2844a462d1dd8cde9fa53cce0a54abeb Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 9 Aug 2024 17:29:41 +0300 Subject: [PATCH 109/110] feat(diary): Chart refactor, photo add and delete refactor --- .../presentation/pages/diary_screen.dart | 74 +++++++++++++------ 1 file changed, 51 insertions(+), 23 deletions(-) diff --git a/lib/features/diary/presentation/pages/diary_screen.dart b/lib/features/diary/presentation/pages/diary_screen.dart index 50853ea..74a00ed 100644 --- a/lib/features/diary/presentation/pages/diary_screen.dart +++ b/lib/features/diary/presentation/pages/diary_screen.dart @@ -150,6 +150,12 @@ class DiaryScreen extends StatelessWidget { xValueMapper: (NutritionData data, _) => data.category, yValueMapper: (NutritionData data, _) => data.nutrition, pointColorMapper: (NutritionData data, _) => data.color, + trackColor: Color.fromRGBO(59, 130, 246, 1), + trackOpacity: 0.1, + gap: "8%", + radius: "110%", + innerRadius: + '20%', // Измените значение по вашему усмотрению ) ], ), @@ -332,7 +338,9 @@ class DiaryScreen extends StatelessWidget { borderRadius: BorderRadiusStyle.roundedBorder5, ), child: Center( - child: CircularProgressIndicator(color: appTheme.blueGray300), // Замените на свой прелоадер при необходимости + child: CircularProgressIndicator( + color: appTheme + .blueGray300), // Замените на свой прелоадер при необходимости ), ), ], @@ -358,7 +366,8 @@ class DiaryScreen extends StatelessWidget { _buildMeal(BuildContext context, DiaryStateLoaded state) { final digitsOnly = FilteringTextInputFormatter.digitsOnly; - List _options = state.autocompleteList.map((Product item) => item.name).toList(); + List _options = + state.autocompleteList.map((Product item) => item.name).toList(); FocusNode focusNodeName = FocusNode(); return Container( padding: EdgeInsets.symmetric( @@ -393,7 +402,9 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectMealTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: state.mealTimeController?.format(context).toString(), + hintText: state.mealTimeController + ?.format(context) + .toString(), autofocus: false, ), ), @@ -529,7 +540,9 @@ class DiaryScreen extends StatelessWidget { SizedBox(height: 24.v), _buildAddProduct(context, state), SizedBox(height: 24.v), - ...state.portions.map((portion) => _buildProduct(context, portion)).toList(), + ...state.portions + .map((portion) => _buildProduct(context, portion)) + .toList(), SizedBox(height: 24.v), _buildCarousel(context, state), SizedBox(height: 24.v), @@ -678,7 +691,8 @@ class DiaryScreen extends StatelessWidget { popDialog(BuildContext dialogContext) { return () { - Navigator.of(dialogContext).pop(); // Dismiss the dialog on Cancel button press + Navigator.of(dialogContext) + .pop(); // Dismiss the dialog on Cancel button press }; } @@ -688,7 +702,8 @@ class DiaryScreen extends StatelessWidget { }; } - selectProduct(AutocompleteOnSelected onSelected, String option, DiaryStateLoaded state) { + selectProduct(AutocompleteOnSelected onSelected, String option, + DiaryStateLoaded state) { state.product_nameController.text = option; return () { onSelected(option); @@ -730,7 +745,7 @@ class DiaryScreen extends StatelessWidget { return CarouselSlider( options: CarouselOptions(height: 200.0), items: state.currentMeal.photos.map((photo) { - return _buildPhoto(context, photo); + return _buildPhoto(context, photo, state); }).toList(), ); } @@ -756,7 +771,9 @@ class DiaryScreen extends StatelessWidget { top: 5.v, ), child: Text( - portion.product_name.length > 8 ? portion.product_name.substring(0, 8) : portion.product_name, + portion.product_name.length > 8 + ? portion.product_name.substring(0, 8) + : portion.product_name, style: CustomTextStyles.titleMedium16, ), ), @@ -786,7 +803,7 @@ class DiaryScreen extends StatelessWidget { ); } - _buildPhoto(BuildContext context, Photo photo) { + _buildPhoto(BuildContext context, Photo photo, DiaryStateLoaded state) { return Stack( children: [ Container( @@ -821,14 +838,12 @@ class DiaryScreen extends StatelessWidget { IconButton( icon: Icon(Icons.photo_outlined), color: Colors.white, - onPressed: () { - // Ваш код для кнопки фотографии - }, + onPressed: addImage(context, state.isLoading), ), IconButton( icon: Icon(Icons.delete_outlined), color: Colors.white, - onPressed: () => removePhoto(context, photo), + onPressed: removePhoto(context, photo), ), ], ), @@ -846,7 +861,9 @@ class DiaryScreen extends StatelessWidget { removePhoto(BuildContext context, Photo photo) { return () { - context.read().add(RemoveImageEvent(photo.id.toString(), photo.path)); + context + .read() + .add(RemoveImageEvent(photo.id.toString(), photo.path)); }; } @@ -906,7 +923,9 @@ class DiaryScreen extends StatelessWidget { r"Подъем \ отход ко сну", style: CustomTextStyles.bodyMediumBlack900, ), - Icon(state.wakeupExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), + Icon(state.wakeupExpanded + ? Icons.arrow_drop_up + : Icons.arrow_drop_down), ], ), ), @@ -920,7 +939,8 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectWakeupTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: state.wakeupController.format(context).toString(), + hintText: + state.wakeupController.format(context).toString(), prefix: Icon(Icons.sunny), autofocus: false, ), @@ -931,7 +951,8 @@ class DiaryScreen extends StatelessWidget { onTap: () => _selectRetireTime(context, state), child: AbsorbPointer( child: CustomTextFormField( - hintText: state.retireController.format(context).toString(), + hintText: + state.retireController.format(context).toString(), prefix: Icon(Icons.bed), autofocus: false, ), @@ -978,7 +999,8 @@ class DiaryScreen extends StatelessWidget { }; } - Function() sendFinishDayData(BuildContext dialogContext, BuildContext context) { + Function() sendFinishDayData( + BuildContext dialogContext, BuildContext context) { return () { closeDialog(dialogContext); context.read().add(FinishDay()); @@ -1012,7 +1034,9 @@ class DiaryScreen extends StatelessWidget { "Ваше настроение после приема пищи", style: CustomTextStyles.bodyMediumBlack900, ), - Icon(state.moodExpanded ? Icons.arrow_drop_up : Icons.arrow_drop_down), + Icon(state.moodExpanded + ? Icons.arrow_drop_up + : Icons.arrow_drop_down), ], ), ), @@ -1072,7 +1096,8 @@ class DiaryScreen extends StatelessWidget { }; } - Future _selectWakeupTime(BuildContext context, DiaryStateLoaded state) async { + Future _selectWakeupTime( + BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.wakeupController, @@ -1082,7 +1107,8 @@ class DiaryScreen extends StatelessWidget { } } - Future _selectRetireTime(BuildContext context, DiaryStateLoaded state) async { + Future _selectRetireTime( + BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.retireController, @@ -1092,7 +1118,8 @@ class DiaryScreen extends StatelessWidget { } } - Future _selectMealTime(BuildContext context, DiaryStateLoaded state) async { + Future _selectMealTime( + BuildContext context, DiaryStateLoaded state) async { final TimeOfDay? pickedTime = await showTimePicker( context: context, initialTime: state.mealTimeController ?? TimeOfDay.now(), @@ -1103,7 +1130,8 @@ class DiaryScreen extends StatelessWidget { } } -bool checkConsumedValues(List recommendedValues, List consumedValues) { +bool checkConsumedValues( + List recommendedValues, List consumedValues) { for (int i = 0; i < recommendedValues.length; i++) { if (consumedValues[i] > recommendedValues[i]) { // Если хотя бы одно потребленное значение превышает рекомендованное -- 2.49.1 From fa7bedbac717e49268d1b3b5cfb27f7f8de6490b Mon Sep 17 00:00:00 2001 From: maxxkim Date: Fri, 9 Aug 2024 17:40:01 +0300 Subject: [PATCH 110/110] feat(diary): Recommended diet product list for current day (stump) --- .../pages/diary_recommendations_scree.dart | 27 +++++++++++++- lib/locator_service.dart | 36 ++++++++++++------- 2 files changed, 50 insertions(+), 13 deletions(-) diff --git a/lib/features/diary/presentation/pages/diary_recommendations_scree.dart b/lib/features/diary/presentation/pages/diary_recommendations_scree.dart index 6c5dea7..b2dcfca 100644 --- a/lib/features/diary/presentation/pages/diary_recommendations_scree.dart +++ b/lib/features/diary/presentation/pages/diary_recommendations_scree.dart @@ -1,5 +1,6 @@ // ignore_for_file: unused_local_variable +import 'package:eatvio_app/features/diary/models/portion.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_bloc.dart'; import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart'; import 'package:eatvio_app/core/app_export.dart'; @@ -55,6 +56,8 @@ class DiaryRecommendationsScreen extends StatelessWidget { Widget _buildDiaryRecommendations( BuildContext context, DiaryStateLoaded state) { + final Portion product = + new Portion(id: 1, product_name: "", quantity: 1, portion: ""); return Stack( alignment: Alignment.bottomCenter, children: [ @@ -75,7 +78,29 @@ class DiaryRecommendationsScreen extends StatelessWidget { child: Padding( padding: EdgeInsets.only(bottom: 5.v), child: Column( - children: [], + children: [ + Scaffold( + appBar: AppBar( + title: Text(product.product_name), + ), + body: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Название продукта: ${product.product_name}', + style: TextStyle(fontSize: 24)), + SizedBox(height: 16), + Text( + 'Количество: ${product.quantity} ${product.portion}', + style: TextStyle(fontSize: 18)), + // Добавьте другие детали о продукте по необходимости + ], + ), + ), + ) + ], ), ), ), diff --git a/lib/locator_service.dart b/lib/locator_service.dart index 5ca320f..2c05df6 100644 --- a/lib/locator_service.dart +++ b/lib/locator_service.dart @@ -28,31 +28,43 @@ final sl = GetIt.instance; Future init() async { // BLoC / Cubit - sl.registerLazySingleton(() => InitializationCubit(chatRepository: sl())); + sl.registerLazySingleton( + () => InitializationCubit(chatRepository: sl())); sl.registerLazySingleton(() => NewMessagesCubit()); sl.registerLazySingleton(() => NotificationsCubit()); - sl.registerFactory(() => RegistrationCubit(registrationRepository: sl())); - sl.registerFactory(() => ChatRoomCubit(chatRepository: sl(), initializationCubit: sl())); + sl.registerFactory( + () => RegistrationCubit(registrationRepository: sl())); + sl.registerFactory( + () => ChatRoomCubit(chatRepository: sl(), initializationCubit: sl())); sl.registerFactory(() => FeedCubit(feedRepository: sl())); sl.registerFactory(() => RecipesCubit(feedRepository: sl())); - sl.registerFactory(() => BlogPostCubit(blogPostRepository: sl())); + sl.registerFactory( + () => BlogPostCubit(blogPostRepository: sl())); sl.registerFactory(() => DiaryBloc(diaryRepository: sl())); - sl.registerFactory(() => CalendarCubit(calendarRepository: sl())); + sl.registerFactory( + () => CalendarCubit(calendarRepository: sl())); // Repository - sl.registerLazySingleton(() => ChatRepository(chatService: sl())); - sl.registerLazySingleton(() => FeedRepository(feedService: sl())); - sl.registerLazySingleton(() => BlogPostRepository(blogPostService: sl())); - sl.registerLazySingleton(() => RegistrationRepository(registrationService: sl())); - sl.registerLazySingleton(() => DiaryRepository(diaryService: sl())); - sl.registerLazySingleton(() => CalendarRepository(calendarService: sl())); + sl.registerLazySingleton( + () => ChatRepository(chatService: sl())); + sl.registerLazySingleton( + () => FeedRepository(feedService: sl())); + sl.registerLazySingleton( + () => BlogPostRepository(blogPostService: sl())); + sl.registerLazySingleton( + () => RegistrationRepository(registrationService: sl())); + sl.registerLazySingleton( + () => DiaryRepository(diaryService: sl())); + sl.registerLazySingleton( + () => CalendarRepository(calendarService: sl())); // Services sl.registerLazySingleton(() => ChatService(sl())); sl.registerLazySingleton(() => FeedService(sl())); sl.registerLazySingleton(() => BlogPostService(sl())); - sl.registerLazySingleton(() => RegistrationService(sl())); + sl.registerLazySingleton( + () => RegistrationService(sl())); sl.registerLazySingleton(() => DiaryService(sl())); sl.registerLazySingleton(() => CalendarService(sl())); -- 2.49.1