Merge pull request 'chat update' (#99) from mso7nueh/eatvio_app_mso7nueh:main into main

Reviewed-on: eatvio/eatvio_app#99
Reviewed-by: apoloz <anatoliy.poloz@gmail.com>
This commit is contained in:
apoloz
2024-06-27 08:10:35 +00:00
142 changed files with 1686 additions and 950 deletions

View File

@@ -27,10 +27,8 @@ dart_code_metrics:
# maximum-nesting-level: 5 # maximum-nesting-level: 5
# metrics-exclude: # metrics-exclude:
# - test/** # - test/**
# rules:
# - newline-before-return # - newline-before-return
# - no-boolean-literal-compare # - no-boolean-literal-compare
# - no-empty-block # - no-empty-block
# - prefer-trailing-comma
# - prefer-conditional-expressions # - prefer-conditional-expressions
# - no-equal-then-else # - no-equal-then-else

View File

@@ -1,5 +1,5 @@
# Uncomment this line to define a global platform for your project # 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. # CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true' ENV['COCOAPODS_DISABLE_STATS'] = 'true'
@@ -37,5 +37,9 @@ end
post_install do |installer| post_install do |installer|
installer.pods_project.targets.each do |target| installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(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
end end

View File

@@ -9,7 +9,7 @@
/* Begin PBXBuildFile section */ /* Begin PBXBuildFile section */
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 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 */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
@@ -32,13 +32,12 @@
/* Begin PBXFileReference section */ /* Begin PBXFileReference section */
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; }; 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; };
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };
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 = "<group>"; }; 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 = "<group>"; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
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 = "<group>"; };
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 = "<group>"; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
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 = "<group>"; };
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };
9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };
97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; 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 = "<group>"; }; 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
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 = "<group>"; }; 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 = "<group>"; };
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 = "<group>"; };
/* End PBXFileReference section */ /* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */ /* Begin PBXFrameworksBuildPhase section */
@@ -54,27 +54,19 @@
isa = PBXFrameworksBuildPhase; isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
68F4DD6659288F4CFDC41C5C /* Pods_Runner.framework in Frameworks */, 46B43B96F809CEC6058EFDD3 /* Pods_Runner.framework in Frameworks */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };
/* End PBXFrameworksBuildPhase section */ /* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */ /* Begin PBXGroup section */
28430AE518366E9EB19A31C9 /* Frameworks */ = {
isa = PBXGroup;
children = (
7024DE075B2C1E5A149230E4 /* Pods_Runner.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
6F201E010624CF963CC3A17B /* Pods */ = { 6F201E010624CF963CC3A17B /* Pods */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
1DC098B20AE17A152A9E7BC6 /* Pods-Runner.debug.xcconfig */, 938EE8FB5BAA359AAEDEFFF8 /* Pods-Runner.debug.xcconfig */,
4B6A3CFB60775CA626789750 /* Pods-Runner.release.xcconfig */, 9D8D6181877DE17809AFF936 /* Pods-Runner.release.xcconfig */,
EC46FEE88A2E87A3510B5EC3 /* Pods-Runner.profile.xcconfig */, DF0C4038A57E19D3ABA03C15 /* Pods-Runner.profile.xcconfig */,
); );
path = Pods; path = Pods;
sourceTree = "<group>"; sourceTree = "<group>";
@@ -97,7 +89,7 @@
97C146F01CF9000F007C117D /* Runner */, 97C146F01CF9000F007C117D /* Runner */,
97C146EF1CF9000F007C117D /* Products */, 97C146EF1CF9000F007C117D /* Products */,
6F201E010624CF963CC3A17B /* Pods */, 6F201E010624CF963CC3A17B /* Pods */,
28430AE518366E9EB19A31C9 /* Frameworks */, AEE6B7943D197783DD1CB2EE /* Frameworks */,
); );
sourceTree = "<group>"; sourceTree = "<group>";
}; };
@@ -124,6 +116,14 @@
path = Runner; path = Runner;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
AEE6B7943D197783DD1CB2EE /* Frameworks */ = {
isa = PBXGroup;
children = (
15ADDB2A35F334AF0AE50011 /* Pods_Runner.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
/* End PBXGroup section */ /* End PBXGroup section */
/* Begin PBXNativeTarget section */ /* Begin PBXNativeTarget section */
@@ -131,14 +131,14 @@
isa = PBXNativeTarget; isa = PBXNativeTarget;
buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
buildPhases = ( buildPhases = (
C9531164650CD277994F87F5 /* [CP] Check Pods Manifest.lock */, 9A49250058577CAA8C897A03 /* [CP] Check Pods Manifest.lock */,
9740EEB61CF901F6004384FC /* Run Script */, 9740EEB61CF901F6004384FC /* Run Script */,
97C146EA1CF9000F007C117D /* Sources */, 97C146EA1CF9000F007C117D /* Sources */,
97C146EB1CF9000F007C117D /* Frameworks */, 97C146EB1CF9000F007C117D /* Frameworks */,
97C146EC1CF9000F007C117D /* Resources */, 97C146EC1CF9000F007C117D /* Resources */,
9705A1C41CF9048500538489 /* Embed Frameworks */, 9705A1C41CF9048500538489 /* Embed Frameworks */,
3B06AD1E1E4923F5004D2608 /* Thin Binary */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */,
8944C2327F94FA34E28A19A3 /* [CP] Embed Pods Frameworks */, 1D324C14EB43C988423BC1AD /* [CP] Embed Pods Frameworks */,
); );
buildRules = ( buildRules = (
); );
@@ -198,23 +198,7 @@
/* End PBXResourcesBuildPhase section */ /* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */
3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { 1D324C14EB43C988423BC1AD /* [CP] Embed Pods Frameworks */ = {
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 */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
@@ -231,6 +215,22 @@
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
showEnvVarsInLog = 0; 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 */ = { 9740EEB61CF901F6004384FC /* Run Script */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1; alwaysOutOfDate = 1;
@@ -246,7 +246,7 @@
shellPath = /bin/sh; shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; 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; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (

View File

@@ -52,5 +52,10 @@
<true/> <true/>
<key>UIApplicationSupportsIndirectInputEvents</key> <key>UIApplicationSupportsIndirectInputEvents</key>
<true/> <true/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</dict> </dict>
</plist> </plist>

View File

@@ -202,16 +202,14 @@ class AppRouter {
path: '/chat-select-screen', path: '/chat-select-screen',
name: 'chatSelectScreen', name: 'chatSelectScreen',
builder: (context, state) => 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( GoRoute(
path: '/my-settings-screen', path: '/my-settings-screen',
name: 'mySettingsScreen', name: 'mySettingsScreen',

View File

@@ -1,7 +1,6 @@
export 'package:flutter_bloc/flutter_bloc.dart'; export 'package:flutter_bloc/flutter_bloc.dart';
export 'package:eatvio_app/core/constants/constants.dart'; export 'package:eatvio_app/core/constants/constants.dart';
export 'package:eatvio_app/core/errors/exceptions.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/image_constant.dart';
export 'package:eatvio_app/core/utils/logger.dart'; export 'package:eatvio_app/core/utils/logger.dart';
export 'package:eatvio_app/core/utils/pref_utils.dart'; export 'package:eatvio_app/core/utils/pref_utils.dart';

View File

@@ -0,0 +1,54 @@
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<InitializationState> {
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 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()));
}
}
}

View File

@@ -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;
}

View File

@@ -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>(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 extends Object?>(
TResult Function() $default, {
required TResult Function() loading,
required TResult Function() success,
required TResult Function(String errorMessage) error,
}) =>
throw _privateConstructorUsedError;
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function()? $default, {
TResult? Function()? loading,
TResult? Function()? success,
TResult? Function(String errorMessage)? error,
}) =>
throw _privateConstructorUsedError;
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function()? $default, {
TResult Function()? loading,
TResult Function()? success,
TResult Function(String errorMessage)? error,
required TResult orElse(),
}) =>
throw _privateConstructorUsedError;
@optionalTypeArgs
TResult map<TResult extends Object?>(
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 extends Object?>(
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 extends Object?>(
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 extends Object?>(
TResult Function() $default, {
required TResult Function() loading,
required TResult Function() success,
required TResult Function(String errorMessage) error,
}) {
return $default();
}
@override
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function()? $default, {
TResult? Function()? loading,
TResult? Function()? success,
TResult? Function(String errorMessage)? error,
}) {
return $default?.call();
}
@override
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
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 extends Object?>(
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 extends Object?>(
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 extends Object?>(
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 extends Object?>(
TResult Function() $default, {
required TResult Function() loading,
required TResult Function() success,
required TResult Function(String errorMessage) error,
}) {
return loading();
}
@override
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function()? $default, {
TResult? Function()? loading,
TResult? Function()? success,
TResult? Function(String errorMessage)? error,
}) {
return loading?.call();
}
@override
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
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 extends Object?>(
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 extends Object?>(
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 extends Object?>(
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 extends Object?>(
TResult Function() $default, {
required TResult Function() loading,
required TResult Function() success,
required TResult Function(String errorMessage) error,
}) {
return success();
}
@override
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function()? $default, {
TResult? Function()? loading,
TResult? Function()? success,
TResult? Function(String errorMessage)? error,
}) {
return success?.call();
}
@override
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
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 extends Object?>(
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 extends Object?>(
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 extends Object?>(
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 extends Object?>(
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 extends Object?>(
TResult? Function()? $default, {
TResult? Function()? loading,
TResult? Function()? success,
TResult? Function(String errorMessage)? error,
}) {
return error?.call(errorMessage);
}
@override
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
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 extends Object?>(
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 extends Object?>(
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 extends Object?>(
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;
}

View File

@@ -1,47 +0,0 @@
import 'package:connectivity_plus/connectivity_plus.dart';
// For checking internet connectivity
abstract class NetworkInfoI {
Future<bool> isConnected();
Future<ConnectivityResult> get connectivityResult;
Stream<ConnectivityResult> 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<bool> isConnected() async {
final result = await connectivity.checkConnectivity();
if (result != ConnectivityResult.none) {
return true;
}
return false;
}
// to check type of internet connectivity
@override
Future<ConnectivityResult> get connectivityResult async {
return connectivity.checkConnectivity();
}
//check the type on internet connection on changed of internet connection
@override
Stream<ConnectivityResult> get onConnectivityChanged =>
connectivity.onConnectivityChanged;
}

View File

@@ -19,7 +19,7 @@ class ProgressDialogUtils {
), ),
), ),
); );
}); },);
isProgressVisible = true; isProgressVisible = true;
} }
} }

View File

@@ -3,7 +3,7 @@ import 'package:flutter/material.dart';
// This functions are responsible to make UI responsive across all the mobile devices. // This functions are responsible to make UI responsive across all the mobile devices.
MediaQueryData mediaQueryData = MediaQueryData.fromView( 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 the Viewport values of your Figma Design.
// These are used in the code as a reference to create your UI Responsively. // These are used in the code as a reference to create your UI Responsively.

View File

@@ -6,7 +6,11 @@ part 'websocket_info_model.g.dart';
@freezed @freezed
class WebsocketInfoModel with _$WebsocketInfoModel { 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<String, Object?> json) => _$WebsocketInfoModelFromJson(json); factory WebsocketInfoModel.fromJson(Map<String, Object?> json) => _$WebsocketInfoModelFromJson(json);
} }

View File

@@ -20,7 +20,14 @@ WebsocketInfoModel _$WebsocketInfoModelFromJson(Map<String, dynamic> json) {
/// @nodoc /// @nodoc
mixin _$WebsocketInfoModel { mixin _$WebsocketInfoModel {
String get key => throw _privateConstructorUsedError;
String get host => throw _privateConstructorUsedError;
String get port => throw _privateConstructorUsedError;
Map<String, dynamic> toJson() => throw _privateConstructorUsedError; Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
@JsonKey(ignore: true)
$WebsocketInfoModelCopyWith<WebsocketInfoModel> get copyWith =>
throw _privateConstructorUsedError;
} }
/// @nodoc /// @nodoc
@@ -28,6 +35,8 @@ abstract class $WebsocketInfoModelCopyWith<$Res> {
factory $WebsocketInfoModelCopyWith( factory $WebsocketInfoModelCopyWith(
WebsocketInfoModel value, $Res Function(WebsocketInfoModel) then) = WebsocketInfoModel value, $Res Function(WebsocketInfoModel) then) =
_$WebsocketInfoModelCopyWithImpl<$Res, WebsocketInfoModel>; _$WebsocketInfoModelCopyWithImpl<$Res, WebsocketInfoModel>;
@useResult
$Res call({String key, String host, String port});
} }
/// @nodoc /// @nodoc
@@ -39,13 +48,40 @@ class _$WebsocketInfoModelCopyWithImpl<$Res, $Val extends WebsocketInfoModel>
final $Val _value; final $Val _value;
// ignore: unused_field // ignore: unused_field
final $Res Function($Val) _then; 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 /// @nodoc
abstract class _$$WebsocketInfoModelImplCopyWith<$Res> { abstract class _$$WebsocketInfoModelImplCopyWith<$Res>
implements $WebsocketInfoModelCopyWith<$Res> {
factory _$$WebsocketInfoModelImplCopyWith(_$WebsocketInfoModelImpl value, factory _$$WebsocketInfoModelImplCopyWith(_$WebsocketInfoModelImpl value,
$Res Function(_$WebsocketInfoModelImpl) then) = $Res Function(_$WebsocketInfoModelImpl) then) =
__$$WebsocketInfoModelImplCopyWithImpl<$Res>; __$$WebsocketInfoModelImplCopyWithImpl<$Res>;
@override
@useResult
$Res call({String key, String host, String port});
} }
/// @nodoc /// @nodoc
@@ -55,30 +91,72 @@ class __$$WebsocketInfoModelImplCopyWithImpl<$Res>
__$$WebsocketInfoModelImplCopyWithImpl(_$WebsocketInfoModelImpl _value, __$$WebsocketInfoModelImplCopyWithImpl(_$WebsocketInfoModelImpl _value,
$Res Function(_$WebsocketInfoModelImpl) _then) $Res Function(_$WebsocketInfoModelImpl) _then)
: super(_value, _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 /// @nodoc
@JsonSerializable() @JsonSerializable()
class _$WebsocketInfoModelImpl implements _WebsocketInfoModel { class _$WebsocketInfoModelImpl implements _WebsocketInfoModel {
const _$WebsocketInfoModelImpl(); const _$WebsocketInfoModelImpl(
{required this.key, required this.host, required this.port});
factory _$WebsocketInfoModelImpl.fromJson(Map<String, dynamic> json) => factory _$WebsocketInfoModelImpl.fromJson(Map<String, dynamic> json) =>
_$$WebsocketInfoModelImplFromJson(json); _$$WebsocketInfoModelImplFromJson(json);
@override
final String key;
@override
final String host;
@override
final String port;
@override @override
String toString() { String toString() {
return 'WebsocketInfoModel()'; return 'WebsocketInfoModel(key: $key, host: $host, port: $port)';
} }
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
return identical(this, 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) @JsonKey(ignore: true)
@override @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 @override
Map<String, dynamic> toJson() { Map<String, dynamic> toJson() {
@@ -89,8 +167,22 @@ class _$WebsocketInfoModelImpl implements _WebsocketInfoModel {
} }
abstract class _WebsocketInfoModel 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<String, dynamic> json) = factory _WebsocketInfoModel.fromJson(Map<String, dynamic> json) =
_$WebsocketInfoModelImpl.fromJson; _$WebsocketInfoModelImpl.fromJson;
@override
String get key;
@override
String get host;
@override
String get port;
@override
@JsonKey(ignore: true)
_$$WebsocketInfoModelImplCopyWith<_$WebsocketInfoModelImpl> get copyWith =>
throw _privateConstructorUsedError;
} }

View File

@@ -8,8 +8,16 @@ part of 'websocket_info_model.dart';
_$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson( _$WebsocketInfoModelImpl _$$WebsocketInfoModelImplFromJson(
Map<String, dynamic> json) => Map<String, dynamic> json) =>
_$WebsocketInfoModelImpl(); _$WebsocketInfoModelImpl(
key: json['key'] as String,
host: json['host'] as String,
port: json['port'] as String,
);
Map<String, dynamic> _$$WebsocketInfoModelImplToJson( Map<String, dynamic> _$$WebsocketInfoModelImplToJson(
_$WebsocketInfoModelImpl instance) => _$WebsocketInfoModelImpl instance) =>
<String, dynamic>{}; <String, dynamic>{
'key': instance.key,
'host': instance.host,
'port': instance.port,
};

View File

@@ -6,7 +6,7 @@ import 'package:flutter/cupertino.dart';
import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/core/app_export.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
class ChatScreen extends StatelessWidget { class ChatScreen extends StatefulWidget {
final String chatId; final String chatId;
const ChatScreen({ const ChatScreen({
@@ -14,9 +14,14 @@ class ChatScreen extends StatelessWidget {
super.key, super.key,
}); });
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocProvider<ChatRoomCubit>( return BlocProvider<ChatRoomCubit>(
create: (BuildContext context) => sl()..initChat(chatId), create: (BuildContext context) => sl()..initChat(widget.chatId),
child: BlocBuilder<ChatRoomCubit, ChatRoomState>( child: BlocBuilder<ChatRoomCubit, ChatRoomState>(
builder: (context, state) { builder: (context, state) {
if (state is ChatRoomStateLoading) { if (state is ChatRoomStateLoading) {
@@ -81,119 +86,121 @@ class ChatScreen extends StatelessWidget {
], ],
), ),
), ),
body: Column( body: SafeArea(
mainAxisSize: MainAxisSize.min, child: Column(
children: [ mainAxisSize: MainAxisSize.min,
Expanded( children: [
child: Container( Expanded(
color: Color(0xFFF0F2F5), child: Container(
width: double.maxFinite, color: Color(0xFFF0F2F5),
child: CustomScrollView( width: double.maxFinite,
reverse: true, child: CustomScrollView(
slivers: [ reverse: true,
SliverPadding( slivers: [
padding: EdgeInsets.symmetric(vertical: 16), SliverPadding(
sliver: SliverList( padding: EdgeInsets.symmetric(vertical: 16),
delegate: SliverChildBuilderDelegate( sliver: SliverList(
(context, index) => ChatBubbleWidget( delegate: SliverChildBuilderDelegate(
text: state.chatRoomModel.messages[state.chatRoomModel.messages.length - index - 1].data, (context, index) => ChatBubbleWidget(
isCurrentUser: state.chatRoomModel.users['to_chat_user']!.id != text: state.chatRoomModel.messages[state.chatRoomModel.messages.length - index - 1].data,
state.chatRoomModel.messages[state.chatRoomModel.messages.length - index - 1].authorId, isCurrentUser: state.chatRoomModel.users['to_chat_user']!.id !=
mediaData: state.chatRoomModel.messages[state.chatRoomModel.messages.length - index - 1].mediaData, 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),
), ),
), ),
), ),
], SizedBox(width: 8),
), SizedBox(
), width: mediaQueryData.size.width - 96,
), child: TextFormField(
Padding( maxLines: 5,
padding: EdgeInsets.symmetric(vertical: 8), minLines: 1,
child: Row( keyboardType: TextInputType.multiline,
crossAxisAlignment: CrossAxisAlignment.center, style: TextStyle(
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(
fontSize: 16, fontSize: 16,
fontFamily: 'Mulish', fontFamily: 'Mulish',
fontWeight: FontWeight.w400, fontWeight: FontWeight.w400,
color: Color(0xFFAEAEB2), color: Colors.black,
), ),
filled: true, decoration: InputDecoration(
border: OutlineInputBorder( contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 4),
borderRadius: BorderRadiusStyle.circleBorder17, hintText: 'Сообщение',
borderSide: BorderSide( hintStyle: TextStyle(
color: Color(0xFFD1D1D6), fontSize: 16,
width: 1, fontFamily: 'Mulish',
fontWeight: FontWeight.w400,
color: Color(0xFFAEAEB2),
), ),
), filled: true,
enabledBorder: OutlineInputBorder( border: OutlineInputBorder(
borderRadius: BorderRadiusStyle.circleBorder17, borderRadius: BorderRadiusStyle.circleBorder17,
borderSide: BorderSide( borderSide: BorderSide(
color: Color(0xFFD1D1D6), color: Color(0xFFD1D1D6),
width: 1, width: 1,
),
), ),
), enabledBorder: OutlineInputBorder(
focusedBorder: OutlineInputBorder( borderRadius: BorderRadiusStyle.circleBorder17,
borderRadius: BorderRadiusStyle.circleBorder17, borderSide: BorderSide(
borderSide: BorderSide( color: Color(0xFFD1D1D6),
color: Color(0xFFD1D1D6), width: 1,
width: 1, ),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadiusStyle.circleBorder17,
borderSide: BorderSide(
color: Color(0xFFD1D1D6),
width: 1,
),
), ),
), ),
), ),
), ),
), SizedBox(width: 8),
SizedBox(width: 8), InkWell(
InkWell( borderRadius: BorderRadiusStyle.circleBorder17,
borderRadius: BorderRadiusStyle.circleBorder17, onTap: () {},
onTap: () {}, child: Ink(
child: Ink( height: 32,
height: 32, width: 32,
width: 32, child: Icon(
child: Icon( Icons.send_outlined,
Icons.send_outlined, size: 28,
size: 28, color: Color(0xFF858E99),
color: Color(0xFF858E99), ),
), ),
), ),
), SizedBox(width: 8),
SizedBox(width: 8), ],
], ),
), ),
), ],
], ),
), ),
); );
} }

View File

@@ -27,17 +27,22 @@ class ChatSelectBloc extends Bloc<ChatSelectEvent, ChatSelectState> {
List<ChatItemModel> chats = []; List<ChatItemModel> chats = [];
for (int i = 0; i < chatRooms.length; i++) { for (int i = 0; i < chatRooms.length; i++) {
String text = chatRooms[i]['last_message']['data']; 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; text = "Вы: " + text;
} }
chats.add(ChatItemModel( chats.add(
ChatItemModel(
id: chatRooms[i]['id'], id: chatRooms[i]['id'],
userImage: chatRooms[i]['users']['to_chat_user'] userImage: chatRooms[i]['users']['to_chat_user']['profile_photo_path'],
['profile_photo_path'],
username: chatRooms[i]['users']['to_chat_user']['name'], username: chatRooms[i]['users']['to_chat_user']['name'],
dateText: DateFormat('dd.MM').format( dateText: DateFormat('dd.MM').format(
DateTime.parse(chatRooms[i]['last_message']['updated_at'])), DateTime.parse(
greetingText: text)); chatRooms[i]['last_message']['updated_at'],
),
),
greetingText: text,
),
);
} }
return chats; return chats;
} }
@@ -66,17 +71,16 @@ class ChatSelectBloc extends Bloc<ChatSelectEvent, ChatSelectState> {
emit(currentState.copyWith( emit(currentState.copyWith(
chatSelectModelObj: currentState.chatSelectModelObj, chatSelectModelObj: currentState.chatSelectModelObj,
chatRooms: currentState.chatRooms, chatRooms: currentState.chatRooms,
)); ),);
} else { } else {
emit(ChatSelectLoadedState( emit(ChatSelectLoadedState(
chatRooms: fillChatEntryList(data['chatRooms']), chatRooms: fillChatEntryList(data['chatRooms']),
//chatRooms: [], //chatRooms: [],
)); ),);
} }
} else { } else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку
emit(ChatSelectErrorState( emit(ChatSelectErrorState('Некоторые необходимые данные отсутствуют.'));
'Некоторые необходимые данные отсутствуют.'));
} }
} else { } else {
// Статус ответа не равен 200, обрабатываем ошибку // Статус ответа не равен 200, обрабатываем ошибку

View File

@@ -2,32 +2,30 @@ import 'package:flutter/material.dart';
import 'package:eatvio_app/core/app_export.dart'; import 'package:eatvio_app/core/app_export.dart';
class CustomSearchView extends StatelessWidget { class CustomSearchView extends StatelessWidget {
CustomSearchView( CustomSearchView({
{Key? key, Key? key,
this.alignment, this.alignment,
this.width, this.width,
this.scrollPadding, this.scrollPadding,
this.controller, this.controller,
this.focusNode, this.focusNode,
this.autofocus = false, this.autofocus = false,
this.textStyle, this.textStyle,
this.textInputType = TextInputType.text, this.textInputType = TextInputType.text,
this.maxLines, this.maxLines,
this.hintText, this.hintText,
this.hintStyle, this.hintStyle,
this.prefix, this.prefix,
this.prefixConstraints, this.prefixConstraints,
this.suffix, this.suffix,
this.suffixConstraints, this.suffixConstraints,
this.contentPadding, this.contentPadding,
this.borderDecoration, this.borderDecoration,
this.fillColor, this.fillColor,
this.filled = true, this.filled = true,
this.validator, this.validator,
this.onChanged}) this.onChanged,
: super( }) : super(key: key);
key: key,
);
final Alignment? alignment; final Alignment? alignment;
@@ -73,13 +71,12 @@ class CustomSearchView extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return alignment != null ? Align(alignment: alignment ?? Alignment.center, child: searchViewWidget(context)) : searchViewWidget(context); return searchViewWidget(context);
} }
searchViewWidget(BuildContext context) => SizedBox( searchViewWidget(BuildContext context) => SizedBox(
width: width ?? double.maxFinite, width: width ?? double.maxFinite,
child: TextFormField( child: TextFormField(
scrollPadding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
controller: controller, controller: controller,
focusNode: focusNode, focusNode: focusNode,
onTapOutside: (event) => onTapOutside(), onTapOutside: (event) => onTapOutside(),

View File

@@ -44,7 +44,7 @@ class ChatSelectScreen extends StatelessWidget {
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return [ return [
SliverAppBar( SliverAppBar(
backgroundColor: Colors.white, automaticallyImplyLeading: false,
stretchTriggerOffset: 1, stretchTriggerOffset: 1,
forceMaterialTransparency: true, forceMaterialTransparency: true,
floating: true, floating: true,
@@ -64,7 +64,10 @@ class ChatSelectScreen extends StatelessWidget {
), ),
); );
} else if (state is ChatSelectErrorState) { } 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 { } else {
return Scaffold( return Scaffold(
body: Center( body: Center(

View File

@@ -4,26 +4,23 @@ import 'package:eatvio_app/core/app_export.dart';
// ignore_for_file: must_be_immutable // ignore_for_file: must_be_immutable
class ChatItemModel { class ChatItemModel {
ChatItemModel( String? userImage;
{this.userImage, String? username;
this.username, String? dateText;
this.dateText, String? greetingText;
this.greetingText, String id;
required this.id}) {
ChatItemModel({
this.userImage,
this.username,
this.dateText,
this.greetingText,
required this.id,
}) {
userImage = userImage ?? ImageConstant.imageNotFound; userImage = userImage ?? ImageConstant.imageNotFound;
username = username; username = username;
dateText = dateText; dateText = dateText;
greetingText = greetingText; greetingText = greetingText;
id = id; id = id;
} }
String? userImage;
String? username;
String? dateText;
String? greetingText;
String id;
} }

View File

@@ -5,9 +5,11 @@ import 'package:equatable/equatable.dart';
/// This class defines the variables used in the [chat_select_screen], /// 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. /// and is typically used to hold data that is passed between different parts of the application.
class ChatSelectModel extends Equatable { class ChatSelectModel extends Equatable {
ChatSelectModel({this.chatList = const []}); ChatSelectModel({this.chatList = const []});
List<ChatItemModel> chatList; List<ChatItemModel> chatList;
ChatSelectModel copyWith({List<ChatItemModel>? chatList}) { ChatSelectModel copyWith({List<ChatItemModel>? chatList}) {
return ChatSelectModel( return ChatSelectModel(
chatList: chatList ?? this.chatList, chatList: chatList ?? this.chatList,

View File

@@ -15,12 +15,13 @@ class ChatEntryWidget extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return GestureDetector( return InkWell(
onTap: () => GoRouter.of(context).goNamed( borderRadius: BorderRadiusStyle.circleBorder8,
onTap: () => GoRouter.of(context).pushNamed(
'chatScreen', 'chatScreen',
extra: chatEntryObj.id.toString(), extra: chatEntryObj.id.toString(),
), ),
child: Container( child: Ink(
padding: EdgeInsets.all(16), padding: EdgeInsets.all(16),
decoration: BoxDecoration( decoration: BoxDecoration(
borderRadius: BorderRadiusStyle.circleBorder8, borderRadius: BorderRadiusStyle.circleBorder8,
@@ -74,7 +75,7 @@ class ChatEntryWidget extends StatelessWidget {
chatEntryObj.dateText!, chatEntryObj.dateText!,
style: theme.textTheme.bodyMedium, style: theme.textTheme.bodyMedium,
), ),
) ),
], ],
), ),
SizedBox(height: 6.v), SizedBox(height: 6.v),
@@ -84,7 +85,7 @@ class ChatEntryWidget extends StatelessWidget {
), ),
], ],
), ),
) ),
], ],
), ),
), ),

View File

@@ -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:eatvio_app/core/app_export.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import 'package:photo_view/photo_view.dart'; import 'package:photo_view/photo_view.dart';
@@ -34,37 +35,32 @@ class _PhotoViewScreenState extends State<PhotoViewScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return DismissiblePage(
backgroundColor: Colors.black, minScale: 1,
appBar: AppBar( onDismissed: () => GoRouter.of(context).pop(),
centerTitle: true, direction: DismissiblePageDismissDirection.vertical,
systemOverlayStyle: SystemUiOverlayStyle( isFullScreen: true,
statusBarColor: Colors.black, child: PhotoViewGallery.builder(
statusBarBrightness: Brightness.dark, backgroundDecoration: BoxDecoration(
statusBarIconBrightness: Brightness.light, color: Colors.transparent,
), ),
backgroundColor: Colors.black, scrollPhysics: const BouncingScrollPhysics(),
foregroundColor: Colors.white, builder: (BuildContext context, int index) {
title: Text( return PhotoViewGalleryPageOptions(
(imageIndex + 1).toString() + ' из ' + widget.imageUrls.length.toString(), imageProvider: CachedNetworkImageProvider(
), widget.imageUrls[index],
), ),
body: Dismissible( initialScale: PhotoViewComputedScale.contained,
direction: DismissDirection.vertical, minScale: PhotoViewComputedScale.contained,
key: const Key('key'), heroAttributes: PhotoViewHeroAttributes(
onDismissed: (_) => GoRouter.of(context).pop(), tag: widget.imageUrls[index],
resizeDuration: Duration(microseconds: 1), transitionOnUserGestures: true,
child: Container( ),
child: PhotoViewGallery.builder( errorBuilder: (context, object, stackTrace) {
scrollPhysics: const BouncingScrollPhysics(), return Scaffold(
builder: (BuildContext context, int index) { backgroundColor: Colors.black,
return PhotoViewGalleryPageOptions( body: SafeArea(
imageProvider: NetworkImage(widget.imageUrls[index]), child: Column(
initialScale: PhotoViewComputedScale.contained,
minScale: PhotoViewComputedScale.contained,
heroAttributes: PhotoViewHeroAttributes(tag: widget.imageUrls[index]),
errorBuilder: (context, object, stackTrace) {
return Column(
children: [ children: [
SizedBox(height: 32), SizedBox(height: 32),
Text('Файл'), Text('Файл'),
@@ -96,28 +92,28 @@ class _PhotoViewScreenState extends State<PhotoViewScreen> {
), ),
), ),
], ],
); ),
}, ),
); );
}, },
itemCount: widget.imageUrls.length, );
loadingBuilder: (context, event) => Center( },
child: Container( itemCount: widget.imageUrls.length,
width: 20.0, loadingBuilder: (context, event) => Center(
height: 20.0, child: Container(
child: CircularProgressIndicator( width: 20.0,
value: event == null ? 0 : event.cumulativeBytesLoaded / event.expectedTotalBytes!, 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;
});
},
), ),
); );
} }

View File

@@ -1,8 +1,9 @@
import 'package:cached_network_image/cached_network_image.dart'; 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:eatvio_app/theme/app_decoration.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:go_router/go_router.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
class ChatBubbleWidget extends StatelessWidget { class ChatBubbleWidget extends StatelessWidget {
@@ -71,18 +72,21 @@ class ChatBubbleWidget extends StatelessWidget {
} }
return GestureDetector( return GestureDetector(
onTap: () { onTap: () {
GoRouter.of(context).pushNamed( context.pushTransparentRoute(
'photoViewScreen', PhotoViewScreen(
extra: mediaData!.map((e) => dotenv.env['STORAGE_URL']! + e.toString()).toList(), imageUrls: mediaData!.map((e) => dotenv.env['STORAGE_URL']! + e.toString()).toList(),
pathParameters: { index: index,
'index': index.toString(), ),
},
); );
}, },
child: ClipRRect( child: Hero(
borderRadius: BorderRadiusStyle.roundedBorder8, tag: dotenv.env['STORAGE_URL']! + '${mediaData![index]}',
child: CachedNetworkImage( transitionOnUserGestures: true,
imageUrl: dotenv.env['STORAGE_URL']! + '${mediaData![index]}', child: ClipRRect(
borderRadius: BorderRadiusStyle.roundedBorder8,
child: CachedNetworkImage(
imageUrl: dotenv.env['STORAGE_URL']! + '${mediaData![index]}',
),
), ),
), ),
); );

View File

@@ -26,7 +26,7 @@ class AppLocalization {
return AppLocalization(Locale( return AppLocalization(Locale(
'ru', 'ru',
'', '',
)); // Возвращаем дефолтное значение или обработку ошибки ),); // Возвращаем дефолтное значение или обработку ошибки
} }
} }

View File

@@ -1,4 +1,5 @@
import 'package:dio/dio.dart'; 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/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/repositories/chat_repository.dart';
import 'package:eatvio_app/features/chat/services/chat_service.dart'; import 'package:eatvio_app/features/chat/services/chat_service.dart';
@@ -10,6 +11,7 @@ final sl = GetIt.instance;
Future<void> init() async { Future<void> init() async {
// BLoC // BLoC
sl.registerFactory<ChatRoomCubit>(() => ChatRoomCubit(chatRepository: sl())); sl.registerFactory<ChatRoomCubit>(() => ChatRoomCubit(chatRepository: sl()));
sl.registerFactory<InitializationCubit>(() => InitializationCubit(chatRepository: sl()));
// Repository // Repository
sl.registerLazySingleton<ChatRepository>(() => ChatRepository(chatService: sl())); sl.registerLazySingleton<ChatRepository>(() => ChatRepository(chatService: sl()));

View File

@@ -1,6 +1,9 @@
import 'package:eatvio_app/app_router.dart'; 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/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/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/bloc/diary_edit_bloc.dart';
import 'package:eatvio_app/presentation/diary/diary_edit_screen/models/diary_edit_model.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/bloc/feed_bloc.dart';
@@ -40,64 +43,46 @@ class MyApp extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MultiBlocProvider( return MultiBlocProvider(
providers: [ providers: [
BlocProvider<ThemeBloc>( BlocProvider<InitializationCubit>(create: (context) => InitializationCubit(chatRepository: sl())..runInitialization()),
create: (context) => ThemeBloc( BlocProvider<ThemeBloc>(create: (context) => ThemeBloc(ThemeState(themeType: PrefUtils().getThemeData()))),
ThemeState(themeType: PrefUtils().getThemeData()), BlocProvider<MyProfileBloc>(create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent())),
), BlocProvider<FeedBloc>(create: (context) => FeedBloc(FeedState(myProfileModelObj: FeedModel()))..add(FeedInitialEvent())),
), BlocProvider<DiaryEditBloc>(create: (context) => DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel()))..add(DiaryEditInitialEvent())),
BlocProvider<MyProfileBloc>(
create: (context) => MyProfileBloc(
MyProfileState(
myProfileModelObj: MyProfileModel(),
),
)..add(MyProfileInitialEvent()),
),
BlocProvider<FeedBloc>(
create: (context) => FeedBloc(FeedState(myProfileModelObj: FeedModel()))
..add(
FeedInitialEvent(),
),
),
BlocProvider<DiaryEditBloc>(
create: (context) => DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel()))
..add(
DiaryEditInitialEvent(),
),
),
BlocProvider<ChatSelectBloc>( BlocProvider<ChatSelectBloc>(
create: (context) => ChatSelectBloc(ChatSelectState(chatSelectModelObj: ChatSelectModel())) create: (context) => ChatSelectBloc(ChatSelectState(chatSelectModelObj: ChatSelectModel()))..add(ChatSelectInitialEvent()),
..add(
ChatSelectInitialEvent(),
),
), ),
], ],
child: BlocBuilder<ThemeBloc, ThemeState>( child: BlocListener<InitializationCubit, InitializationState>(
builder: (context, state) { listener: (BuildContext context, InitializationState 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: BlocBuilder<ThemeBloc, ThemeState>(
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',
'',
),
],
),
);
},
),
), ),
); );
} }

View File

@@ -50,7 +50,7 @@ class AuthScreen extends StatelessWidget {
selector: (state) => state.emailController, selector: (state) => state.emailController,
builder: (context, emailController) { builder: (context, emailController) {
return CustomTextFormField(controller: emailController, textInputAction: TextInputAction.done); return CustomTextFormField(controller: emailController, textInputAction: TextInputAction.done);
}), },),
SizedBox(height: 22.v), SizedBox(height: 22.v),
Text("password".tr, style: theme.textTheme.bodyLarge), Text("password".tr, style: theme.textTheme.bodyLarge),
SizedBox(height: 5.v), SizedBox(height: 5.v),
@@ -61,7 +61,7 @@ class AuthScreen extends StatelessWidget {
obscureText: true, obscureText: true,
controller: passwordController, controller: passwordController,
); );
}), },),
SizedBox(height: 50.v), SizedBox(height: 50.v),
NextStepButton( NextStepButton(
text: "no_account".tr.toUpperCase(), text: "no_account".tr.toUpperCase(),
@@ -86,9 +86,9 @@ class AuthScreen extends StatelessWidget {
text: "authentificate".tr.toUpperCase(), text: "authentificate".tr.toUpperCase(),
margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v),
buttonStyle: CustomButtonStyles.outlinePrimaryTL15, buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
onPressed: onTapAuth(state, context)); onPressed: onTapAuth(state, context),);
}), },),
])))); ],),),),);
} }
onTapAuth(AuthState state, BuildContext context) { onTapAuth(AuthState state, BuildContext context) {
@@ -100,7 +100,7 @@ class AuthScreen extends StatelessWidget {
'password': state.passwordController!.text, 'password': state.passwordController!.text,
}; };
final response = await http.post(Uri.parse(dotenv.env['SERVER_ROOT']! + '/login'), 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); print(response.statusCode);
if (response.statusCode == 200) { if (response.statusCode == 200) {
var res = await jsonDecode(response.body); var res = await jsonDecode(response.body);

View File

@@ -29,15 +29,15 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
on<AddPortionEvent>(_addPortion); //пользователь нажимает "Добавить продукт" on<AddPortionEvent>(_addPortion); //пользователь нажимает "Добавить продукт"
on<RemovePortionEvent>(_removePortion); on<RemovePortionEvent>(_removePortion);
on<RemoveImageEvent>( on<RemoveImageEvent>(
_removeImage); // пользователь нажимает на крестик около продукта _removeImage,); // пользователь нажимает на крестик около продукта
on<UploadImages>(_uploadImages); //пользователь нажимает "Добавить фото" on<UploadImages>(_uploadImages); //пользователь нажимает "Добавить фото"
on<AddComment>(_addComment); //пользователь нажимает "Добавить комментарий" on<AddComment>(_addComment); //пользователь нажимает "Добавить комментарий"
on<ProductInput>( on<ProductInput>(
_inputProduct); //пользователь нажимает "Добавить комментарий" _inputProduct,); //пользователь нажимает "Добавить комментарий"
on<FinishDay>(_finishDay); //пользователь нажимает "Добавить комментарий" on<FinishDay>(_finishDay); //пользователь нажимает "Добавить комментарий"
on<SendModeration>(_sendModeration); on<SendModeration>(_sendModeration);
on<RefreshEvent>( on<RefreshEvent>(
reloadScreen); //пользователь нажимает "Добавить комментарий" reloadScreen,); //пользователь нажимает "Добавить комментарий"
on<ClearInput>(_clearInput); on<ClearInput>(_clearInput);
} }
@@ -89,7 +89,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
recommendedChartValues: currentState.recommendedChartValues, recommendedChartValues: currentState.recommendedChartValues,
consumedChartValues: currentState.consumedChartValues, consumedChartValues: currentState.consumedChartValues,
autocompleteList: currentState.autocompleteList, autocompleteList: currentState.autocompleteList,
diaryEditModelObj: currentState.diaryEditModelObj)); diaryEditModelObj: currentState.diaryEditModelObj,),);
} else { } else {
// Если текущее состояние - начальное, создаем новое загруженное состояние // Если текущее состояние - начальное, создаем новое загруженное состояние
final List<SelectionPopupModel> meals = final List<SelectionPopupModel> meals =
@@ -97,7 +97,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
emit(DiaryEditLoadedState( emit(DiaryEditLoadedState(
currentMeal: meals[0], currentMeal: meals[0],
portionController: SelectionPopupModel( portionController: SelectionPopupModel(
id: 0, title: "порций", isSelected: true), id: 0, title: "порций", isSelected: true,),
wakeupExpanded: true, wakeupExpanded: true,
moodExpanded: true, moodExpanded: true,
moderationExpanded: false, moderationExpanded: false,
@@ -125,7 +125,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
diaryDate: diaryDate, diaryDate: diaryDate,
autocompleteList: [], autocompleteList: [],
diaryEditModelObj: state.diaryEditModelObj diaryEditModelObj: state.diaryEditModelObj
?.copyWith(mealList: meals, portionList: fillPortions()))); ?.copyWith(mealList: meals, portionList: fillPortions()),),);
} }
} }
} catch (e) { } catch (e) {
@@ -177,10 +177,10 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
} }
fetchChartValues( fetchChartValues(
String token, int diaryID, Emitter<DiaryEditState> emit) async { String token, int diaryID, Emitter<DiaryEditState> emit,) async {
final responseChart = await http.get( final responseChart = await http.get(
Uri.parse( Uri.parse(
dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/dailyNutritionData/'), dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/dailyNutritionData/',),
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'Authorization': 'Bearer $token', 'Authorization': 'Bearer $token',
@@ -250,7 +250,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
final String diaryDate = diary['date'] ?? DateTime.now().toString(); final String diaryDate = diary['date'] ?? DateTime.now().toString();
final responseChart = await http.get( final responseChart = await http.get(
Uri.parse(dotenv.env['SERVER_ROOT']! + Uri.parse(dotenv.env['SERVER_ROOT']! +
'/diary/$diaryId/dailyNutritionData/'), '/diary/$diaryId/dailyNutritionData/',),
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'Authorization': 'Bearer $token', 'Authorization': 'Bearer $token',
@@ -258,7 +258,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
); );
if (responseChart.statusCode == 200) { if (responseChart.statusCode == 200) {
final recommendedChartValues = jsonDecode( final recommendedChartValues = jsonDecode(
responseChart.body)['dailyNutritionRecommendation']; responseChart.body,)['dailyNutritionRecommendation'];
final consumedChartValues = final consumedChartValues =
jsonDecode(responseChart.body)['dailyNutritionIntake']; jsonDecode(responseChart.body)['dailyNutritionIntake'];
final List<SelectionPopupModel> meals = final List<SelectionPopupModel> meals =
@@ -266,10 +266,10 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
try { try {
await Future(() => emit(DiaryEditLoadedState( await Future(() => emit(DiaryEditLoadedState(
diaryEditModelObj: state.diaryEditModelObj?.copyWith( diaryEditModelObj: state.diaryEditModelObj?.copyWith(
mealList: meals, portionList: fillPortions()), mealList: meals, portionList: fillPortions(),),
currentMeal: meals[0], currentMeal: meals[0],
portionController: SelectionPopupModel( portionController: SelectionPopupModel(
id: 0, title: "порций", isSelected: true), id: 0, title: "порций", isSelected: true,),
wakeupExpanded: true, wakeupExpanded: true,
moodExpanded: true, moodExpanded: true,
moderationExpanded: false, moderationExpanded: false,
@@ -301,7 +301,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
diaryDate: diaryDate, diaryDate: diaryDate,
isLoading: false, isLoading: false,
autocompleteList: [], autocompleteList: [],
))); ),),);
print("Updated"); print("Updated");
} catch (e) { } catch (e) {
@@ -312,11 +312,11 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
} }
} else { } else {
emit(DiaryEditErrorState( emit(DiaryEditErrorState(
'Ошибка при декодировании данных дневника')); 'Ошибка при декодировании данных дневника',),);
} }
} else { } else {
emit( emit(
DiaryEditErrorState('Некоторые необходимые данные отсутствуют.')); DiaryEditErrorState('Некоторые необходимые данные отсутствуют.'),);
} }
} else { } else {
emit(DiaryEditErrorState('Ошибка сервера: ${response.statusCode}')); emit(DiaryEditErrorState('Ошибка сервера: ${response.statusCode}'));
@@ -327,7 +327,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
} }
Future<void> _changeSatiety( Future<void> _changeSatiety(
ChangeSatiety event, Emitter<DiaryEditState> emit) async { ChangeSatiety event, Emitter<DiaryEditState> emit,) async {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
var updatedState = var updatedState =
@@ -338,7 +338,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
currentState.token, currentState.token,
event.selectedElement, event.selectedElement,
currentState.currentMeal?.id, currentState.currentMeal?.id,
currentState.diaryId); currentState.diaryId,);
if (response.statusCode == 200) { if (response.statusCode == 200) {
updatedState.selectedSatiety = event.selectedElement; updatedState.selectedSatiety = event.selectedElement;
@@ -364,12 +364,12 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
'Authorization': 'Bearer $token', 'Authorization': 'Bearer $token',
}, },
body: json.encode(credentials), body: json.encode(credentials),
encoding: utf8); encoding: utf8,);
return response; return response;
} }
Future<void> _changeMood( Future<void> _changeMood(
ChangeMood event, Emitter<DiaryEditState> emit) async { ChangeMood event, Emitter<DiaryEditState> emit,) async {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
var updatedState = var updatedState =
@@ -380,11 +380,11 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
currentState.token, currentState.token,
event.selectedElement, event.selectedElement,
currentState.currentMeal?.id, currentState.currentMeal?.id,
currentState.diaryId); currentState.diaryId,);
if (response.statusCode == 200) { if (response.statusCode == 200) {
print( 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; updatedState.selectedMood = event.selectedElement;
emit(updatedState); // Передаем обновленное состояние в emit emit(updatedState); // Передаем обновленное состояние в emit
} }
@@ -409,17 +409,17 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
'Authorization': 'Bearer $token', 'Authorization': 'Bearer $token',
}, },
body: json.encode(credentials), body: json.encode(credentials),
encoding: utf8); encoding: utf8,);
return response; return response;
} }
FutureOr<void> _changeWakeup( FutureOr<void> _changeWakeup(
WakeupEvent event, Emitter<DiaryEditState> emit) async { WakeupEvent event, Emitter<DiaryEditState> emit,) async {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
var response = await sendWakeupData( var response = await sendWakeupData(
currentState.token, event.selectedTime, currentState.diaryId); currentState.token, event.selectedTime, currentState.diaryId,);
if (response.statusCode == 200) { if (response.statusCode == 200) {
await reloadScreen(event, emit); await reloadScreen(event, emit);
var updatedState = var updatedState =
@@ -432,11 +432,11 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
} }
FutureOr<void> _changeRetire( FutureOr<void> _changeRetire(
RetireEvent event, Emitter<DiaryEditState> emit) async { RetireEvent event, Emitter<DiaryEditState> emit,) async {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
var response = await sendRetireData( var response = await sendRetireData(
currentState.token, event.selectedTime, currentState.diaryId); currentState.token, event.selectedTime, currentState.diaryId,);
if (response.statusCode == 200) { if (response.statusCode == 200) {
await reloadScreen(event, emit); await reloadScreen(event, emit);
var updatedState = var updatedState =
@@ -467,13 +467,13 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
'Authorization': 'Bearer $token', 'Authorization': 'Bearer $token',
}, },
body: json.encode(credentials), body: json.encode(credentials),
encoding: utf8); encoding: utf8,);
return response; return response;
} }
Future<http.Response> sendRetireData( Future<http.Response> 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'; String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill';
final formatter = DateFormat('HH:mm'); final formatter = DateFormat('HH:mm');
final retireString = final retireString =
@@ -488,13 +488,13 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
'Authorization': 'Bearer $token', 'Authorization': 'Bearer $token',
}, },
body: json.encode(credentials), body: json.encode(credentials),
encoding: utf8); encoding: utf8,);
return response; return response;
} }
FutureOr<void> _changeMealTime( FutureOr<void> _changeMealTime(
ChangeMealTime event, Emitter<DiaryEditState> emit) async { ChangeMealTime event, Emitter<DiaryEditState> emit,) async {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
var updatedState = currentState.copyWith(mealTimeController: event.time); var updatedState = currentState.copyWith(mealTimeController: event.time);
@@ -522,18 +522,18 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
'Authorization': 'Bearer $token', 'Authorization': 'Bearer $token',
}, },
body: json.encode(credentials), body: json.encode(credentials),
encoding: utf8); encoding: utf8,);
return response; return response;
} }
FutureOr<void> _changeMeal( FutureOr<void> _changeMeal(
ChangeMeal event, Emitter<DiaryEditState> emit) async { ChangeMeal event, Emitter<DiaryEditState> emit,) async {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
final meal = currentState.meals?.firstWhere( final meal = currentState.meals?.firstWhere(
(meal) => meal['id'] == event.value.id, (meal) => meal['id'] == event.value.id,
orElse: () => null); orElse: () => null,);
int? id = event.value.id; int? id = event.value.id;
print(meal['photos']); print(meal['photos']);
DiaryEditLoadedState updatedState = currentState.copyWith( DiaryEditLoadedState updatedState = currentState.copyWith(
@@ -542,7 +542,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
photos: meal['photos'], photos: meal['photos'],
mealTimeController: toTime(meal['time'] ?? "1$id:00"), mealTimeController: toTime(meal['time'] ?? "1$id:00"),
selectedMood: meal['mood'], selectedMood: meal['mood'],
selectedSatiety: meal['satiety']); selectedSatiety: meal['satiety'],);
print(updatedState.photos); print(updatedState.photos);
emit(updatedState); emit(updatedState);
} }
@@ -550,7 +550,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
FutureOr<void> _clearInput( FutureOr<void> _clearInput(
ClearInput event, Emitter<DiaryEditState> emit) { ClearInput event, Emitter<DiaryEditState> emit,) {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
DiaryEditLoadedState updatedState = currentState.copyWith( DiaryEditLoadedState updatedState = currentState.copyWith(
@@ -560,7 +560,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
} }
FutureOr<void> _changePortion( FutureOr<void> _changePortion(
ChangePortion event, Emitter<DiaryEditState> emit) { ChangePortion event, Emitter<DiaryEditState> emit,) {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
DiaryEditLoadedState updatedState = currentState.copyWith( DiaryEditLoadedState updatedState = currentState.copyWith(
@@ -571,7 +571,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
} }
FutureOr<void> _toggleMood( FutureOr<void> _toggleMood(
ToggleMoodExpandedEvent event, Emitter<DiaryEditState> emit) { ToggleMoodExpandedEvent event, Emitter<DiaryEditState> emit,) {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
@@ -581,7 +581,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
} }
FutureOr<void> _toggleWakeup( FutureOr<void> _toggleWakeup(
ToggleWakeupExpandedEvent event, Emitter<DiaryEditState> emit) { ToggleWakeupExpandedEvent event, Emitter<DiaryEditState> emit,) {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
@@ -591,7 +591,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
} }
FutureOr<void> _addPortion( FutureOr<void> _addPortion(
AddPortionEvent event, Emitter<DiaryEditState> emit) async { AddPortionEvent event, Emitter<DiaryEditState> emit,) async {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
@@ -609,13 +609,13 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
await reloadScreen(event, emit); await reloadScreen(event, emit);
} else { } else {
print( print(
'Failed to add portion. Status Code: ${response.statusCode} ${response.body}'); 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}',);
} }
} }
} }
FutureOr<http.Response> sendPortionData(String? token, String? name, FutureOr<http.Response> 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 = String url =
'${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/create'; '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/create';
@@ -639,14 +639,14 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
} }
Future<void> _inputProduct( Future<void> _inputProduct(
ProductInput event, Emitter<DiaryEditState> emit) async { ProductInput event, Emitter<DiaryEditState> emit,) async {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
String? token = currentState.token; String? token = currentState.token;
final Map<String, dynamic> credentials = {'name': event.input}; final Map<String, dynamic> credentials = {'name': event.input};
final uri = Uri.parse( 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( final response = await http.get(
uri, uri,
@@ -679,7 +679,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
} }
Future<void> _removePortion( Future<void> _removePortion(
RemovePortionEvent event, Emitter<DiaryEditState> emit) async { RemovePortionEvent event, Emitter<DiaryEditState> emit,) async {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
@@ -697,13 +697,13 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
await reloadScreen(event, emit); await reloadScreen(event, emit);
} else { } else {
print( print(
'Failed to add portion. Status Code: ${response.statusCode} ${response.body}'); 'Failed to add portion. Status Code: ${response.statusCode} ${response.body}',);
} }
} }
} }
Future<http.Response> sendRemovePortion( Future<http.Response> sendRemovePortion(
String? token, int? portionID, int? mealID, int diaryID) async { String? token, int? portionID, int? mealID, int diaryID,) async {
String url = String url =
'${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete'; '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/portions/$portionID/delete';
@@ -720,7 +720,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
} }
FutureOr<void> _removeImage( FutureOr<void> _removeImage(
RemoveImageEvent event, Emitter<DiaryEditState> emit) async { RemoveImageEvent event, Emitter<DiaryEditState> emit,) async {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
@@ -736,13 +736,13 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
await reloadScreen(event, emit); await reloadScreen(event, emit);
} else { } else {
print( print(
'Failed to remove photo. Status Code: ${response.statusCode} ${response.body}'); 'Failed to remove photo. Status Code: ${response.statusCode} ${response.body}',);
} }
} }
} }
Future<http.Response> sendRemovePhoto(String? token, String? path, Future<http.Response> sendRemovePhoto(String? token, String? path,
String? photoID, int? mealID, int diaryID) async { String? photoID, int? mealID, int diaryID,) async {
String url = String url =
'${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete'; '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealID/photo/delete';
final Map<String, dynamic> credentials = { final Map<String, dynamic> credentials = {
@@ -781,7 +781,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
} }
Future<http.Response> sendFinishDay(String? token, int diaryID, Future<http.Response> 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 formatter = DateFormat('HH:mm');
final wakeupString = final wakeupString =
formatter.format(DateTime(2022, 1, 1, wakeup!.hour, wakeup.minute)); formatter.format(DateTime(2022, 1, 1, wakeup!.hour, wakeup.minute));
@@ -810,19 +810,19 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
} }
Future<void> _uploadImages( Future<void> _uploadImages(
UploadImages event, Emitter<DiaryEditState> emit) async { UploadImages event, Emitter<DiaryEditState> emit,) async {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
emit(currentState.copyWith(isLoading: true)); emit(currentState.copyWith(isLoading: true));
await uploadImageToServer(event.image.path, currentState.diaryId, await uploadImageToServer(event.image.path, currentState.diaryId,
currentState.currentMeal!.id!, currentState.token); currentState.currentMeal!.id!, currentState.token,);
await reloadScreen(event, emit); await reloadScreen(event, emit);
} }
} }
Future<String> uploadImageToServer( Future<String> uploadImageToServer(
String imagePath, int diaryID, int mealId, String? token) async { String imagePath, int diaryID, int mealId, String? token,) async {
String url = String url =
'${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload'; '${dotenv.env['SERVER_ROOT']!}/diary/$diaryID/meal/$mealId/photo/upload';
@@ -841,12 +841,12 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
return imageUrl; return imageUrl;
} else { } else {
throw Exception( throw Exception(
'Failed to upload image. Status code: ${streamedResponse.statusCode}}'); 'Failed to upload image. Status code: ${streamedResponse.statusCode}}',);
} }
} }
FutureOr<void> _sendModeration( FutureOr<void> _sendModeration(
SendModeration event, Emitter<DiaryEditState> emit) async { SendModeration event, Emitter<DiaryEditState> emit,) async {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
final response = await _sendModerationData( final response = await _sendModerationData(
@@ -871,9 +871,9 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
String proteins_on_100gr, String proteins_on_100gr,
String fats_on_100gr, String fats_on_100gr,
String carbohydrates_on_100gr, String carbohydrates_on_100gr,
String? token) async { String? token,) async {
final Uri url = Uri.parse( 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']!}'); final Uri serverURL = Uri.parse('${dotenv.env['SERVER_ROOT']!}');
String host = serverURL.host; String host = serverURL.host;
final Map<String, String> credentials = { final Map<String, String> credentials = {
@@ -901,12 +901,12 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
return response; return response;
} else { } else {
throw Exception( throw Exception(
'Failed to send a product for moderation ${response.statusCode}'); 'Failed to send a product for moderation ${response.statusCode}',);
} }
} }
FutureOr<void> _addComment( FutureOr<void> _addComment(
AddComment event, Emitter<DiaryEditState> emit) async { AddComment event, Emitter<DiaryEditState> emit,) async {
if (state is DiaryEditLoadedState) { if (state is DiaryEditLoadedState) {
var currentState = state as DiaryEditLoadedState; var currentState = state as DiaryEditLoadedState;
var updatedState = currentState.copyWith( var updatedState = currentState.copyWith(
@@ -915,7 +915,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
// Отправляем данные по HTTP маршруту и ждем ответ // Отправляем данные по HTTP маршруту и ждем ответ
var response = await sendCommentData( var response = await sendCommentData(
currentState.token, event.comment, currentState.diaryId); currentState.token, event.comment, currentState.diaryId,);
if (response.statusCode == 200) { if (response.statusCode == 200) {
emit(updatedState); // Передаем обновленное состояние в emit emit(updatedState); // Передаем обновленное состояние в emit
@@ -924,7 +924,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
} }
Future<http.Response> sendCommentData( Future<http.Response> 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'; String url = dotenv.env['SERVER_ROOT']! + '/diary/$diaryID/retire/fill';
final Map<String, dynamic> credentials = { final Map<String, dynamic> credentials = {
'comment': comment, 'comment': comment,
@@ -936,7 +936,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
'Authorization': 'Bearer $token', 'Authorization': 'Bearer $token',
}, },
body: json.encode(credentials), body: json.encode(credentials),
encoding: utf8); encoding: utf8,);
return response; return response;
} }

View File

@@ -159,7 +159,7 @@ class SendModeration extends DiaryEditEvent {
required this.energyOn100gr, required this.energyOn100gr,
required this.proteinsOn100gr, required this.proteinsOn100gr,
required this.fatsOn100gr, required this.fatsOn100gr,
required this.carbohydratesOn100gr}); required this.carbohydratesOn100gr,});
String name; String name;
String energyOn100gr; String energyOn100gr;
String proteinsOn100gr; String proteinsOn100gr;

View File

@@ -47,7 +47,7 @@ class DiaryEditLoadedState extends DiaryEditState {
required this.selectedSatiety, required this.selectedSatiety,
required this.moderationExpanded, required this.moderationExpanded,
required this.wakeupExpanded, required this.wakeupExpanded,
required this.moodExpanded}) required this.moodExpanded,})
: super(diaryEditModelObj: null); : super(diaryEditModelObj: null);
DiaryEditModel? diaryEditModelObj; DiaryEditModel? diaryEditModelObj;
@@ -109,7 +109,7 @@ class DiaryEditLoadedState extends DiaryEditState {
moderationExpanded, moderationExpanded,
isLoading, isLoading,
isAdded, isAdded,
currentMeal currentMeal,
]; ];
DiaryEditLoadedState copyWith({ DiaryEditLoadedState copyWith({
DiaryEditModel? diaryEditModelObj, DiaryEditModel? diaryEditModelObj,
@@ -174,7 +174,7 @@ class DiaryEditLoadedState extends DiaryEditState {
moderationExpanded: moderationExpanded ?? this.moderationExpanded, moderationExpanded: moderationExpanded ?? this.moderationExpanded,
moodExpanded: moodExpanded ?? this.moodExpanded, moodExpanded: moodExpanded ?? this.moodExpanded,
isAdded: isAdded ?? this.isAdded, isAdded: isAdded ?? this.isAdded,
isLoading: isLoading ?? this.isLoading); isLoading: isLoading ?? this.isLoading,);
} }
} }

View File

@@ -21,7 +21,7 @@ class DiaryEditScreen extends StatelessWidget {
static Widget builder(BuildContext context) { static Widget builder(BuildContext context) {
return BlocProvider<DiaryEditBloc>( return BlocProvider<DiaryEditBloc>(
create: (context) => DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel()))..add(DiaryEditInitialEvent()), child: DiaryEditScreen()); create: (context) => DiaryEditBloc(DiaryEditState(diaryEditModelObj: DiaryEditModel()))..add(DiaryEditInitialEvent()), child: DiaryEditScreen(),);
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -221,7 +221,7 @@ class DiaryEditScreen extends StatelessWidget {
Icon( Icon(
Icons.photo_library, Icons.photo_library,
color: appTheme.blueGray300, color: appTheme.blueGray300,
) ),
], ],
), ),
), ),
@@ -332,7 +332,7 @@ class DiaryEditScreen extends StatelessWidget {
defaultValue: diaryEditModelObj?.mealList[0], defaultValue: diaryEditModelObj?.mealList[0],
onChanged: changeMeal(context, state), onChanged: changeMeal(context, state),
); );
})), },),),
SizedBox(height: 20.v), SizedBox(height: 20.v),
Padding( Padding(
padding: EdgeInsets.symmetric(horizontal: 10.h), padding: EdgeInsets.symmetric(horizontal: 10.h),
@@ -381,7 +381,7 @@ class DiaryEditScreen extends StatelessWidget {
), ),
), ),
); );
}), },),
), ),
SizedBox(height: 20.v), SizedBox(height: 20.v),
if (state.moderationExpanded) if (state.moderationExpanded)
@@ -492,9 +492,9 @@ class DiaryEditScreen extends StatelessWidget {
return Container(); // Возвращаем пустой контейнер, если состояние не является DiaryEditLoadedState return Container(); // Возвращаем пустой контейнер, если состояние не является DiaryEditLoadedState
} }
}, },
) ),
], ],
)); ),);
} }
openCaloriesDialog(BuildContext context, DiaryEditLoadedState state) { openCaloriesDialog(BuildContext context, DiaryEditLoadedState state) {
@@ -543,7 +543,7 @@ class DiaryEditScreen extends StatelessWidget {
), ),
TextButton( TextButton(
onPressed: triggerModeration(context, state.productNameController!.text, state.caloriesController!.text, state.proteinsController!.text, 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('Отправить'), child: Text('Отправить'),
), ),
], ],
@@ -553,11 +553,11 @@ class DiaryEditScreen extends StatelessWidget {
} }
triggerModeration(BuildContext context, String name, String energyOn100gr, String proteinsOn100gr, String fatsOn100gr, String carbohydratesOn100gr, triggerModeration(BuildContext context, String name, String energyOn100gr, String proteinsOn100gr, String fatsOn100gr, String carbohydratesOn100gr,
BuildContext dialogContext) { BuildContext dialogContext,) {
return () { return () {
// Call function to send moderation with the entered values // Call function to send moderation with the entered values
context.read<DiaryEditBloc>().add(SendModeration( context.read<DiaryEditBloc>().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 Navigator.of(dialogContext).pop(); // Dismiss the dialog
}; };
} }
@@ -647,7 +647,7 @@ class DiaryEditScreen extends StatelessWidget {
child: Text( 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, style: CustomTextStyles.titleMedium16,
)), ),),
Padding( Padding(
padding: EdgeInsets.only( padding: EdgeInsets.only(
left: 20.h, left: 20.h,
@@ -667,7 +667,7 @@ class DiaryEditScreen extends StatelessWidget {
Icons.close, Icons.close,
color: appTheme.blueGray300, color: appTheme.blueGray300,
), ),
)), ),),
], ],
), ),
); );
@@ -783,26 +783,26 @@ class DiaryEditScreen extends StatelessWidget {
BarChartRodData( BarChartRodData(
toY: consumedValues[0] / recommendedValues[0] * 100, 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,
) ),
]), ],),
BarChartGroupData(x: 1, barRods: [ BarChartGroupData(x: 1, barRods: [
BarChartRodData( BarChartRodData(
toY: consumedValues[1] / recommendedValues[1] * 100, 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,
) ),
]), ],),
BarChartGroupData(x: 2, barRods: [ BarChartGroupData(x: 2, barRods: [
BarChartRodData( BarChartRodData(
toY: consumedValues[2] / recommendedValues[2] * 100, 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,
) ),
]), ],),
BarChartGroupData(x: 3, barRods: [ BarChartGroupData(x: 3, barRods: [
BarChartRodData( BarChartRodData(
toY: consumedValues[3] / recommendedValues[3] * 100, 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,
) ),
]), ],),
], ],
), ),
), ),
@@ -909,7 +909,7 @@ class DiaryEditScreen extends StatelessWidget {
Text( Text(
"*Превышенная суточная норма", "*Превышенная суточная норма",
style: theme.textTheme.labelLarge, style: theme.textTheme.labelLarge,
) ),
], ],
), ),
); );
@@ -1147,7 +1147,7 @@ class DiaryEditScreen extends StatelessWidget {
// Остальные элементы шкалы // Остальные элементы шкалы
], ],
), ),
])); ],),);
} }
changeMood(BuildContext context, int satiety) { changeMood(BuildContext context, int satiety) {

File diff suppressed because one or more lines are too long

View File

@@ -10,7 +10,7 @@ class DietCreateScreen extends StatelessWidget {
final dietID = ModalRoute.of(context)!.settings.arguments; final dietID = ModalRoute.of(context)!.settings.arguments;
return BlocProvider<DietCreateBloc>( return BlocProvider<DietCreateBloc>(
create: (context) => DietCreateBloc(DietCreateState(dietModelObj: DietCreateModel(dietID: dietID.toString())))..add(DietCreateInitialEvent()), create: (context) => DietCreateBloc(DietCreateState(dietModelObj: DietCreateModel(dietID: dietID.toString())))..add(DietCreateInitialEvent()),
child: DietCreateScreen()); child: DietCreateScreen(),);
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -80,10 +80,10 @@ class DietCreateScreen extends StatelessWidget {
ElevatedButton( ElevatedButton(
onPressed: () => context.read<DietCreateBloc>().add(CreateDiet()), onPressed: () => context.read<DietCreateBloc>().add(CreateDiet()),
child: Text('Создать'), child: Text('Создать'),
) ),
]), ],),
) ),
]), ],),
), ),
), ),
); );

View File

@@ -49,13 +49,13 @@ class DietEditBloc extends Bloc<DietEditEvent, DietEditState> {
diet: currentState.diet, diet: currentState.diet,
name: currentState.name, name: currentState.name,
duration: currentState.duration, duration: currentState.duration,
details: currentState.details)); details: currentState.details,),);
} else { } else {
emit(DietEditLoadedState( emit(DietEditLoadedState(
diet: data, diet: data,
name: TextEditingController(text: data['name']), name: TextEditingController(text: data['name']),
details: TextEditingController(text: data['details']), details: TextEditingController(text: data['details']),
duration: TextEditingController(text: data['duration']))); duration: TextEditingController(text: data['duration']),),);
} }
} else { } else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку

View File

@@ -23,7 +23,7 @@ class DietEditState extends Equatable {
class DietEditLoadedState extends DietEditState { class DietEditLoadedState extends DietEditState {
DietEditLoadedState( DietEditLoadedState(
{this.dietModelObj, this.diet, this.name, this.details, this.duration}); {this.dietModelObj, this.diet, this.name, this.details, this.duration,});
DietEditModel? dietModelObj; DietEditModel? dietModelObj;
Map<String, dynamic>? diet; Map<String, dynamic>? diet;

View File

@@ -12,7 +12,7 @@ class DietEditScreen extends StatelessWidget {
final dietID = ModalRoute.of(context)!.settings.arguments; final dietID = ModalRoute.of(context)!.settings.arguments;
return BlocProvider<DietEditBloc>( return BlocProvider<DietEditBloc>(
create: (context) => DietEditBloc(DietEditState(dietModelObj: DietEditModel(dietID: dietID.toString())))..add(DietEditInitialEvent()), create: (context) => DietEditBloc(DietEditState(dietModelObj: DietEditModel(dietID: dietID.toString())))..add(DietEditInitialEvent()),
child: DietEditScreen()); child: DietEditScreen(),);
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -98,10 +98,10 @@ class DietEditScreen extends StatelessWidget {
ElevatedButton( ElevatedButton(
onPressed: () => context.read<DietEditBloc>().add(EditDiet()), onPressed: () => context.read<DietEditBloc>().add(EditDiet()),
child: Text('Сохранить'), child: Text('Сохранить'),
) ),
], ],
), ),
) ),
], ],
), ),
), ),

View File

@@ -50,12 +50,12 @@ class DietSelectBloc extends Bloc<DietSelectEvent, DietSelectState> {
emit((currentState).copyWith( emit((currentState).copyWith(
posts: data, posts: data,
myProfileModelObj: currentState.myProfileModelObj, myProfileModelObj: currentState.myProfileModelObj,
)); ),);
} else { } else {
print('Got unloaded'); print('Got unloaded');
emit(DietSelectLoadedState( emit(DietSelectLoadedState(
posts: data, posts: data,
)); ),);
} }
} else { } else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку

View File

@@ -13,7 +13,7 @@ import 'package:flutter/material.dart';
class DietSelectScreen extends StatelessWidget { class DietSelectScreen extends StatelessWidget {
static Widget builder(BuildContext context) { static Widget builder(BuildContext context) {
return BlocProvider<DietSelectBloc>( return BlocProvider<DietSelectBloc>(
create: (context) => DietSelectBloc(DietSelectState(myProfileModelObj: DietSelectModel()))..add(DietSelectInitialEvent()), child: DietSelectScreen()); create: (context) => DietSelectBloc(DietSelectState(myProfileModelObj: DietSelectModel()))..add(DietSelectInitialEvent()), child: DietSelectScreen(),);
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -95,14 +95,14 @@ class DietSelectScreen extends StatelessWidget {
onTap: () => GoRouter.of(context).goNamed('dietCreateScreen'), onTap: () => GoRouter.of(context).goNamed('dietCreateScreen'),
child: Icon(Icons.create_outlined), child: Icon(Icons.create_outlined),
), ),
) ),
], ],
), ),
), ),
), ),
), ),
SizedBox(height: 20), SizedBox(height: 20),
_buildDietList(context, state) _buildDietList(context, state),
], ],
), ),
), ),
@@ -161,7 +161,7 @@ class DietSelectScreen extends StatelessWidget {
), ),
child: Icon(Icons.edit), child: Icon(Icons.edit),
), ),
)); ),);
}, },
); );
} }

View File

@@ -13,7 +13,7 @@ class DietScreen extends StatelessWidget {
static Widget builder(BuildContext context) { static Widget builder(BuildContext context) {
final dietID = ModalRoute.of(context)!.settings.arguments; final dietID = ModalRoute.of(context)!.settings.arguments;
return BlocProvider<DietBloc>( return BlocProvider<DietBloc>(
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) { Widget build(BuildContext context) {
@@ -104,9 +104,9 @@ class DietScreen extends StatelessWidget {
child: Text('Удалить'), child: Text('Удалить'),
), ),
], ],
) ),
]), ],),
) ),
], ],
), ),
), ),

View File

@@ -37,18 +37,18 @@ class BlogPostCreateBloc
title: currentState.title, title: currentState.title,
description: currentState.description, description: currentState.description,
youtube_url: currentState.youtube_url, youtube_url: currentState.youtube_url,
token: currentState.token)); token: currentState.token,),);
} else { } else {
emit(BlogPostCreateLoadedState( emit(BlogPostCreateLoadedState(
token: token, token: token,
title: TextEditingController(), title: TextEditingController(),
description: TextEditingController(), description: TextEditingController(),
youtube_url: TextEditingController())); youtube_url: TextEditingController(),),);
} }
} }
FutureOr<void> _createBlogPost( FutureOr<void> _createBlogPost(
CreateBlogPost event, Emitter<BlogPostCreateState> emit) async { CreateBlogPost event, Emitter<BlogPostCreateState> emit,) async {
if (state is BlogPostCreateLoadedState) { if (state is BlogPostCreateLoadedState) {
var currentState = state as BlogPostCreateLoadedState; var currentState = state as BlogPostCreateLoadedState;
@@ -62,7 +62,7 @@ class BlogPostCreateBloc
AppRouter.navigatorKey.currentContext?.goNamed('feedScreen'); AppRouter.navigatorKey.currentContext?.goNamed('feedScreen');
} else { } else {
print( print(
'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}'); 'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}',);
} }
} }
} }

View File

@@ -27,7 +27,7 @@ class BlogPostCreateLoadedState extends BlogPostCreateState {
this.blog_postModelObj, this.blog_postModelObj,
this.title, this.title,
this.description, this.description,
this.youtube_url}); this.youtube_url,});
BlogPostCreateModel? blog_postModelObj; BlogPostCreateModel? blog_postModelObj;
TextEditingController? title; TextEditingController? title;
@@ -42,7 +42,7 @@ class BlogPostCreateLoadedState extends BlogPostCreateState {
TextEditingController? title, TextEditingController? title,
TextEditingController? description, TextEditingController? description,
TextEditingController? youtube_url, TextEditingController? youtube_url,
String? token}) { String? token,}) {
return BlogPostCreateLoadedState( return BlogPostCreateLoadedState(
blog_postModelObj: blog_postModelObj ?? this.blog_postModelObj, blog_postModelObj: blog_postModelObj ?? this.blog_postModelObj,
title: title ?? this.title, title: title ?? this.title,

View File

@@ -13,7 +13,7 @@ class BlogPostCreateScreen extends StatelessWidget {
return BlocProvider<BlogPostCreateBloc>( return BlocProvider<BlogPostCreateBloc>(
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()), ..add(BlogPostCreateInitialEvent()),
child: BlogPostCreateScreen()); child: BlogPostCreateScreen(),);
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -100,7 +100,7 @@ class BlogPostCreateScreen extends StatelessWidget {
), ),
], ],
), ),
) ),
], ],
), ),
), ),

View File

@@ -49,13 +49,13 @@ class BlogPostEditBloc extends Bloc<BlogPostEditEvent, BlogPostEditState> {
blog_post: currentState.blog_post, blog_post: currentState.blog_post,
title: currentState.title, title: currentState.title,
description: currentState.description, description: currentState.description,
youtube_url: currentState.youtube_url)); youtube_url: currentState.youtube_url,),);
} else { } else {
emit(BlogPostEditLoadedState( emit(BlogPostEditLoadedState(
blog_post: data, blog_post: data,
title: TextEditingController(text: data['title']), title: TextEditingController(text: data['title']),
description: TextEditingController(text: data['description']), description: TextEditingController(text: data['description']),
youtube_url: TextEditingController(text: data['youtube_url']))); youtube_url: TextEditingController(text: data['youtube_url']),),);
} }
} else { } else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку

View File

@@ -27,7 +27,7 @@ class BlogPostEditLoadedState extends BlogPostEditState {
this.blog_post, this.blog_post,
this.title, this.title,
this.description, this.description,
this.youtube_url}); this.youtube_url,});
BlogPostEditModel? blog_postModelObj; BlogPostEditModel? blog_postModelObj;
Map<String, dynamic>? blog_post; Map<String, dynamic>? blog_post;

View File

@@ -12,7 +12,7 @@ class BlogPostEditScreen extends StatelessWidget {
return BlocProvider<BlogPostEditBloc>( return BlocProvider<BlogPostEditBloc>(
create: (context) => create: (context) =>
BlogPostEditBloc(BlogPostEditState(blog_postModelObj: BlogPostEditModel(blog_postID: blog_postID.toString())))..add(BlogPostEditInitialEvent()), BlogPostEditBloc(BlogPostEditState(blog_postModelObj: BlogPostEditModel(blog_postID: blog_postID.toString())))..add(BlogPostEditInitialEvent()),
child: BlogPostEditScreen()); child: BlogPostEditScreen(),);
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -106,10 +106,10 @@ class BlogPostEditScreen extends StatelessWidget {
ElevatedButton( ElevatedButton(
onPressed: () => context.read<BlogPostEditBloc>().add(EditBlogPost()), onPressed: () => context.read<BlogPostEditBloc>().add(EditBlogPost()),
child: Text('Сохранить'), child: Text('Сохранить'),
) ),
], ],
), ),
) ),
], ],
), ),
), ),

View File

@@ -50,14 +50,14 @@ class BlogPostBloc extends Bloc<BlogPostEvent, BlogPostState> {
blog_post: currentState.blog_post, blog_post: currentState.blog_post,
author: currentState.author, author: currentState.author,
comments: currentState.comments, comments: currentState.comments,
token: currentState.token)); token: currentState.token,),);
} else { } else {
emit(BlogPostLoadedState( emit(BlogPostLoadedState(
blog_post: data, blog_post: data,
token: token, token: token,
commentController: TextEditingController(), commentController: TextEditingController(),
author: await _fetchAuthor(data['id']), author: await _fetchAuthor(data['id']),
comments: fillCommentList(await _fetchComments(data['id'])))); comments: fillCommentList(await _fetchComments(data['id'])),),);
} }
} else { } else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку
@@ -74,15 +74,15 @@ class BlogPostBloc extends Bloc<BlogPostEvent, BlogPostState> {
} }
FutureOr<void> _createComment( FutureOr<void> _createComment(
CreateComment event, Emitter<BlogPostState> emit) async { CreateComment event, Emitter<BlogPostState> emit,) async {
if (state is BlogPostLoadedState) { if (state is BlogPostLoadedState) {
var currentState = state as BlogPostLoadedState; var currentState = state as BlogPostLoadedState;
// Отправляем данные по HTTP маршруту и ждем ответ // Отправляем данные по HTTP маршруту и ждем ответ
var response = await _sendCommentData( var response = await _sendCommentData(
currentState.token, event.body, currentState.blog_post?['id']); currentState.token, event.body, currentState.blog_post?['id'],);
if (response.statusCode == 200) { if (response.statusCode == 200) {
var updatedComments = fillCommentList( var updatedComments = fillCommentList(
await _fetchComments(currentState.blog_post?['id'])); await _fetchComments(currentState.blog_post?['id']),);
var updatedState = currentState.copyWith( var updatedState = currentState.copyWith(
comments: updatedComments, comments: updatedComments,
commentController: commentController:
@@ -94,7 +94,7 @@ class BlogPostBloc extends Bloc<BlogPostEvent, BlogPostState> {
} }
FutureOr<void> _deleteEntry( FutureOr<void> _deleteEntry(
DeleteEntry event, Emitter<BlogPostState> emit) async { DeleteEntry event, Emitter<BlogPostState> emit,) async {
final box = await Hive.openBox('token'); final box = await Hive.openBox('token');
final token = box.get('token'); final token = box.get('token');
if (token == null) { if (token == null) {
@@ -158,13 +158,13 @@ class BlogPostBloc extends Bloc<BlogPostEvent, BlogPostState> {
username: comments[i]['name'], username: comments[i]['name'],
dateText: DateFormat('dd.MM') dateText: DateFormat('dd.MM')
.format(DateTime.parse(comments[i]['updated_at'])), .format(DateTime.parse(comments[i]['updated_at'])),
greetingText: comments[i]['body'])); greetingText: comments[i]['body'],),);
} }
return list; return list;
} }
Future<http.Response> _sendCommentData( Future<http.Response> _sendCommentData(
String? token, String body, int id) async { String? token, String body, int id,) async {
String url = dotenv.env['SERVER_ROOT']! + '/feed/createComment/$id'; String url = dotenv.env['SERVER_ROOT']! + '/feed/createComment/$id';
final Map<String, dynamic> credentials = { final Map<String, dynamic> credentials = {
'id': id, 'id': id,
@@ -177,7 +177,7 @@ class BlogPostBloc extends Bloc<BlogPostEvent, BlogPostState> {
'Authorization': 'Bearer $token', 'Authorization': 'Bearer $token',
}, },
body: json.encode(credentials), body: json.encode(credentials),
encoding: utf8); encoding: utf8,);
return response; return response;
} }

View File

@@ -28,7 +28,7 @@ class BlogPostLoadedState extends BlogPostState {
this.author, this.author,
this.comments, this.comments,
this.token, this.token,
this.commentController}); this.commentController,});
BlogPostModel? blog_postModelObj; BlogPostModel? blog_postModelObj;
Map<String, dynamic>? blog_post; Map<String, dynamic>? blog_post;
@@ -44,14 +44,14 @@ class BlogPostLoadedState extends BlogPostState {
Map<String, dynamic>? author, Map<String, dynamic>? author,
TextEditingController? commentController, TextEditingController? commentController,
String? token, String? token,
List<dynamic>? comments}) { List<dynamic>? comments,}) {
return BlogPostLoadedState( return BlogPostLoadedState(
blog_postModelObj: blog_postModelObj ?? this.blog_postModelObj, blog_postModelObj: blog_postModelObj ?? this.blog_postModelObj,
blog_post: blog_post ?? this.blog_post, blog_post: blog_post ?? this.blog_post,
author: author ?? this.author, author: author ?? this.author,
comments: comments ?? this.comments, comments: comments ?? this.comments,
token: token ?? this.token, token: token ?? this.token,
commentController: commentController ?? this.commentController); commentController: commentController ?? this.commentController,);
} }
} }

View File

@@ -197,7 +197,7 @@ class BlogPostScreen extends StatelessWidget {
child: Text( child: Text(
DateFormat('dd.MM.yyyy').format(DateTime.parse(state.blog_post?['updated_at'])), DateFormat('dd.MM.yyyy').format(DateTime.parse(state.blog_post?['updated_at'])),
style: theme.textTheme.bodyMedium, style: theme.textTheme.bodyMedium,
)), ),),
SizedBox(height: 16.0), SizedBox(height: 16.0),
Row(children: [ Row(children: [
Padding( Padding(
@@ -210,8 +210,8 @@ class BlogPostScreen extends StatelessWidget {
Text( Text(
"Нравится", "Нравится",
style: CustomTextStyles.titleMediumSemiBold, style: CustomTextStyles.titleMediumSemiBold,
) ),
]), ],),
), ),
Spacer(), Spacer(),
Padding( Padding(
@@ -224,10 +224,10 @@ class BlogPostScreen extends StatelessWidget {
Text( Text(
"Поделиться", "Поделиться",
style: CustomTextStyles.titleMediumSemiBold, style: CustomTextStyles.titleMediumSemiBold,
) ),
])) ],),),
]), ],),
]), ],),
); );
} }
@@ -356,7 +356,7 @@ class BlogPostScreen extends StatelessWidget {
), ),
onPressed: () => context.read<BlogPostBloc>().add(CreateComment(state.commentController!.text)), onPressed: () => context.read<BlogPostBloc>().add(CreateComment(state.commentController!.text)),
// Установите прозрачный фон // Установите прозрачный фон
) ),
], ],
), ),
], ],

View File

@@ -9,7 +9,7 @@ class CommentModel {
this.username, this.username,
this.dateText, this.dateText,
this.greetingText, this.greetingText,
required this.id}) { required this.id,}) {
userImage = userImage ?? ImageConstant.imageNotFound; userImage = userImage ?? ImageConstant.imageNotFound;
username = username; username = username;
dateText = dateText; dateText = dateText;

View File

@@ -82,7 +82,7 @@ class CommentWidget extends StatelessWidget {
commentModelObj.dateText!, commentModelObj.dateText!,
style: theme.textTheme.bodyMedium, style: theme.textTheme.bodyMedium,
), ),
) ),
], ],
), ),
), ),
@@ -99,7 +99,7 @@ class CommentWidget extends StatelessWidget {
imagePath: ImageConstant.imgSend, imagePath: ImageConstant.imgSend,
height: 30.v, height: 30.v,
width: 30.h, width: 30.h,
margin: EdgeInsets.only(left: 5)), margin: EdgeInsets.only(left: 5),),
], ],
), ),
); );

View File

@@ -50,12 +50,12 @@ class FeedBloc extends Bloc<FeedEvent, FeedState> {
emit((currentState).copyWith( emit((currentState).copyWith(
posts: data, posts: data,
myProfileModelObj: currentState.myProfileModelObj, myProfileModelObj: currentState.myProfileModelObj,
)); ),);
} else { } else {
print('Got unloaded'); print('Got unloaded');
emit(FeedLoadedState( emit(FeedLoadedState(
posts: data, posts: data,
)); ),);
} }
} else { } else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку

View File

@@ -56,7 +56,7 @@ class FeedScreen extends StatelessWidget {
SizedBox(height: 20), SizedBox(height: 20),
_buildMenu(context, state), _buildMenu(context, state),
SizedBox(height: 20), 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( Text(
"Комментировать", "Комментировать",
) ),
]), ],),
), ),
Spacer(), Spacer(),
Row(children: [ Row(children: [
@@ -246,18 +246,18 @@ class FeedScreen extends StatelessWidget {
), ),
Text( Text(
"Нравится", "Нравится",
) ),
]), ],),
Spacer(), Spacer(),
Padding( Padding(
padding: EdgeInsets.only(right: 4), padding: EdgeInsets.only(right: 4),
child: Icon(Icons.share_outlined), child: Icon(Icons.share_outlined),
), ),
]), ],),
], ],
), ),
), ),
])); ],),);
} }
Function onTapBack(BuildContext context) { Function onTapBack(BuildContext context) {

View File

@@ -24,7 +24,7 @@ class CustomSearchView extends StatelessWidget {
this.fillColor, this.fillColor,
this.filled = true, this.filled = true,
this.validator, this.validator,
this.onChanged}) this.onChanged,})
: super( : super(
key: key, key: key,
); );
@@ -76,7 +76,7 @@ class CustomSearchView extends StatelessWidget {
return alignment != null return alignment != null
? Align( ? Align(
alignment: alignment ?? Alignment.center, alignment: alignment ?? Alignment.center,
child: searchViewWidget(context)) child: searchViewWidget(context),)
: searchViewWidget(context); : searchViewWidget(context);
} }
@@ -113,7 +113,7 @@ class CustomSearchView extends StatelessWidget {
SizedBox( SizedBox(
child: Padding( child: Padding(
padding: EdgeInsets.only(left: 10), padding: EdgeInsets.only(left: 10),
child: Icon(Icons.search)), child: Icon(Icons.search),),
), ),
prefixIconConstraints: prefixConstraints ?? prefixIconConstraints: prefixConstraints ??
BoxConstraints( BoxConstraints(

View File

@@ -45,14 +45,14 @@ class GlossaryBloc extends Bloc<GlossaryEvent, GlossaryState> {
glossaryModelObj: currentState.glossaryModelObj, glossaryModelObj: currentState.glossaryModelObj,
token: currentState.token, token: currentState.token,
productGroups: currentState.productGroups, productGroups: currentState.productGroups,
productList: currentState.productList)); productList: currentState.productList,),);
} else { } else {
List<SelectionPopupModel> productGroupsModel = List<SelectionPopupModel> productGroupsModel =
_fillProductGroups(dataProductGroups); _fillProductGroups(dataProductGroups);
emit(GlossaryLoadedState( emit(GlossaryLoadedState(
token: token, token: token,
productGroups: productGroupsModel, productGroups: productGroupsModel,
productList: [])); productList: [],),);
await _getProductListById(token, emit, productGroupsModel[0].id); await _getProductListById(token, emit, productGroupsModel[0].id);
} }
} else { } else {
@@ -62,7 +62,7 @@ class GlossaryBloc extends Bloc<GlossaryEvent, GlossaryState> {
} else { } else {
// Статус ответа не равен 200, обрабатываем ошибку // Статус ответа не равен 200, обрабатываем ошибку
emit(GlossaryErrorState( emit(GlossaryErrorState(
'Ошибка сервера: ${responseProductGroups.statusCode}')); 'Ошибка сервера: ${responseProductGroups.statusCode}',),);
} }
} catch (e) { } catch (e) {
// Ошибка при декодировании JSON или другая ошибка выполнения // Ошибка при декодировании JSON или другая ошибка выполнения
@@ -71,7 +71,7 @@ class GlossaryBloc extends Bloc<GlossaryEvent, GlossaryState> {
} }
void _changeProductGroup( void _changeProductGroup(
ChangeProductGroup event, Emitter<GlossaryState> emit) async { ChangeProductGroup event, Emitter<GlossaryState> emit,) async {
if (state is GlossaryLoadedState) { if (state is GlossaryLoadedState) {
var currentState = state as GlossaryLoadedState; var currentState = state as GlossaryLoadedState;
await _getProductListById(currentState.token, emit, event.id); await _getProductListById(currentState.token, emit, event.id);
@@ -79,7 +79,7 @@ class GlossaryBloc extends Bloc<GlossaryEvent, GlossaryState> {
} }
Future<void> _getProductListById( Future<void> _getProductListById(
token, Emitter<GlossaryState> emit, int? productGroupID) async { token, Emitter<GlossaryState> emit, int? productGroupID,) async {
final responseProductList = await http.get( final responseProductList = await http.get(
Uri.parse(dotenv.env['SERVER_ROOT']! + '/glossary/index/$productGroupID'), Uri.parse(dotenv.env['SERVER_ROOT']! + '/glossary/index/$productGroupID'),
headers: { headers: {
@@ -93,7 +93,7 @@ class GlossaryBloc extends Bloc<GlossaryEvent, GlossaryState> {
emit(currentState.copyWith( emit(currentState.copyWith(
glossaryModelObj: currentState.glossaryModelObj, glossaryModelObj: currentState.glossaryModelObj,
productGroups: currentState.productGroups, productGroups: currentState.productGroups,
productList: dataProductList)); productList: dataProductList,),);
} else { } else {
emit(GlossaryErrorState('Список продуктов некорректного формата')); emit(GlossaryErrorState('Список продуктов некорректного формата'));
} }

View File

@@ -26,7 +26,7 @@ class GlossaryLoadedState extends GlossaryState {
{this.glossaryModelObj, {this.glossaryModelObj,
this.productGroups, this.productGroups,
this.productList, this.productList,
this.token}); this.token,});
GlossaryModel? glossaryModelObj; GlossaryModel? glossaryModelObj;
String? token; String? token;
@@ -39,7 +39,7 @@ class GlossaryLoadedState extends GlossaryState {
{GlossaryModel? glossaryModelObj, {GlossaryModel? glossaryModelObj,
String? token, String? token,
List<SelectionPopupModel>? productGroups, List<SelectionPopupModel>? productGroups,
List<dynamic>? productList}) { List<dynamic>? productList,}) {
return GlossaryLoadedState( return GlossaryLoadedState(
glossaryModelObj: glossaryModelObj ?? this.glossaryModelObj, glossaryModelObj: glossaryModelObj ?? this.glossaryModelObj,
productGroups: productGroups ?? this.productGroups, productGroups: productGroups ?? this.productGroups,

View File

@@ -14,7 +14,7 @@ class GlossaryScreen extends StatelessWidget {
static Widget builder(BuildContext context) { static Widget builder(BuildContext context) {
return BlocProvider<GlossaryBloc>( return BlocProvider<GlossaryBloc>(
create: (context) => GlossaryBloc(GlossaryState(glossaryModelObj: GlossaryModel()))..add(GlossaryInitialEvent()), child: GlossaryScreen()); create: (context) => GlossaryBloc(GlossaryState(glossaryModelObj: GlossaryModel()))..add(GlossaryInitialEvent()), child: GlossaryScreen(),);
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -67,7 +67,7 @@ class GlossaryScreen extends StatelessWidget {
SizedBox(height: 20), SizedBox(height: 20),
_buildMenu(context), _buildMenu(context),
SizedBox(height: 20), SizedBox(height: 20),
_buildProducts(context, state) _buildProducts(context, state),
], ],
), ),
), ),
@@ -142,7 +142,7 @@ class GlossaryScreen extends StatelessWidget {
children: List.generate(33, _fillAlphabet), children: List.generate(33, _fillAlphabet),
), ),
), ),
]), ],),
); );
} }
@@ -196,8 +196,8 @@ class GlossaryScreen extends StatelessWidget {
SizedBox( SizedBox(
height: 8, height: 8,
), ),
_buildProductList(context, state) _buildProductList(context, state),
]), ],),
); );
} }
@@ -259,22 +259,22 @@ class GlossaryScreen extends StatelessWidget {
Column(children: [ Column(children: [
Text("Ккал - ${product['energy_on_100gr'].toString()}"), Text("Ккал - ${product['energy_on_100gr'].toString()}"),
SizedBox(height: 8), SizedBox(height: 8),
Text("Белки - ${product['proteins_on_100gr'].toString()}") Text("Белки - ${product['proteins_on_100gr'].toString()}"),
]), ],),
Spacer(), Spacer(),
Padding( Padding(
padding: const EdgeInsets.only(right: 24.0), padding: const EdgeInsets.only(right: 24.0),
child: Column(children: [ child: Column(children: [
Text("Жиры - ${product['fats_on_100gr'].toString()}"), Text("Жиры - ${product['fats_on_100gr'].toString()}"),
SizedBox(height: 8), SizedBox(height: 8),
Text("Углеводы - ${product['carbohydrates_on_100gr'].toString()}") Text("Углеводы - ${product['carbohydrates_on_100gr'].toString()}"),
]), ],),
) ),
]) ],),
], ],
), ),
), ),
])); ],),);
} }
Widget _fillAlphabet(int index) { Widget _fillAlphabet(int index) {

View File

@@ -24,7 +24,7 @@ class CustomSearchView extends StatelessWidget {
this.fillColor, this.fillColor,
this.filled = true, this.filled = true,
this.validator, this.validator,
this.onChanged}) this.onChanged,})
: super( : super(
key: key, key: key,
); );
@@ -76,7 +76,7 @@ class CustomSearchView extends StatelessWidget {
return alignment != null return alignment != null
? Align( ? Align(
alignment: alignment ?? Alignment.center, alignment: alignment ?? Alignment.center,
child: searchViewWidget(context)) child: searchViewWidget(context),)
: searchViewWidget(context); : searchViewWidget(context);
} }
@@ -113,7 +113,7 @@ class CustomSearchView extends StatelessWidget {
SizedBox( SizedBox(
child: Padding( child: Padding(
padding: EdgeInsets.only(left: 10), padding: EdgeInsets.only(left: 10),
child: Icon(Icons.search)), child: Icon(Icons.search),),
), ),
prefixIconConstraints: prefixConstraints ?? prefixIconConstraints: prefixConstraints ??
BoxConstraints( BoxConstraints(

File diff suppressed because one or more lines are too long

View File

@@ -10,7 +10,7 @@ class PlanCreateScreen extends StatelessWidget {
final planID = ModalRoute.of(context)!.settings.arguments; final planID = ModalRoute.of(context)!.settings.arguments;
return BlocProvider<PlanCreateBloc>( return BlocProvider<PlanCreateBloc>(
create: (context) => PlanCreateBloc(PlanCreateState(planModelObj: PlanCreateModel(planID: planID.toString())))..add(PlanCreateInitialEvent()), create: (context) => PlanCreateBloc(PlanCreateState(planModelObj: PlanCreateModel(planID: planID.toString())))..add(PlanCreateInitialEvent()),
child: PlanCreateScreen()); child: PlanCreateScreen(),);
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -81,9 +81,9 @@ class PlanCreateScreen extends StatelessWidget {
ElevatedButton( ElevatedButton(
onPressed: () => context.read<PlanCreateBloc>().add(CreatePlan()), onPressed: () => context.read<PlanCreateBloc>().add(CreatePlan()),
child: Text('Создать'), child: Text('Создать'),
) ),
]), ],),
) ),
], ],
), ),
), ),

View File

@@ -49,13 +49,13 @@ class PlanEditBloc extends Bloc<PlanEditEvent, PlanEditState> {
plan: currentState.plan, plan: currentState.plan,
name: currentState.name, name: currentState.name,
duration: currentState.duration, duration: currentState.duration,
details: currentState.details)); details: currentState.details,),);
} else { } else {
emit(PlanEditLoadedState( emit(PlanEditLoadedState(
plan: data, plan: data,
name: TextEditingController(text: data['name']), name: TextEditingController(text: data['name']),
details: TextEditingController(text: data['details']), details: TextEditingController(text: data['details']),
duration: TextEditingController(text: data['duration'].toString()))); duration: TextEditingController(text: data['duration'].toString()),),);
} }
} else { } else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку

View File

@@ -23,7 +23,7 @@ class PlanEditState extends Equatable {
class PlanEditLoadedState extends PlanEditState { class PlanEditLoadedState extends PlanEditState {
PlanEditLoadedState( PlanEditLoadedState(
{this.planModelObj, this.plan, this.name, this.details, this.duration}); {this.planModelObj, this.plan, this.name, this.details, this.duration,});
PlanEditModel? planModelObj; PlanEditModel? planModelObj;
Map<String, dynamic>? plan; Map<String, dynamic>? plan;

View File

@@ -12,7 +12,7 @@ class PlanEditScreen extends StatelessWidget {
final planID = ModalRoute.of(context)!.settings.arguments; final planID = ModalRoute.of(context)!.settings.arguments;
return BlocProvider<PlanEditBloc>( return BlocProvider<PlanEditBloc>(
create: (context) => PlanEditBloc(PlanEditState(planModelObj: PlanEditModel(planID: planID.toString())))..add(PlanEditInitialEvent()), create: (context) => PlanEditBloc(PlanEditState(planModelObj: PlanEditModel(planID: planID.toString())))..add(PlanEditInitialEvent()),
child: PlanEditScreen()); child: PlanEditScreen(),);
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -98,10 +98,10 @@ class PlanEditScreen extends StatelessWidget {
ElevatedButton( ElevatedButton(
onPressed: () => context.read<PlanEditBloc>().add(EditPlan()), onPressed: () => context.read<PlanEditBloc>().add(EditPlan()),
child: Text('Сохранить'), child: Text('Сохранить'),
) ),
], ],
), ),
) ),
], ],
), ),
), ),

View File

@@ -47,12 +47,12 @@ class PlanSelectBloc extends Bloc<PlanSelectEvent, PlanSelectState> {
emit((currentState).copyWith( emit((currentState).copyWith(
posts: data, posts: data,
myProfileModelObj: currentState.myProfileModelObj, myProfileModelObj: currentState.myProfileModelObj,
)); ),);
} else { } else {
print('Got unloaded'); print('Got unloaded');
emit(PlanSelectLoadedState( emit(PlanSelectLoadedState(
posts: data, posts: data,
)); ),);
} }
} else { } else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку

View File

@@ -13,7 +13,7 @@ import 'package:flutter/material.dart';
class PlanSelectScreen extends StatelessWidget { class PlanSelectScreen extends StatelessWidget {
static Widget builder(BuildContext context) { static Widget builder(BuildContext context) {
return BlocProvider<PlanSelectBloc>( return BlocProvider<PlanSelectBloc>(
create: (context) => PlanSelectBloc(PlanSelectState(myProfileModelObj: PlanSelectModel()))..add(PlanSelectInitialEvent()), child: PlanSelectScreen()); create: (context) => PlanSelectBloc(PlanSelectState(myProfileModelObj: PlanSelectModel()))..add(PlanSelectInitialEvent()), child: PlanSelectScreen(),);
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -95,14 +95,14 @@ class PlanSelectScreen extends StatelessWidget {
onTap: () => GoRouter.of(context).goNamed('planCreateScreen'), onTap: () => GoRouter.of(context).goNamed('planCreateScreen'),
child: Icon(Icons.create_outlined), child: Icon(Icons.create_outlined),
), ),
) ),
], ],
), ),
), ),
), ),
), ),
SizedBox(height: 20), SizedBox(height: 20),
_buildPlanList(context, state) _buildPlanList(context, state),
], ],
), ),
), ),

View File

@@ -14,7 +14,7 @@ class PlanScreen extends StatelessWidget {
static Widget builder(BuildContext context) { static Widget builder(BuildContext context) {
final planID = ModalRoute.of(context)!.settings.arguments; final planID = ModalRoute.of(context)!.settings.arguments;
return BlocProvider<PlanBloc>( return BlocProvider<PlanBloc>(
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) { Widget build(BuildContext context) {
@@ -104,9 +104,9 @@ class PlanScreen extends StatelessWidget {
child: Text('Удалить'), child: Text('Удалить'),
), ),
], ],
) ),
]), ],),
) ),
], ],
), ),
), ),

View File

@@ -100,7 +100,7 @@ class MyProfileBloc extends Bloc<MyProfileEvent, MyProfileState> {
selectedCountry: currentState.selectedCountry, selectedCountry: currentState.selectedCountry,
selectedActivity: currentState.selectedActivity, selectedActivity: currentState.selectedActivity,
myProfileModelObj: currentState.myProfileModelObj, myProfileModelObj: currentState.myProfileModelObj,
)); ),);
} else { } else {
var plans = [] var plans = []
..addAll(data["finishedPlans"]) ..addAll(data["finishedPlans"])
@@ -135,7 +135,7 @@ class MyProfileBloc extends Bloc<MyProfileEvent, MyProfileState> {
"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", "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++) { for (int i = 0; i < data["circumferences"].length; i++) {
dates[i] = data["circumferences"]['$i']["created_at"]; dates[i] = data["circumferences"]['$i']["created_at"];
@@ -147,7 +147,7 @@ class MyProfileBloc extends Bloc<MyProfileEvent, MyProfileState> {
"user_id": 0, "user_id": 0,
"weight": 0, "weight": 0,
"created_at": "0000-00-00 00:00:00", "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<MyProfileEvent, MyProfileState> {
"waist_circumference": 0, "waist_circumference": 0,
"hip_circumference": 0, "hip_circumference": 0,
"created_at": "0000-00-00 00:00:00", "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<MyProfileEvent, MyProfileState> {
hypoFormController: data['userDetails']['has_hypo'].toString(), hypoFormController: data['userDetails']['has_hypo'].toString(),
hyperFormController: data['userDetails']['has_hyper'].toString(), hyperFormController: data['userDetails']['has_hyper'].toString(),
chestCircumferenceFormController: TextEditingController( chestCircumferenceFormController: TextEditingController(
text: data['userDetails']['chest_circumference']?.toString()), text: data['userDetails']['chest_circumference']?.toString(),),
waistCircumferenceFormController: TextEditingController( waistCircumferenceFormController: TextEditingController(
text: data['userDetails']['waist_circumference']?.toString()), text: data['userDetails']['waist_circumference']?.toString(),),
hipCircumferenceFormController: TextEditingController( hipCircumferenceFormController: TextEditingController(
text: data['userDetails']['hip_circumference']?.toString()), text: data['userDetails']['hip_circumference']?.toString(),),
weightController: TextEditingController( weightController: TextEditingController(
text: data['userDetails']['weight']?.toString()), text: data['userDetails']['weight']?.toString(),),
weightFormController: TextEditingController( weightFormController: TextEditingController(
text: data['userDetails']['weight']?.toString()), text: data['userDetails']['weight']?.toString(),),
firstNameFormController: TextEditingController( firstNameFormController: TextEditingController(
text: data['userDetails']['first_name']), text: data['userDetails']['first_name'],),
lastNameFormController: lastNameFormController:
TextEditingController(text: data['userDetails']['last_name']), TextEditingController(text: data['userDetails']['last_name']),
countryFormController: countryFormController:
@@ -198,35 +198,35 @@ class MyProfileBloc extends Bloc<MyProfileEvent, MyProfileState> {
cityFormController: cityFormController:
TextEditingController(text: data['userDetails']['city']), TextEditingController(text: data['userDetails']['city']),
heightFormController: TextEditingController( heightFormController: TextEditingController(
text: data['userDetails']['height']?.toString()), text: data['userDetails']['height']?.toString(),),
upPressureFormController: TextEditingController( upPressureFormController: TextEditingController(
text: data['userDetails']['blood_pressure_up']?.toString()), text: data['userDetails']['blood_pressure_up']?.toString(),),
downPressureFormController: TextEditingController( downPressureFormController: TextEditingController(
text: data['userDetails']['blood_pressure_down']?.toString()), text: data['userDetails']['blood_pressure_down']?.toString(),),
allergiesFormController: TextEditingController( allergiesFormController: TextEditingController(
text: data['userDetails']['about_alergy']), text: data['userDetails']['about_alergy'],),
pillsFormController: TextEditingController( pillsFormController: TextEditingController(
text: data['userDetails']['about_taking_pils']), text: data['userDetails']['about_taking_pils'],),
sportsFormController: TextEditingController( sportsFormController: TextEditingController(
text: data['userDetails']['about_sport_hobbies']), text: data['userDetails']['about_sport_hobbies'],),
favoriteFormController: TextEditingController( favoriteFormController: TextEditingController(
text: data['userDetails']['favorite_foods']), text: data['userDetails']['favorite_foods'],),
unfavoriteFormController: TextEditingController( unfavoriteFormController: TextEditingController(
text: data['userDetails']['unfavorite_foods']), text: data['userDetails']['unfavorite_foods'],),
additionalFormController: TextEditingController( additionalFormController: TextEditingController(
text: data['userDetails']['additional_info']), text: data['userDetails']['additional_info'],),
dateFormController: dateFormController:
TextEditingController(text: data['userDetails']['birthdate']), TextEditingController(text: data['userDetails']['birthdate']),
selectedCity: data['userDetails']['city'], selectedCity: data['userDetails']['city'],
selectedCountry: data['userDetails']['country'], selectedCountry: data['userDetails']['country'],
selectedActivity: determineActivityLevel( selectedActivity: determineActivityLevel(
data['userDetails']['activity_coefficient']), data['userDetails']['activity_coefficient'],),
)); ),);
} }
} else { } else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку
emit( emit(
MyProfileErrorState('Некоторые необходимые данные отсутствуют.')); MyProfileErrorState('Некоторые необходимые данные отсутствуют.'),);
} }
} else { } else {
// Статус ответа не равен 200, обрабатываем ошибку // Статус ответа не равен 200, обрабатываем ошибку
@@ -253,7 +253,7 @@ class MyProfileBloc extends Bloc<MyProfileEvent, MyProfileState> {
} // колхоз, но свитчкейсы в дарте странно ведут себя при сравнении double } // колхоз, но свитчкейсы в дарте странно ведут себя при сравнении double
Future<void> _uploadAvatar( Future<void> _uploadAvatar(
UploadAvatar event, Emitter<MyProfileState> emit) async { UploadAvatar event, Emitter<MyProfileState> emit,) async {
if (state is MyProfileLoadedState) { if (state is MyProfileLoadedState) {
var currentState = state as MyProfileLoadedState; var currentState = state as MyProfileLoadedState;
@@ -279,7 +279,7 @@ class MyProfileBloc extends Bloc<MyProfileEvent, MyProfileState> {
return imageUrl; return imageUrl;
} else { } else {
throw Exception( throw Exception(
'Failed to upload image. Status code: ${streamedResponse.statusCode} ${streamedResponse}}'); 'Failed to upload image. Status code: ${streamedResponse.statusCode} ${streamedResponse}}',);
} }
} }
} }

View File

@@ -53,7 +53,7 @@ class MyProfileLoadedState extends MyProfileState {
this.additionalFormController, this.additionalFormController,
this.hypoFormController, this.hypoFormController,
this.hyperFormController, this.hyperFormController,
this.circumferences}) this.circumferences,})
: super(myProfileModelObj: null); : super(myProfileModelObj: null);
MyProfileModel? myProfileModelObj; MyProfileModel? myProfileModelObj;

View File

@@ -112,7 +112,7 @@ class MyProfileScreen extends StatelessWidget {
), ),
], ],
), ),
child: _buildCarousel(context, state)), child: _buildCarousel(context, state),),
SizedBox(height: 15.v), SizedBox(height: 15.v),
if (!state.plans!.isEmpty) if (!state.plans!.isEmpty)
Container( Container(
@@ -137,7 +137,7 @@ class MyProfileScreen extends StatelessWidget {
state.plans?.map((plan) => plan['name']).toList(), state.plans?.map((plan) => plan['name']).toList(),
state.plans?.map((plan) => plan['image']).toList(), state.plans?.map((plan) => plan['image']).toList(),
state.plans?.map((plan) => plan['state']).toList(), state.plans?.map((plan) => plan['state']).toList(),
)), ),),
SizedBox(height: 5.v), SizedBox(height: 5.v),
], ],
), ),
@@ -175,13 +175,13 @@ class MyProfileScreen extends StatelessWidget {
} }
addImage(BuildContext context) async { addImage(BuildContext context) async {
final picker = ImagePicker(); final picker = ImagePicker();
List<XFile>? images = await picker.pickMultiImage(); List<XFile>? images = await picker.pickMultiImage();
if (images.isNotEmpty) { if (images.isNotEmpty) {
for (var image in images) { for (var image in images) {
context.read<MyProfileBloc>().add(UploadAvatar(image)); context.read<MyProfileBloc>().add(UploadAvatar(image));
}
} }
}
} }
onTapSettings(BuildContext context) { onTapSettings(BuildContext context) {
@@ -192,7 +192,7 @@ class MyProfileScreen extends StatelessWidget {
_buildCarousel(BuildContext contex, MyProfileLoadedState state) { _buildCarousel(BuildContext contex, MyProfileLoadedState state) {
return CarouselSlider( return CarouselSlider(
options: CarouselOptions(height: 320.0), options: CarouselOptions(height: 340),
items: [1, 2, 3].map((chartType) { items: [1, 2, 3].map((chartType) {
return Builder( return Builder(
builder: (BuildContext context) { builder: (BuildContext context) {
@@ -212,8 +212,8 @@ class MyProfileScreen extends StatelessWidget {
context, context,
state.chartPoints?.values.map<int>((e) => e['weight']).toList().map((i) => i.toDouble()).toList() ?? [0.0, 0.0, 0.0, 0.0], state.chartPoints?.values.map<int>((e) => e['weight']).toList().map((i) => i.toDouble()).toList() ?? [0.0, 0.0, 0.0, 0.0],
state.chartDates, state.chartDates,
) ),
])); ],),);
case 2: // График ИМТ case 2: // График ИМТ
return Column(children: [ return Column(children: [
Text( Text(
@@ -226,9 +226,9 @@ class MyProfileScreen extends StatelessWidget {
_buildChart( _buildChart(
context, context,
_bodyMassIndex(state.chartPoints?.values.map<int>((e) => e['weight']).toList().map((i) => i.toDouble()).toList() ?? [0.0, 0.0, 0.0, 0.0], _bodyMassIndex(state.chartPoints?.values.map<int>((e) => e['weight']).toList().map((i) => i.toDouble()).toList() ?? [0.0, 0.0, 0.0, 0.0],
state.userDetails?['height'].toInt() ?? 160), state.userDetails?['height'].toInt() ?? 160,),
state.chartDates), state.chartDates,),
]); ],);
case 3: //График обхватов case 3: //График обхватов
return GestureDetector( return GestureDetector(
onTap: () => _editCircumference(context, state), onTap: () => _editCircumference(context, state),
@@ -241,8 +241,8 @@ class MyProfileScreen extends StatelessWidget {
), ),
SizedBox(height: 30.v), SizedBox(height: 30.v),
_buildCircumferenceChart(context, state.circumferences, state.chartDates), _buildCircumferenceChart(context, state.circumferences, state.chartDates),
_buildChartLegend() _buildChartLegend(),
])); ],),);
default: default:
return Text('text', style: TextStyle(fontSize: 16.0)); return Text('text', style: TextStyle(fontSize: 16.0));
} }
@@ -342,7 +342,7 @@ class MyProfileScreen extends StatelessWidget {
lineTouchData: LineTouchData( lineTouchData: LineTouchData(
touchTooltipData: LineTouchTooltipData( touchTooltipData: LineTouchTooltipData(
maxContentWidth: 100, maxContentWidth: 100,
tooltipBgColor: Colors.black, // tooltipBgColor: Colors.black,
getTooltipItems: mapSpots(), getTooltipItems: mapSpots(),
), ),
handleBuiltInTouches: true, handleBuiltInTouches: true,
@@ -519,7 +519,7 @@ class MyProfileScreen extends StatelessWidget {
lineTouchData: LineTouchData( lineTouchData: LineTouchData(
touchTooltipData: LineTouchTooltipData( touchTooltipData: LineTouchTooltipData(
maxContentWidth: 100, maxContentWidth: 100,
tooltipBgColor: Colors.black, // tooltipBgColor: Colors.black,
getTooltipItems: mapTouchedSpots(), getTooltipItems: mapTouchedSpots(),
), ),
handleBuiltInTouches: true, handleBuiltInTouches: true,
@@ -640,7 +640,7 @@ class MyProfileScreen extends StatelessWidget {
child: Column(children: [ child: Column(children: [
Padding( Padding(
padding: EdgeInsets.only(left: 15.h), 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), SizedBox(height: 5.v),
Container( Container(
decoration: AppDecoration.outlineBlueGray.copyWith(borderRadius: BorderRadiusStyle.roundedBorder5), decoration: AppDecoration.outlineBlueGray.copyWith(borderRadius: BorderRadiusStyle.roundedBorder5),
@@ -683,12 +683,12 @@ class MyProfileScreen extends StatelessWidget {
child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
Padding( Padding(
padding: EdgeInsets.only(bottom: 1.v), padding: EdgeInsets.only(bottom: 1.v),
child: Text(plans![i], style: CustomTextStyles.titleSmallBluegray800Bold)), child: Text(plans![i], style: CustomTextStyles.titleSmallBluegray800Bold),),
Container( Container(
height: 19.v, height: 19.v,
width: 100.h, width: 100.h,
decoration: BoxDecoration(color: boxColor, borderRadius: BorderRadius.circular(5.h))) decoration: BoxDecoration(color: boxColor, borderRadius: BorderRadius.circular(5.h)),),
]))), ],),),),
Align( Align(
alignment: Alignment.center, alignment: Alignment.center,
child: Container( child: Container(
@@ -697,18 +697,18 @@ class MyProfileScreen extends StatelessWidget {
dotenv.env['STORAGE_URL']! + imagePaths?[i], dotenv.env['STORAGE_URL']! + imagePaths?[i],
height: 25.adaptSize, height: 25.adaptSize,
width: 25.adaptSize, width: 25.adaptSize,
))), ),),),
Align( Align(
alignment: Alignment.bottomRight, alignment: Alignment.bottomRight,
child: Container( child: Container(
width: 70.h, width: 70.h,
margin: EdgeInsets.only(bottom: 14.h, right: 22.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<double> _bodyMassIndex(List<double> weightPoints, int height) { List<double> _bodyMassIndex(List<double> weightPoints, int height) {
@@ -770,7 +770,7 @@ class MyProfileScreen extends StatelessWidget {
], ],
), ),
], ],
)), ),),
actions: [ actions: [
TextButton( TextButton(
onPressed: onTapOk(context), onPressed: onTapOk(context),
@@ -781,7 +781,7 @@ class MyProfileScreen extends StatelessWidget {
child: Text("Изменить", child: Text("Изменить",
style: CustomTextStyles.titleMediumBlack.copyWith( style: CustomTextStyles.titleMediumBlack.copyWith(
color: Colors.blue, color: Colors.blue,
)), ),),
), ),
], ],
backgroundColor: Colors.white, backgroundColor: Colors.white,
@@ -862,7 +862,7 @@ class MyProfileScreen extends StatelessWidget {
child: Text("Изменить", child: Text("Изменить",
style: CustomTextStyles.titleMediumBlack.copyWith( style: CustomTextStyles.titleMediumBlack.copyWith(
color: Colors.blue, color: Colors.blue,
)), ),),
), ),
], ],
backgroundColor: Colors.white, backgroundColor: Colors.white,

View File

@@ -16,7 +16,7 @@ import 'package:flutter/material.dart';
class MySettingsScreen extends StatelessWidget { class MySettingsScreen extends StatelessWidget {
static Widget builder(BuildContext context) { static Widget builder(BuildContext context) {
return BlocProvider<MyProfileBloc>( return BlocProvider<MyProfileBloc>(
create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent()), child: MySettingsScreen()); create: (context) => MyProfileBloc(MyProfileState(myProfileModelObj: MyProfileModel()))..add(MyProfileInitialEvent()), child: MySettingsScreen(),);
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -86,8 +86,8 @@ class MySettingsScreen extends StatelessWidget {
), ),
title: Padding( title: Padding(
padding: EdgeInsets.only(left: 20.h), 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), SizedBox(height: 20),
Container( Container(
padding: EdgeInsets.symmetric( padding: EdgeInsets.symmetric(

View File

@@ -42,7 +42,7 @@ class RecipeCreateBloc extends Bloc<RecipeCreateEvent, RecipeCreateState> {
video_url: currentState.video_url, video_url: currentState.video_url,
steps: currentState.steps, steps: currentState.steps,
stepDescriptions: currentState.stepDescriptions, stepDescriptions: currentState.stepDescriptions,
tags: currentState.tags)); tags: currentState.tags,),);
} else { } else {
final Map<String, dynamic> step = { final Map<String, dynamic> step = {
'description': '', 'description': '',
@@ -55,12 +55,12 @@ class RecipeCreateBloc extends Bloc<RecipeCreateEvent, RecipeCreateState> {
video_url: TextEditingController(), video_url: TextEditingController(),
tags: TextEditingController(), tags: TextEditingController(),
stepDescriptions: [TextEditingController()], stepDescriptions: [TextEditingController()],
steps: [step])); steps: [step],),);
} }
} }
FutureOr<void> _addStep( FutureOr<void> _addStep(
AddStep event, Emitter<RecipeCreateState> emit) async { AddStep event, Emitter<RecipeCreateState> emit,) async {
if (state is RecipeCreateLoadedState) { if (state is RecipeCreateLoadedState) {
var currentState = state as RecipeCreateLoadedState; var currentState = state as RecipeCreateLoadedState;
@@ -74,13 +74,13 @@ class RecipeCreateBloc extends Bloc<RecipeCreateEvent, RecipeCreateState> {
}); });
updatedStepDescriptions!.add(TextEditingController()); updatedStepDescriptions!.add(TextEditingController());
emit(currentState.copyWith( emit(currentState.copyWith(
steps: updatedSteps, stepDescriptions: updatedStepDescriptions)); steps: updatedSteps, stepDescriptions: updatedStepDescriptions,),);
await _reloadScreen(event, emit); await _reloadScreen(event, emit);
} }
} }
FutureOr<void> _removeStep( FutureOr<void> _removeStep(
RemoveStep event, Emitter<RecipeCreateState> emit) async { RemoveStep event, Emitter<RecipeCreateState> emit,) async {
if (state is RecipeCreateLoadedState) { if (state is RecipeCreateLoadedState) {
var currentState = state as RecipeCreateLoadedState; var currentState = state as RecipeCreateLoadedState;
@@ -91,13 +91,13 @@ class RecipeCreateBloc extends Bloc<RecipeCreateEvent, RecipeCreateState> {
updatedSteps!.removeAt(event.id); updatedSteps!.removeAt(event.id);
updatedStepDescriptions!.removeAt(event.id); updatedStepDescriptions!.removeAt(event.id);
emit(currentState.copyWith( emit(currentState.copyWith(
steps: updatedSteps, stepDescriptions: updatedStepDescriptions)); steps: updatedSteps, stepDescriptions: updatedStepDescriptions,),);
await _reloadScreen(event, emit); await _reloadScreen(event, emit);
} }
} }
FutureOr<void> _createRecipe( FutureOr<void> _createRecipe(
CreateRecipe event, Emitter<RecipeCreateState> emit) async { CreateRecipe event, Emitter<RecipeCreateState> emit,) async {
if (state is RecipeCreateLoadedState) { if (state is RecipeCreateLoadedState) {
var currentState = state as RecipeCreateLoadedState; var currentState = state as RecipeCreateLoadedState;
@@ -112,13 +112,13 @@ class RecipeCreateBloc extends Bloc<RecipeCreateEvent, RecipeCreateState> {
AppRouter.navigatorKey.currentContext?.goNamed('recipeSelectScreen'); AppRouter.navigatorKey.currentContext?.goNamed('recipeSelectScreen');
} else { } else {
print( print(
'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}'); 'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}',);
} }
} }
} }
FutureOr<http.Response> sendRecipe(String? title, String? video_url, FutureOr<http.Response> sendRecipe(String? title, String? video_url,
String? description, List<dynamic>? steps) async { String? description, List<dynamic>? steps,) async {
String url = '${dotenv.env['SERVER_ROOT']!}/recipe/create'; String url = '${dotenv.env['SERVER_ROOT']!}/recipe/create';
final Map<String, dynamic> credentials = { final Map<String, dynamic> credentials = {
'title': title, 'title': title,
@@ -141,7 +141,7 @@ class RecipeCreateBloc extends Bloc<RecipeCreateEvent, RecipeCreateState> {
} }
FutureOr<void> _reloadScreen( FutureOr<void> _reloadScreen(
RecipeCreateEvent? event, Emitter<RecipeCreateState> emit) async { RecipeCreateEvent? event, Emitter<RecipeCreateState> emit,) async {
print('Reloading..'); print('Reloading..');
final box = await Hive.openBox('token'); final box = await Hive.openBox('token');
final token = box.get('token'); final token = box.get('token');
@@ -158,7 +158,7 @@ class RecipeCreateBloc extends Bloc<RecipeCreateEvent, RecipeCreateState> {
video_url: currentState.video_url, video_url: currentState.video_url,
steps: currentState.steps, steps: currentState.steps,
stepDescriptions: currentState.stepDescriptions, stepDescriptions: currentState.stepDescriptions,
tags: currentState.tags)); tags: currentState.tags,),);
} }
} }
} }

View File

@@ -30,7 +30,7 @@ class RecipeCreateLoadedState extends RecipeCreateState {
this.video_url, this.video_url,
this.tags, this.tags,
this.stepDescriptions, this.stepDescriptions,
this.steps}); this.steps,});
RecipeCreateModel? recipeModelObj; RecipeCreateModel? recipeModelObj;
String? token; String? token;
@@ -49,7 +49,7 @@ class RecipeCreateLoadedState extends RecipeCreateState {
video_url, video_url,
steps, steps,
tags, tags,
stepDescriptions stepDescriptions,
]; ];
RecipeCreateLoadedState copyWith({ RecipeCreateLoadedState copyWith({
RecipeCreateModel? recipeModelObj, RecipeCreateModel? recipeModelObj,
@@ -69,7 +69,7 @@ class RecipeCreateLoadedState extends RecipeCreateState {
token: token ?? this.token, token: token ?? this.token,
steps: steps ?? this.steps, steps: steps ?? this.steps,
tags: tags ?? this.tags, tags: tags ?? this.tags,
stepDescriptions: stepDescriptions ?? this.stepDescriptions); stepDescriptions: stepDescriptions ?? this.stepDescriptions,);
} }
} }

View File

@@ -18,7 +18,7 @@ class RecipeCreateScreen extends StatelessWidget {
return BlocProvider<RecipeCreateBloc>( return BlocProvider<RecipeCreateBloc>(
create: (context) => create: (context) =>
RecipeCreateBloc(RecipeCreateState(recipeModelObj: RecipeCreateModel(recipeID: recipeID.toString())))..add(RecipeCreateInitialEvent()), RecipeCreateBloc(RecipeCreateState(recipeModelObj: RecipeCreateModel(recipeID: recipeID.toString())))..add(RecipeCreateInitialEvent()),
child: RecipeCreateScreen()); child: RecipeCreateScreen(),);
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -73,9 +73,9 @@ class RecipeCreateScreen extends StatelessWidget {
children: steps, children: steps,
), ),
SizedBox(height: 20.v), SizedBox(height: 20.v),
_buildAdditional(context, state) _buildAdditional(context, state),
]), ],),
))); ),),);
} }
_buldAppBar(BuildContext context) { _buldAppBar(BuildContext context) {
@@ -105,7 +105,7 @@ class RecipeCreateScreen extends StatelessWidget {
alignment: Alignment.center, alignment: Alignment.center,
child: AppbarSubtitle( child: AppbarSubtitle(
text: "Добавление рецепта", text: "Добавление рецепта",
)), ),),
), ),
); );
} }
@@ -164,7 +164,7 @@ class RecipeCreateScreen extends StatelessWidget {
), ),
), ),
SizedBox(height: 16.0), SizedBox(height: 16.0),
]), ],),
); );
} }
@@ -206,7 +206,7 @@ class RecipeCreateScreen extends StatelessWidget {
Icon( Icon(
Icons.photo_library, Icons.photo_library,
color: appTheme.blueGray300, color: appTheme.blueGray300,
) ),
], ],
), ),
), ),
@@ -318,7 +318,7 @@ class RecipeCreateScreen extends StatelessWidget {
text: "x", text: "x",
buttonStyle: CustomButtonStyles.outlinePrimaryTL15, buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
), ),
]), ],),
); );
} }
@@ -375,7 +375,7 @@ class RecipeCreateScreen extends StatelessWidget {
text: "Добавить рецепт", text: "Добавить рецепт",
buttonStyle: CustomButtonStyles.outlinePrimaryTL15, buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
), ),
]), ],),
); );
} }

View File

@@ -56,7 +56,7 @@ class RecipeEditBloc extends Bloc<RecipeEditEvent, RecipeEditState> {
video_url: currentState.video_url, video_url: currentState.video_url,
steps: currentState.steps, steps: currentState.steps,
stepDescriptions: currentState.stepDescriptions, stepDescriptions: currentState.stepDescriptions,
tags: currentState.tags)); tags: currentState.tags,),);
} else { } else {
final Map<String, dynamic> defaultStep = { final Map<String, dynamic> defaultStep = {
'description': '', 'description': '',
@@ -85,7 +85,7 @@ class RecipeEditBloc extends Bloc<RecipeEditEvent, RecipeEditState> {
tags: await _fetchTags(data['id']), tags: await _fetchTags(data['id']),
stepDescriptions: stepDescriptions, stepDescriptions: stepDescriptions,
steps: steps, steps: steps,
)); ),);
} }
} else { } else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку
@@ -171,7 +171,7 @@ class RecipeEditBloc extends Bloc<RecipeEditEvent, RecipeEditState> {
'steps': '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."}]', '[{"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': '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( var response = await http.post(
@@ -222,7 +222,7 @@ class RecipeEditBloc extends Bloc<RecipeEditEvent, RecipeEditState> {
video_url: currentState.video_url, video_url: currentState.video_url,
steps: currentState.steps, steps: currentState.steps,
stepDescriptions: currentState.stepDescriptions, stepDescriptions: currentState.stepDescriptions,
tags: currentState.tags)); tags: currentState.tags,),);
} }
} }
} }

View File

@@ -32,7 +32,7 @@ class RecipeEditLoadedState extends RecipeEditState {
this.tagsController, this.tagsController,
this.stepDescriptions, this.stepDescriptions,
this.tags, this.tags,
this.steps}); this.steps,});
RecipeEditModel? recipeModelObj; RecipeEditModel? recipeModelObj;
Map<String, dynamic>? recipe; Map<String, dynamic>? recipe;

View File

@@ -19,7 +19,7 @@ class RecipeEditScreen extends StatelessWidget {
final recipeID = ModalRoute.of(context)!.settings.arguments; final recipeID = ModalRoute.of(context)!.settings.arguments;
return BlocProvider<RecipeEditBloc>( return BlocProvider<RecipeEditBloc>(
create: (context) => RecipeEditBloc(RecipeEditState(recipeModelObj: RecipeEditModel(recipeID: recipeID.toString())))..add(RecipeEditInitialEvent()), create: (context) => RecipeEditBloc(RecipeEditState(recipeModelObj: RecipeEditModel(recipeID: recipeID.toString())))..add(RecipeEditInitialEvent()),
child: RecipeEditScreen()); child: RecipeEditScreen(),);
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -76,7 +76,7 @@ class RecipeEditScreen extends StatelessWidget {
children: steps, children: steps,
), ),
SizedBox(height: 20.v), SizedBox(height: 20.v),
_buildAdditional(context, state) _buildAdditional(context, state),
], ],
), ),
), ),
@@ -112,7 +112,7 @@ class RecipeEditScreen extends StatelessWidget {
alignment: Alignment.center, alignment: Alignment.center,
child: AppbarSubtitle( child: AppbarSubtitle(
text: "Редактирование рецепта", text: "Редактирование рецепта",
)), ),),
), ),
); );
} }
@@ -182,7 +182,7 @@ class RecipeEditScreen extends StatelessWidget {
), ),
), ),
SizedBox(height: 16.0), SizedBox(height: 16.0),
]), ],),
); );
} }
@@ -224,7 +224,7 @@ class RecipeEditScreen extends StatelessWidget {
Icon( Icon(
Icons.photo_library, Icons.photo_library,
color: appTheme.blueGray300, color: appTheme.blueGray300,
) ),
], ],
), ),
), ),
@@ -348,7 +348,7 @@ class RecipeEditScreen extends StatelessWidget {
text: "x", text: "x",
buttonStyle: CustomButtonStyles.outlinePrimaryTL15, buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
), ),
]), ],),
); );
} }
@@ -394,7 +394,7 @@ class RecipeEditScreen extends StatelessWidget {
text: "Добавить рецепт", text: "Добавить рецепт",
buttonStyle: CustomButtonStyles.outlinePrimaryTL15, buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
), ),
]), ],),
); );
} }

View File

@@ -46,12 +46,12 @@ class RecipeSelectBloc extends Bloc<RecipeSelectEvent, RecipeSelectState> {
emit((currentState).copyWith( emit((currentState).copyWith(
posts: data, posts: data,
myProfileModelObj: currentState.myProfileModelObj, myProfileModelObj: currentState.myProfileModelObj,
)); ),);
} else { } else {
print('Got unloaded'); print('Got unloaded');
emit(RecipeSelectLoadedState( emit(RecipeSelectLoadedState(
posts: data, posts: data,
)); ),);
} }
} else { } else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку

View File

@@ -14,7 +14,7 @@ class RecipeSelectScreen extends StatelessWidget {
static Widget builder(BuildContext context) { static Widget builder(BuildContext context) {
return BlocProvider<RecipeSelectBloc>( return BlocProvider<RecipeSelectBloc>(
create: (context) => RecipeSelectBloc(RecipeSelectState(myProfileModelObj: RecipeSelectModel()))..add(RecipeSelectInitialEvent()), create: (context) => RecipeSelectBloc(RecipeSelectState(myProfileModelObj: RecipeSelectModel()))..add(RecipeSelectInitialEvent()),
child: RecipeSelectScreen()); child: RecipeSelectScreen(),);
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -94,7 +94,7 @@ class RecipeSelectScreen extends StatelessWidget {
onTap: () => GoRouter.of(context).goNamed('recipeCreateScreen'), onTap: () => GoRouter.of(context).goNamed('recipeCreateScreen'),
child: Icon(Icons.create_outlined), child: Icon(Icons.create_outlined),
), ),
) ),
], ],
), ),
), ),
@@ -160,7 +160,7 @@ class RecipeSelectScreen extends StatelessWidget {
), ),
child: Icon(Icons.edit), child: Icon(Icons.edit),
), ),
)); ),);
}, },
); );
} }

View File

@@ -54,7 +54,7 @@ class RecipeBloc extends Bloc<RecipeEvent, RecipeState> {
commentController: currentState.commentController, commentController: currentState.commentController,
comments: currentState.comments, comments: currentState.comments,
steps: currentState.steps, steps: currentState.steps,
author: currentState.author)); author: currentState.author,),);
} else { } else {
emit(RecipeLoadedState( emit(RecipeLoadedState(
token: token, token: token,
@@ -63,7 +63,7 @@ class RecipeBloc extends Bloc<RecipeEvent, RecipeState> {
author: await _fetchAuthor(data['id']), author: await _fetchAuthor(data['id']),
comments: fillCommentList(await _fetchComments(data['id'])), comments: fillCommentList(await _fetchComments(data['id'])),
tags: await _fetchTags(data['id']), tags: await _fetchTags(data['id']),
commentController: TextEditingController())); commentController: TextEditingController(),),);
} }
} else { } else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку // Один или несколько ключевых полей отсутствуют, обрабатываем ошибку
@@ -176,7 +176,7 @@ class RecipeBloc extends Bloc<RecipeEvent, RecipeState> {
userImage: comments[i]['profile_photo_path'], userImage: comments[i]['profile_photo_path'],
username: comments[i]['name'], username: comments[i]['name'],
dateText: DateFormat('dd.MM').format(DateTime.parse(comments[i]['updated_at'])), dateText: DateFormat('dd.MM').format(DateTime.parse(comments[i]['updated_at'])),
greetingText: comments[i]['body'])); greetingText: comments[i]['body'],),);
} }
return list; return list;
} }
@@ -194,7 +194,7 @@ class RecipeBloc extends Bloc<RecipeEvent, RecipeState> {
'Authorization': 'Bearer $token', 'Authorization': 'Bearer $token',
}, },
body: json.encode(credentials), body: json.encode(credentials),
encoding: utf8); encoding: utf8,);
return response; return response;
} }

View File

@@ -30,7 +30,7 @@ class RecipeLoadedState extends RecipeState {
this.token, this.token,
this.commentController, this.commentController,
this.tags, this.tags,
this.steps}); this.steps,});
RecipeModel? recipeModelObj; RecipeModel? recipeModelObj;
Map<String, dynamic>? recipe; Map<String, dynamic>? recipe;
@@ -48,7 +48,7 @@ class RecipeLoadedState extends RecipeState {
comments, comments,
token, token,
commentController, commentController,
steps steps,
]; ];
RecipeLoadedState copyWith( RecipeLoadedState copyWith(
{RecipeModel? recipeModelObj, {RecipeModel? recipeModelObj,
@@ -58,7 +58,7 @@ class RecipeLoadedState extends RecipeState {
String? token, String? token,
List<dynamic>? tags, List<dynamic>? tags,
List<dynamic>? steps, List<dynamic>? steps,
List<dynamic>? comments}) { List<dynamic>? comments,}) {
return RecipeLoadedState( return RecipeLoadedState(
recipeModelObj: recipeModelObj ?? this.recipeModelObj, recipeModelObj: recipeModelObj ?? this.recipeModelObj,
recipe: recipe ?? this.recipe, recipe: recipe ?? this.recipe,

View File

@@ -18,7 +18,7 @@ class RecipeScreen extends StatelessWidget {
final recipeID = ModalRoute.of(context)!.settings.arguments; final recipeID = ModalRoute.of(context)!.settings.arguments;
return BlocProvider<RecipeBloc>( return BlocProvider<RecipeBloc>(
create: (context) => RecipeBloc(RecipeState(recipeModelObj: RecipeModel(recipeID: recipeID.toString())))..add(RecipeInitialEvent()), create: (context) => RecipeBloc(RecipeState(recipeModelObj: RecipeModel(recipeID: recipeID.toString())))..add(RecipeInitialEvent()),
child: RecipeScreen()); child: RecipeScreen(),);
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -77,7 +77,7 @@ class RecipeScreen extends StatelessWidget {
_buildCommentSection(context, state), _buildCommentSection(context, state),
], ],
), ),
)); ),);
} }
_buildHeaderRow(BuildContext context, RecipeLoadedState state) { _buildHeaderRow(BuildContext context, RecipeLoadedState state) {
@@ -195,7 +195,7 @@ class RecipeScreen extends StatelessWidget {
child: Text( child: Text(
DateFormat('dd.MM.yyyy').format(DateTime.parse(state.recipe?['updated_at'])), DateFormat('dd.MM.yyyy').format(DateTime.parse(state.recipe?['updated_at'])),
style: theme.textTheme.bodyMedium, style: theme.textTheme.bodyMedium,
)), ),),
SizedBox(height: 16.0), SizedBox(height: 16.0),
_buildTags(state.tags), _buildTags(state.tags),
SizedBox(height: 16.0), SizedBox(height: 16.0),
@@ -210,8 +210,8 @@ class RecipeScreen extends StatelessWidget {
Text( Text(
"Нравится", "Нравится",
style: CustomTextStyles.titleMediumSemiBold, style: CustomTextStyles.titleMediumSemiBold,
) ),
]), ],),
), ),
Spacer(), Spacer(),
Padding( Padding(
@@ -224,10 +224,10 @@ class RecipeScreen extends StatelessWidget {
Text( Text(
"Поделиться", "Поделиться",
style: CustomTextStyles.titleMediumSemiBold, style: CustomTextStyles.titleMediumSemiBold,
) ),
])) ],),),
]), ],),
]), ],),
); );
} }
@@ -368,7 +368,7 @@ class RecipeScreen extends StatelessWidget {
), ),
onPressed: () => context.read<RecipeBloc>().add(CreateComment(state.commentController!.text)), onPressed: () => context.read<RecipeBloc>().add(CreateComment(state.commentController!.text)),
// Установите прозрачный фон // Установите прозрачный фон
) ),
], ],
), ),
], ],
@@ -400,7 +400,7 @@ class RecipeScreen extends StatelessWidget {
), ),
SizedBox( SizedBox(
height: 20, height: 20,
) ),
], ],
); );
} }
@@ -451,8 +451,8 @@ class RecipeScreen extends StatelessWidget {
errorWidget: (context, url, error) => Icon(Icons.error), errorWidget: (context, url, error) => Icon(Icons.error),
), ),
SizedBox(height: 16.0), SizedBox(height: 16.0),
Text(state.steps?[i]['description']) Text(state.steps?[i]['description']),
]), ],),
); );
} }
} }

View File

@@ -82,7 +82,7 @@ class CommentWidget extends StatelessWidget {
commentModelObj.dateText!, commentModelObj.dateText!,
style: theme.textTheme.bodyMedium, style: theme.textTheme.bodyMedium,
), ),
) ),
], ],
), ),
), ),
@@ -99,7 +99,7 @@ class CommentWidget extends StatelessWidget {
imagePath: ImageConstant.imgSend, imagePath: ImageConstant.imgSend,
height: 30.v, height: 30.v,
width: 30.h, width: 30.h,
margin: EdgeInsets.only(left: 5)), margin: EdgeInsets.only(left: 5),),
], ],
), ),
); );

View File

@@ -23,7 +23,7 @@ class AdditionalInformationScreen extends StatelessWidget {
create: (context) => create: (context) =>
AdditionalInformationBloc(AdditionalInformationState(additionalInformationModelObj: AdditionalInformationModel(userRegistrationSheet: sheet))) AdditionalInformationBloc(AdditionalInformationState(additionalInformationModelObj: AdditionalInformationModel(userRegistrationSheet: sheet)))
..add(AdditionalInformationInitialEvent()), ..add(AdditionalInformationInitialEvent()),
child: AdditionalInformationScreen()); child: AdditionalInformationScreen(),);
} }
@override @override
@@ -42,11 +42,11 @@ class AdditionalInformationScreen extends StatelessWidget {
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.onPrimary, color: theme.colorScheme.onPrimary,
borderRadius: BorderRadius.circular(8.h), 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( child: ClipRRect(
borderRadius: BorderRadius.circular(8.h), borderRadius: BorderRadius.circular(8.h),
child: LinearProgressIndicator( child: LinearProgressIndicator(
value: 1, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400)))), value: 1, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400),),),),
SizedBox(height: 20.v), SizedBox(height: 20.v),
SizedBox(height: 73.v), SizedBox(height: 73.v),
_buildTextFormField(context), _buildTextFormField(context),
@@ -56,9 +56,9 @@ class AdditionalInformationScreen extends StatelessWidget {
text: "finish".tr.toUpperCase(), text: "finish".tr.toUpperCase(),
margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v),
buttonStyle: CustomButtonStyles.outlinePrimaryTL15, buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
onPressed: onTapFinish(state, context)); onPressed: onTapFinish(state, context),);
}), },),
]))); ],),),);
} }
onTapFinish(AdditionalInformationState state, BuildContext context) { onTapFinish(AdditionalInformationState state, BuildContext context) {
@@ -67,7 +67,7 @@ class AdditionalInformationScreen extends StatelessWidget {
sheet.additionalInfo = state.editTextController!.text; sheet.additionalInfo = state.editTextController!.text;
final response = await http.post(Uri.parse(dotenv.env['SERVER_ROOT']! + '/register'), 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); var res = await jsonDecode(response.body);
if (response.statusCode == 200) { if (response.statusCode == 200) {
@@ -88,7 +88,7 @@ class AdditionalInformationScreen extends StatelessWidget {
leading: leading:
AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 18.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 18.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)),
centerTitle: true, centerTitle: true,
title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio)); title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),);
} }
onTapBack(BuildContext context) { onTapBack(BuildContext context) {
@@ -110,7 +110,7 @@ class AdditionalInformationScreen extends StatelessWidget {
width: 294.h, width: 294.h,
margin: EdgeInsets.only(left: 24.h, right: 23.h), margin: EdgeInsets.only(left: 24.h, right: 23.h),
child: Text("enter_additional_information".tr, 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), SizedBox(height: 10.v),
BlocSelector<AdditionalInformationBloc, AdditionalInformationState, TextEditingController?>( BlocSelector<AdditionalInformationBloc, AdditionalInformationState, TextEditingController?>(
selector: (state) => state.editTextController, selector: (state) => state.editTextController,
@@ -119,10 +119,10 @@ class AdditionalInformationScreen extends StatelessWidget {
controller: editTextController, controller: editTextController,
hintText: "У меня крепкое здоровье, но последнее время часто утомляюсь, однако, это мне не мешает радоваться жизни", hintText: "У меня крепкое здоровье, но последнее время часто утомляюсь, однако, это мне не мешает радоваться жизни",
textInputAction: TextInputAction.done, textInputAction: TextInputAction.done,
maxLines: 8); maxLines: 8,);
}) },),
])) ],),),
])); ],),);
} }
/// Navigates to the previous screen. /// Navigates to the previous screen.
@@ -139,7 +139,7 @@ class AdditionalInformationScreen extends StatelessWidget {
title: const Text('Ошибка'), title: const Text('Ошибка'),
content: Text(text), content: Text(text),
actions: [TextButton(onPressed: onTapOk(context), child: const Text('Ok'))], actions: [TextButton(onPressed: onTapOk(context), child: const Text('Ok'))],
)); ),);
} }
onTapOk(BuildContext context) { onTapOk(BuildContext context) {

View File

@@ -17,7 +17,7 @@ class AllergiesScreen extends StatefulWidget {
static Widget builder(BuildContext context, sheet) { static Widget builder(BuildContext context, sheet) {
return BlocProvider<AllergiesBloc>( return BlocProvider<AllergiesBloc>(
create: (context) => AllergiesBloc(AllergiesState(allergiesModelObj: AllergiesModel(userRegistrationSheet: sheet)))..add(AllergiesInitialEvent()), create: (context) => AllergiesBloc(AllergiesState(allergiesModelObj: AllergiesModel(userRegistrationSheet: sheet)))..add(AllergiesInitialEvent()),
child: AllergiesScreen()); child: AllergiesScreen(),);
} }
@override @override
@@ -41,11 +41,11 @@ class _AllergiesScreenState extends State<AllergiesScreen> {
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.onPrimary, color: theme.colorScheme.onPrimary,
borderRadius: BorderRadius.circular(8.h), 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( child: ClipRRect(
borderRadius: BorderRadius.circular(8.h), borderRadius: BorderRadius.circular(8.h),
child: LinearProgressIndicator( child: LinearProgressIndicator(
value: 0.76, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400)))), value: 0.76, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400),),),),
SizedBox(height: 22.v), SizedBox(height: 22.v),
Text("allergies_presence".tr, style: theme.textTheme.headlineSmall), Text("allergies_presence".tr, style: theme.textTheme.headlineSmall),
Spacer(flex: 36), Spacer(flex: 36),
@@ -56,15 +56,15 @@ class _AllergiesScreenState extends State<AllergiesScreen> {
text: "continue".tr.toUpperCase(), text: "continue".tr.toUpperCase(),
margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v),
buttonStyle: CustomButtonStyles.outlinePrimaryTL15, buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
onPressed: onTapContinue(state, context)); onPressed: onTapContinue(state, context),);
}), },),
BlocBuilder<AllergiesBloc, AllergiesState>(builder: (context, state) { BlocBuilder<AllergiesBloc, AllergiesState>(builder: (context, state) {
return GestureDetector( return GestureDetector(
onTap: onTapSkip(state, context), onTap: onTapSkip(state, context),
child: Text("skip".tr, style: theme.textTheme.bodyLarge), child: Text("skip".tr, style: theme.textTheme.bodyLarge),
); );
}), },),
]))); ],),),);
} }
onTapSkip(AllergiesState state, BuildContext context) { onTapSkip(AllergiesState state, BuildContext context) {
@@ -89,7 +89,7 @@ class _AllergiesScreenState extends State<AllergiesScreen> {
leading: leading:
AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 18.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 18.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)),
centerTitle: true, centerTitle: true,
title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio)); title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),);
} }
onTapBack(BuildContext context) { onTapBack(BuildContext context) {
@@ -107,9 +107,9 @@ class _AllergiesScreenState extends State<AllergiesScreen> {
selector: (state) => state.enterInformationController, selector: (state) => state.enterInformationController,
builder: (context, enterInformationController) { builder: (context, enterInformationController) {
return CustomTextFormField( 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. /// Navigates to the previous screen.

View File

@@ -15,7 +15,7 @@ class AppNavigationScreen extends StatefulWidget {
return BlocProvider<AppNavigationBloc>( return BlocProvider<AppNavigationBloc>(
create: (context) => AppNavigationBloc(AppNavigationState( create: (context) => AppNavigationBloc(AppNavigationState(
appNavigationModelObj: AppNavigationModel(), appNavigationModelObj: AppNavigationModel(),
)) ),)
..add(AppNavigationInitialEvent()), ..add(AppNavigationInitialEvent()),
child: AppNavigationScreen(), child: AppNavigationScreen(),
); );

View File

@@ -53,9 +53,9 @@ class BloodPressureBloc extends Bloc<BloodPressureEvent, BloodPressureState> {
) async { ) async {
emit(state.copyWith( emit(state.copyWith(
upPressureController: TextEditingController(), upPressureController: TextEditingController(),
downPressureController: TextEditingController())); downPressureController: TextEditingController(),),);
emit(state.copyWith( emit(state.copyWith(
bloodPressureModelObj: state.bloodPressureModelObj bloodPressureModelObj: state.bloodPressureModelObj
?.copyWith(dropdownItemList: fillDropdownItemList()))); ?.copyWith(dropdownItemList: fillDropdownItemList()),),);
} }
} }

View File

@@ -21,7 +21,7 @@ class BloodPressureScreen extends StatefulWidget {
return BlocProvider<BloodPressureBloc>( return BlocProvider<BloodPressureBloc>(
create: (context) => create: (context) =>
BloodPressureBloc(BloodPressureState(bloodPressureModelObj: BloodPressureModel(userRegistrationSheet: sheet)))..add(BloodPressureInitialEvent()), BloodPressureBloc(BloodPressureState(bloodPressureModelObj: BloodPressureModel(userRegistrationSheet: sheet)))..add(BloodPressureInitialEvent()),
child: BloodPressureScreen()); child: BloodPressureScreen(),);
} }
@override @override
@@ -66,7 +66,7 @@ class _BloodPressureScreenState extends State<BloodPressureScreen> {
SizedBox( SizedBox(
width: 224.h, width: 224.h,
child: Text("your_blood_pressure".tr, 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), SizedBox(height: 21.v),
Container( Container(
margin: EdgeInsets.only(right: 1.h), margin: EdgeInsets.only(right: 1.h),
@@ -78,8 +78,8 @@ class _BloodPressureScreenState extends State<BloodPressureScreen> {
selector: (state) => state.upPressureController, selector: (state) => state.upPressureController,
builder: (context, upPressureController) { builder: (context, upPressureController) {
return CustomTextFormField(inputFormatters: [digitsOnly], controller: upPressureController, hintText: "90".tr); return CustomTextFormField(inputFormatters: [digitsOnly], controller: upPressureController, hintText: "90".tr);
}) },),
])), ],),),
SizedBox(height: 21.v), SizedBox(height: 21.v),
Container( Container(
margin: EdgeInsets.only(right: 1.h), margin: EdgeInsets.only(right: 1.h),
@@ -91,8 +91,8 @@ class _BloodPressureScreenState extends State<BloodPressureScreen> {
selector: (state) => state.downPressureController, selector: (state) => state.downPressureController,
builder: (context, downPressureController) { builder: (context, downPressureController) {
return CustomTextFormField(inputFormatters: [digitsOnly], controller: downPressureController, hintText: "90".tr); return CustomTextFormField(inputFormatters: [digitsOnly], controller: downPressureController, hintText: "90".tr);
}) },),
])), ],),),
SizedBox(height: 22.v), SizedBox(height: 22.v),
Text("do_you_have_hypotension_tendency".tr, style: theme.textTheme.bodyLarge), Text("do_you_have_hypotension_tendency".tr, style: theme.textTheme.bodyLarge),
SizedBox(height: 2.v), SizedBox(height: 2.v),
@@ -105,11 +105,11 @@ class _BloodPressureScreenState extends State<BloodPressureScreen> {
icon: Container( icon: Container(
margin: EdgeInsets.fromLTRB(30.h, 11.v, 13.h, 11.v), margin: EdgeInsets.fromLTRB(30.h, 11.v, 13.h, 11.v),
decoration: BoxDecoration(borderRadius: BorderRadius.circular(1.h)), 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, hintText: "Не выбрано".tr,
items: bloodPressureModelObj?.dropdownItemList ?? [], items: bloodPressureModelObj?.dropdownItemList ?? [],
onChanged: onChangeHyper(context)); onChanged: onChangeHyper(context),);
})), },),),
SizedBox(height: 22.v), SizedBox(height: 22.v),
Text("do_you_have_hypertension_tendency".tr, style: theme.textTheme.bodyLarge), Text("do_you_have_hypertension_tendency".tr, style: theme.textTheme.bodyLarge),
SizedBox(height: 2.v), SizedBox(height: 2.v),
@@ -122,26 +122,26 @@ class _BloodPressureScreenState extends State<BloodPressureScreen> {
icon: Container( icon: Container(
margin: EdgeInsets.fromLTRB(30.h, 11.v, 13.h, 11.v), margin: EdgeInsets.fromLTRB(30.h, 11.v, 13.h, 11.v),
decoration: BoxDecoration(borderRadius: BorderRadius.circular(1.h)), 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, hintText: "Не выбрано".tr,
items: bloodPressureModelObj?.dropdownItemList ?? [], items: bloodPressureModelObj?.dropdownItemList ?? [],
onChanged: onChangeHypo(context)); onChanged: onChangeHypo(context),);
})), },),),
Spacer(), Spacer(),
BlocBuilder<BloodPressureBloc, BloodPressureState>(builder: (context, state) { BlocBuilder<BloodPressureBloc, BloodPressureState>(builder: (context, state) {
return NextStepButton( return NextStepButton(
text: "continue".tr.toUpperCase(), text: "continue".tr.toUpperCase(),
margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v),
buttonStyle: CustomButtonStyles.outlinePrimaryTL15, buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
onPressed: onTapContinue(state, context)); onPressed: onTapContinue(state, context),);
}), },),
BlocBuilder<BloodPressureBloc, BloodPressureState>(builder: (context, state) { BlocBuilder<BloodPressureBloc, BloodPressureState>(builder: (context, state) {
return GestureDetector( return GestureDetector(
onTap: onTapSkip(state, context), onTap: onTapSkip(state, context),
child: Text("skip".tr, style: theme.textTheme.bodyLarge), child: Text("skip".tr, style: theme.textTheme.bodyLarge),
); );
}), },),
]))); ],),),);
} }
onTapSkip(BloodPressureState state, BuildContext context) { onTapSkip(BloodPressureState state, BuildContext context) {
@@ -208,7 +208,7 @@ class _BloodPressureScreenState extends State<BloodPressureScreen> {
leading: leading:
AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)),
centerTitle: true, centerTitle: true,
title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio)); title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),);
} }
Function onTapBack(BuildContext context) { Function onTapBack(BuildContext context) {

View File

@@ -9,7 +9,7 @@ import 'package:eatvio_app/data/models/userRegistrationModel/user_registration_m
class BloodPressureModel extends Equatable { class BloodPressureModel extends Equatable {
UserRegistrationSheet userRegistrationSheet; UserRegistrationSheet userRegistrationSheet;
BloodPressureModel( BloodPressureModel(
{required this.userRegistrationSheet, this.dropdownItemList = const []}); {required this.userRegistrationSheet, this.dropdownItemList = const [],});
List<SelectionPopupModel> dropdownItemList; List<SelectionPopupModel> dropdownItemList;

View File

@@ -20,6 +20,6 @@ class BodyCircumferencesBloc
emit(state.copyWith( emit(state.copyWith(
chestCircumferenceController: TextEditingController(), chestCircumferenceController: TextEditingController(),
waistCircumferenceController: TextEditingController(), waistCircumferenceController: TextEditingController(),
hipCircumferenceController: TextEditingController())); hipCircumferenceController: TextEditingController(),),);
} }
} }

View File

@@ -41,11 +41,11 @@ class BodyCircumferencesScreen extends StatelessWidget {
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.onPrimary, color: theme.colorScheme.onPrimary,
borderRadius: BorderRadius.circular(8.h), 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( child: ClipRRect(
borderRadius: BorderRadius.circular(8.h), borderRadius: BorderRadius.circular(8.h),
child: LinearProgressIndicator( child: LinearProgressIndicator(
value: 0.40, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400)))), value: 0.40, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400),),),),
SizedBox(height: 39.v), SizedBox(height: 39.v),
Text("initial_measurements".tr, style: theme.textTheme.headlineSmall), Text("initial_measurements".tr, style: theme.textTheme.headlineSmall),
SizedBox(height: 93.v), SizedBox(height: 93.v),
@@ -56,8 +56,8 @@ class BodyCircumferencesScreen extends StatelessWidget {
selector: (state) => state.chestCircumferenceController, selector: (state) => state.chestCircumferenceController,
builder: (context, chestCircumferenceController) { builder: (context, chestCircumferenceController) {
return CustomTextFormField(inputFormatters: [digitsOnly], controller: chestCircumferenceController, hintText: "90".tr); return CustomTextFormField(inputFormatters: [digitsOnly], controller: chestCircumferenceController, hintText: "90".tr);
}) },),
]), ],),
SizedBox(height: 19.v), SizedBox(height: 19.v),
Text("waist_circumference".tr, style: theme.textTheme.bodyLarge), Text("waist_circumference".tr, style: theme.textTheme.bodyLarge),
SizedBox(height: 5.v), SizedBox(height: 5.v),
@@ -65,7 +65,7 @@ class BodyCircumferencesScreen extends StatelessWidget {
selector: (state) => state.waistCircumferenceController, selector: (state) => state.waistCircumferenceController,
builder: (context, waistCircumferenceController) { builder: (context, waistCircumferenceController) {
return CustomTextFormField(inputFormatters: [digitsOnly], controller: waistCircumferenceController, hintText: "60".tr); return CustomTextFormField(inputFormatters: [digitsOnly], controller: waistCircumferenceController, hintText: "60".tr);
}), },),
SizedBox(height: 21.v), SizedBox(height: 21.v),
Text("hip_circumference".tr, style: theme.textTheme.bodyLarge), Text("hip_circumference".tr, style: theme.textTheme.bodyLarge),
SizedBox(height: 3.v), SizedBox(height: 3.v),
@@ -73,17 +73,17 @@ class BodyCircumferencesScreen extends StatelessWidget {
selector: (state) => state.hipCircumferenceController, selector: (state) => state.hipCircumferenceController,
builder: (context, hipCircumferenceController) { builder: (context, hipCircumferenceController) {
return CustomTextFormField( return CustomTextFormField(
inputFormatters: [digitsOnly], controller: hipCircumferenceController, hintText: "90".tr, textInputAction: TextInputAction.done); inputFormatters: [digitsOnly], controller: hipCircumferenceController, hintText: "90".tr, textInputAction: TextInputAction.done,);
}), },),
Spacer(), Spacer(),
BlocBuilder<BodyCircumferencesBloc, BodyCircumferencesState>(builder: (context, state) { BlocBuilder<BodyCircumferencesBloc, BodyCircumferencesState>(builder: (context, state) {
return NextStepButton( return NextStepButton(
text: "continue".tr.toUpperCase(), text: "continue".tr.toUpperCase(),
margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v),
buttonStyle: CustomButtonStyles.outlinePrimaryTL15, buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
onPressed: onTapContinue(state, context)); onPressed: onTapContinue(state, context),);
}), },),
]))); ],),),);
} }
onTapContinue(BodyCircumferencesState state, BuildContext context) { onTapContinue(BodyCircumferencesState state, BuildContext context) {
@@ -133,7 +133,7 @@ class BodyCircumferencesScreen extends StatelessWidget {
leading: leading:
AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)),
centerTitle: true, centerTitle: true,
title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio)); title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),);
} }
Function onTapBack(BuildContext context) { Function onTapBack(BuildContext context) {

View File

@@ -19,7 +19,7 @@ class CityOfLivingBloc extends Bloc<CityOfLivingEvent, CityOfLivingState> {
emit(state.copyWith( emit(state.copyWith(
cityOfLivingModelObj: state.cityOfLivingModelObj?.copyWith( cityOfLivingModelObj: state.cityOfLivingModelObj?.copyWith(
dropdownItemList: fillDropdownItemList(), dropdownItemList: fillDropdownItemList(),
))); ),),);
} }
_changeDropDown( _changeDropDown(

View File

@@ -1142,7 +1142,7 @@ class CityOfLivingScreen extends StatelessWidget {
"Ярцево", "Ярцево",
"Ясногорск", "Ясногорск",
"Ясный", "Ясный",
"Яхрома" "Яхрома",
]; ];
return Scaffold( return Scaffold(
appBar: _buildAppBar(context), appBar: _buildAppBar(context),
@@ -1157,11 +1157,11 @@ class CityOfLivingScreen extends StatelessWidget {
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.onPrimary, color: theme.colorScheme.onPrimary,
borderRadius: BorderRadius.circular(8.h), 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( child: ClipRRect(
borderRadius: BorderRadius.circular(8.h), borderRadius: BorderRadius.circular(8.h),
child: LinearProgressIndicator( child: LinearProgressIndicator(
value: 0.32, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400)))), value: 0.32, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400),),),),
SizedBox(height: 39.v), SizedBox(height: 39.v),
Text("place_of_living".tr, style: theme.textTheme.headlineSmall), Text("place_of_living".tr, style: theme.textTheme.headlineSmall),
Spacer(flex: 34), Spacer(flex: 34),
@@ -1174,11 +1174,11 @@ class CityOfLivingScreen extends StatelessWidget {
icon: Container( icon: Container(
margin: EdgeInsets.fromLTRB(30.h, 11.v, 17.h, 11.v), margin: EdgeInsets.fromLTRB(30.h, 11.v, 17.h, 11.v),
decoration: BoxDecoration(borderRadius: BorderRadius.circular(1.h)), 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, hintText: "Не выбрано".tr,
items: cityOfLivingModelObj?.dropdownItemList ?? [], items: cityOfLivingModelObj?.dropdownItemList ?? [],
onChanged: onDropDownChange(context)); onChanged: onDropDownChange(context),);
}), },),
SizedBox(height: 22.v), SizedBox(height: 22.v),
Text("Населенный пункт", style: theme.textTheme.bodyLarge), Text("Населенный пункт", style: theme.textTheme.bodyLarge),
SizedBox(height: 2.v), SizedBox(height: 2.v),
@@ -1228,16 +1228,16 @@ class CityOfLivingScreen extends StatelessWidget {
); );
}, },
); );
}), },),
Spacer(flex: 65), Spacer(flex: 65),
BlocBuilder<CityOfLivingBloc, CityOfLivingState>(builder: (context, state) { BlocBuilder<CityOfLivingBloc, CityOfLivingState>(builder: (context, state) {
return NextStepButton( return NextStepButton(
text: "continue".tr.toUpperCase(), text: "continue".tr.toUpperCase(),
margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v),
buttonStyle: CustomButtonStyles.outlinePrimaryTL15, buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
onPressed: onTapContinue(state, context)); onPressed: onTapContinue(state, context),);
}), },),
]))); ],),),);
} }
onTapContinue(CityOfLivingState state, BuildContext context) { onTapContinue(CityOfLivingState state, BuildContext context) {
@@ -1260,7 +1260,7 @@ class CityOfLivingScreen extends StatelessWidget {
leading: leading:
AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)),
centerTitle: true, centerTitle: true,
title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio)); title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),);
} }
Function onTapBack(BuildContext context) { Function onTapBack(BuildContext context) {

View File

@@ -1128,7 +1128,7 @@ class CityOfLivingModel extends Equatable {
"Ярцево", "Ярцево",
"Ясногорск", "Ясногорск",
"Ясный", "Ясный",
"Яхрома" "Яхрома",
], ],
}); });

View File

@@ -19,6 +19,6 @@ class CredentialsBloc extends Bloc<CredentialsEvent, CredentialsState> {
emailController: TextEditingController(), emailController: TextEditingController(),
nameController: TextEditingController(), nameController: TextEditingController(),
passwordController: TextEditingController(), passwordController: TextEditingController(),
passwordConfirmationController: TextEditingController())); passwordConfirmationController: TextEditingController(),),);
} }
} }

View File

@@ -40,11 +40,11 @@ class CredentialsScreen extends StatelessWidget {
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.onPrimary, color: theme.colorScheme.onPrimary,
borderRadius: BorderRadius.circular(8.h), 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( child: ClipRRect(
borderRadius: BorderRadius.circular(8.h), borderRadius: BorderRadius.circular(8.h),
child: LinearProgressIndicator( child: LinearProgressIndicator(
value: 0.05, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400)))), value: 0.05, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400),),),),
SizedBox(height: 39.v), SizedBox(height: 39.v),
Text("user_registration".tr, style: theme.textTheme.headlineSmall), Text("user_registration".tr, style: theme.textTheme.headlineSmall),
SizedBox(height: 16.v), SizedBox(height: 16.v),
@@ -54,7 +54,7 @@ class CredentialsScreen extends StatelessWidget {
selector: (state) => state.emailController, selector: (state) => state.emailController,
builder: (context, emailController) { builder: (context, emailController) {
return CustomTextFormField(controller: emailController, textInputAction: TextInputAction.done); return CustomTextFormField(controller: emailController, textInputAction: TextInputAction.done);
}), },),
SizedBox(height: 22.v), SizedBox(height: 22.v),
Text("username".tr, style: theme.textTheme.bodyLarge), Text("username".tr, style: theme.textTheme.bodyLarge),
SizedBox(height: 3.v), SizedBox(height: 3.v),
@@ -62,7 +62,7 @@ class CredentialsScreen extends StatelessWidget {
selector: (state) => state.nameController, selector: (state) => state.nameController,
builder: (context, nameController) { builder: (context, nameController) {
return CustomTextFormField(controller: nameController, textInputAction: TextInputAction.done); return CustomTextFormField(controller: nameController, textInputAction: TextInputAction.done);
}), },),
SizedBox(height: 19.v), SizedBox(height: 19.v),
Text("password".tr, style: theme.textTheme.bodyLarge), Text("password".tr, style: theme.textTheme.bodyLarge),
SizedBox(height: 5.v), SizedBox(height: 5.v),
@@ -73,7 +73,7 @@ class CredentialsScreen extends StatelessWidget {
obscureText: true, obscureText: true,
controller: passwordController, controller: passwordController,
); );
}), },),
SizedBox(height: 21.v), SizedBox(height: 21.v),
Text("password_confirmation".tr, style: theme.textTheme.bodyLarge), Text("password_confirmation".tr, style: theme.textTheme.bodyLarge),
SizedBox(height: 3.v), SizedBox(height: 3.v),
@@ -81,16 +81,16 @@ class CredentialsScreen extends StatelessWidget {
selector: (state) => state.passwordConfirmationController, selector: (state) => state.passwordConfirmationController,
builder: (context, passwordConfirmationController) { builder: (context, passwordConfirmationController) {
return CustomTextFormField(obscureText: true, controller: passwordConfirmationController, textInputAction: TextInputAction.done); return CustomTextFormField(obscureText: true, controller: passwordConfirmationController, textInputAction: TextInputAction.done);
}), },),
Spacer(), Spacer(),
BlocBuilder<CredentialsBloc, CredentialsState>(builder: (context, state) { BlocBuilder<CredentialsBloc, CredentialsState>(builder: (context, state) {
return NextStepButton( return NextStepButton(
text: "continue".tr.toUpperCase(), text: "continue".tr.toUpperCase(),
margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v),
buttonStyle: CustomButtonStyles.outlinePrimaryTL15, buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
onPressed: onTapContinue(state, context)); onPressed: onTapContinue(state, context),);
}), },),
]))); ],),),);
} }
onTapContinue(CredentialsState state, BuildContext context) { onTapContinue(CredentialsState state, BuildContext context) {

View File

@@ -49,11 +49,11 @@ class _DateOfBirthScreenState extends State<DateOfBirthScreen> {
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.onPrimary, color: theme.colorScheme.onPrimary,
borderRadius: BorderRadius.circular(8.h), 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( child: ClipRRect(
borderRadius: BorderRadius.circular(8.h), borderRadius: BorderRadius.circular(8.h),
child: LinearProgressIndicator( child: LinearProgressIndicator(
value: 0.24, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400)))), value: 0.24, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400),),),),
SizedBox(height: 38.v), SizedBox(height: 38.v),
Text("date_of_birth".tr, style: theme.textTheme.headlineSmall), Text("date_of_birth".tr, style: theme.textTheme.headlineSmall),
Spacer(flex: 39), Spacer(flex: 39),
@@ -64,10 +64,10 @@ class _DateOfBirthScreenState extends State<DateOfBirthScreen> {
text: "continue".tr.toUpperCase(), text: "continue".tr.toUpperCase(),
margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v),
buttonStyle: CustomButtonStyles.outlinePrimaryTL15, buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
onPressed: onTapContinue(state, context)); onPressed: onTapContinue(state, context),);
}), },),
]))); ],),),);
}); },);
} }
onTapContinue(DateOfBirthState state, BuildContext context) { onTapContinue(DateOfBirthState state, BuildContext context) {
@@ -85,7 +85,7 @@ class _DateOfBirthScreenState extends State<DateOfBirthScreen> {
leading: leading:
AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)),
centerTitle: true, centerTitle: true,
title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio)); title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),);
} }
Function onTapBack(BuildContext context) { Function onTapBack(BuildContext context) {
@@ -107,9 +107,9 @@ class _DateOfBirthScreenState extends State<DateOfBirthScreen> {
alignment: Alignment.center, alignment: Alignment.center,
child: GestureDetector( child: GestureDetector(
onTap: onTapCalendar(context), onTap: onTapCalendar(context),
child: Text('${selectedDate.day}.${selectedDate.month}.${selectedDate.year}', style: theme.textTheme.titleMedium))), child: Text('${selectedDate.day}.${selectedDate.month}.${selectedDate.year}', style: theme.textTheme.titleMedium),),),
SizedBox(height: 6.v) SizedBox(height: 6.v),
])); ],),);
} }
onTapCalendar(BuildContext context) { onTapCalendar(BuildContext context) {

View File

@@ -17,6 +17,6 @@ class FavoriteFoodsBloc extends Bloc<FavoriteFoodsEvent, FavoriteFoodsState> {
) async { ) async {
emit(state.copyWith( emit(state.copyWith(
favoriteFoodsController: TextEditingController(), favoriteFoodsController: TextEditingController(),
unfavoriteFoodsController: TextEditingController())); unfavoriteFoodsController: TextEditingController(),),);
} }
} }

View File

@@ -18,7 +18,7 @@ class FavoriteFoodsScreen extends StatefulWidget {
return BlocProvider<FavoriteFoodsBloc>( return BlocProvider<FavoriteFoodsBloc>(
create: (context) => create: (context) =>
FavoriteFoodsBloc(FavoriteFoodsState(favoriteFoodsModelObj: FavoriteFoodsModel(userRegistrationSheet: sheet)))..add(FavoriteFoodsInitialEvent()), FavoriteFoodsBloc(FavoriteFoodsState(favoriteFoodsModelObj: FavoriteFoodsModel(userRegistrationSheet: sheet)))..add(FavoriteFoodsInitialEvent()),
child: FavoriteFoodsScreen()); child: FavoriteFoodsScreen(),);
} }
@override @override
@@ -42,17 +42,17 @@ class _FavoriteFoodsScreenState extends State<FavoriteFoodsScreen> {
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.onPrimary, color: theme.colorScheme.onPrimary,
borderRadius: BorderRadius.circular(8.h), 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( child: ClipRRect(
borderRadius: BorderRadius.circular(8.h), borderRadius: BorderRadius.circular(8.h),
child: LinearProgressIndicator( child: LinearProgressIndicator(
value: 0.90, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400)))), value: 0.90, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400),),),),
SizedBox(height: 19.v), SizedBox(height: 19.v),
Container( Container(
width: 327.h, width: 327.h,
margin: EdgeInsets.only(left: 8.h, right: 7.h), margin: EdgeInsets.only(left: 8.h, right: 7.h),
child: Text("favorite_unfavorite_foods".tr, 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), SizedBox(height: 13.v),
_buildTextFormFieldFav(context), _buildTextFormFieldFav(context),
SizedBox(height: 12.v), SizedBox(height: 12.v),
@@ -63,15 +63,15 @@ class _FavoriteFoodsScreenState extends State<FavoriteFoodsScreen> {
text: "continue".tr.toUpperCase(), text: "continue".tr.toUpperCase(),
margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 40.v), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 40.v),
buttonStyle: CustomButtonStyles.outlinePrimaryTL15, buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
onPressed: onTapContinue(state, context)); onPressed: onTapContinue(state, context),);
}), },),
BlocBuilder<FavoriteFoodsBloc, FavoriteFoodsState>(builder: (context, state) { BlocBuilder<FavoriteFoodsBloc, FavoriteFoodsState>(builder: (context, state) {
return GestureDetector( return GestureDetector(
onTap: onTapSkip(state, context), onTap: onTapSkip(state, context),
child: Text("skip".tr, style: theme.textTheme.bodyLarge), child: Text("skip".tr, style: theme.textTheme.bodyLarge),
); );
}), },),
]))); ],),),);
} }
onTapSkip(FavoriteFoodsState state, BuildContext context) { onTapSkip(FavoriteFoodsState state, BuildContext context) {
@@ -97,7 +97,7 @@ class _FavoriteFoodsScreenState extends State<FavoriteFoodsScreen> {
leading: leading:
AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 18.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 18.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)),
centerTitle: true, centerTitle: true,
title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio)); title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),);
} }
Function onTapBack(BuildContext context) { Function onTapBack(BuildContext context) {
@@ -115,8 +115,8 @@ class _FavoriteFoodsScreenState extends State<FavoriteFoodsScreen> {
selector: (state) => state.favoriteFoodsController, selector: (state) => state.favoriteFoodsController,
builder: (context, favoriteFoodsController) { builder: (context, favoriteFoodsController) {
return CustomTextFormField(controller: favoriteFoodsController, hintText: "enter_information".tr, maxLines: 7); return CustomTextFormField(controller: favoriteFoodsController, hintText: "enter_information".tr, maxLines: 7);
}) },),
]); ],);
} }
/// Section Widget /// Section Widget
@@ -128,9 +128,9 @@ class _FavoriteFoodsScreenState extends State<FavoriteFoodsScreen> {
selector: (state) => state.unfavoriteFoodsController, selector: (state) => state.unfavoriteFoodsController,
builder: (context, unfavoriteFoodsController) { builder: (context, unfavoriteFoodsController) {
return CustomTextFormField( 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. /// Navigates to the previous screen.

View File

@@ -18,7 +18,7 @@ class FavoriteSportsScreen extends StatefulWidget {
return BlocProvider<FavoriteSportsBloc>( return BlocProvider<FavoriteSportsBloc>(
create: (context) => FavoriteSportsBloc(FavoriteSportsState(favoriteSportsModelObj: FavoriteSportsModel(userRegistrationSheet: sheet))) create: (context) => FavoriteSportsBloc(FavoriteSportsState(favoriteSportsModelObj: FavoriteSportsModel(userRegistrationSheet: sheet)))
..add(FavoriteSportsInitialEvent()), ..add(FavoriteSportsInitialEvent()),
child: FavoriteSportsScreen()); child: FavoriteSportsScreen(),);
} }
@override @override
@@ -42,11 +42,11 @@ class _FavoriteSportsScreenState extends State<FavoriteSportsScreen> {
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.onPrimary, color: theme.colorScheme.onPrimary,
borderRadius: BorderRadius.circular(8.h), 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( child: ClipRRect(
borderRadius: BorderRadius.circular(8.h), borderRadius: BorderRadius.circular(8.h),
child: LinearProgressIndicator( child: LinearProgressIndicator(
value: 0.83, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400)))), value: 0.83, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400),),),),
SizedBox(height: 38.v), SizedBox(height: 38.v),
Text("your_favorite_sports".tr, style: theme.textTheme.headlineSmall), Text("your_favorite_sports".tr, style: theme.textTheme.headlineSmall),
Spacer(flex: 32), Spacer(flex: 32),
@@ -57,15 +57,15 @@ class _FavoriteSportsScreenState extends State<FavoriteSportsScreen> {
text: "continue".tr.toUpperCase(), text: "continue".tr.toUpperCase(),
margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v),
buttonStyle: CustomButtonStyles.outlinePrimaryTL15, buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
onPressed: onTapContinue(state, context)); onPressed: onTapContinue(state, context),);
}), },),
BlocBuilder<FavoriteSportsBloc, FavoriteSportsState>(builder: (context, state) { BlocBuilder<FavoriteSportsBloc, FavoriteSportsState>(builder: (context, state) {
return GestureDetector( return GestureDetector(
onTap: onTapSkip(state, context), onTap: onTapSkip(state, context),
child: Text("skip".tr, style: theme.textTheme.bodyLarge), child: Text("skip".tr, style: theme.textTheme.bodyLarge),
); );
}), },),
]))); ],),),);
} }
onTapSkip(FavoriteSportsState state, BuildContext context) { onTapSkip(FavoriteSportsState state, BuildContext context) {
@@ -89,7 +89,7 @@ class _FavoriteSportsScreenState extends State<FavoriteSportsScreen> {
leading: leading:
AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)), AppbarLeadingImage(imagePath: ImageConstant.imgArrowLeft, margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v), onTap: onTapBack(context)),
centerTitle: true, centerTitle: true,
title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio)); title: AppbarTitleImage(imagePath: ImageConstant.imgLogoEatvio),);
} }
Function onTapBack(BuildContext context) { Function onTapBack(BuildContext context) {
@@ -111,9 +111,9 @@ class _FavoriteSportsScreenState extends State<FavoriteSportsScreen> {
hintText: hintText:
"Я занимаюсь плаванием , почти каждый вечер прогулки на свежем воздухе, пару раз в месяц играю в волейбол. Стараюсь не сидеть на месте!", "Я занимаюсь плаванием , почти каждый вечер прогулки на свежем воздухе, пару раз в месяц играю в волейбол. Стараюсь не сидеть на месте!",
textInputAction: TextInputAction.done, textInputAction: TextInputAction.done,
maxLines: 8); maxLines: 8,);
}) },),
]); ],);
} }
onTapArrowLeft(BuildContext context) { onTapArrowLeft(BuildContext context) {

View File

@@ -20,7 +20,7 @@ class GenderScreen extends StatefulWidget {
genderModelObj: GenderModel(userRegistrationSheet: sheet), genderModelObj: GenderModel(userRegistrationSheet: sheet),
), ),
)..add(GenderInitialEvent()), )..add(GenderInitialEvent()),
child: GenderScreen()); child: GenderScreen(),);
} }
@override @override
@@ -45,11 +45,11 @@ class _GenderScreenState extends State<GenderScreen> {
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.onPrimary, color: theme.colorScheme.onPrimary,
borderRadius: BorderRadius.circular(8.h), 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( child: ClipRRect(
borderRadius: BorderRadius.circular(8.h), borderRadius: BorderRadius.circular(8.h),
child: LinearProgressIndicator( child: LinearProgressIndicator(
value: 0.16, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400)))), value: 0.16, backgroundColor: theme.colorScheme.onPrimary, valueColor: AlwaysStoppedAnimation<Color>(appTheme.blueA400),),),),
SizedBox(height: 36.v), SizedBox(height: 36.v),
Text("your_gender".tr, style: theme.textTheme.headlineSmall), Text("your_gender".tr, style: theme.textTheme.headlineSmall),
RadioListTile( RadioListTile(
@@ -80,10 +80,10 @@ class _GenderScreenState extends State<GenderScreen> {
text: "continue".tr.toUpperCase(), text: "continue".tr.toUpperCase(),
margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v), margin: EdgeInsets.only(left: 16.h, right: 16.h, bottom: 50.v),
buttonStyle: CustomButtonStyles.outlinePrimaryTL15, buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
onPressed: onTapNext(state, context)); onPressed: onTapNext(state, context),);
}), },),
]))); ],),),);
}); },);
} }
onTapNext(GenderState state, BuildContext context) { onTapNext(GenderState state, BuildContext context) {

Some files were not shown because too many files have changed in this diff Show More