Merge remote-tracking branch 'upstream/main'

This commit is contained in:
Username1548
2025-02-20 16:58:14 +07:00
158 changed files with 22292 additions and 227 deletions

View File

@@ -1,123 +0,0 @@
import 'dart:convert';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/credentials_storage.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/token_storage.dart';
import 'package:eatvio_app/features/auth/const/strings.dart';
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:go_router/go_router.dart';
import 'package:http/http.dart' as http;
import 'package:webview_flutter/webview_flutter.dart';
class AuthScreen extends StatefulWidget {
final bool needLogout;
const AuthScreen({
this.needLogout = false,
});
@override
State<AuthScreen> createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen> {
bool checkboxState = false;
bool hidePassword = true;
final baseUrlController = TextEditingController();
late final WebViewController _controller;
String email = '';
String password = '';
bool needLogout = false;
Future<void> logoutFromWeb() async {
await CredentialsStorage.removeCredentials();
await _controller.runJavaScript('''
document.querySelector('.header-list__link button[type="submit"]').click();
''');
}
Future<void> loginInApplication() async {
final credentialsFromStorage = await CredentialsStorage.getCredentialsFromStorage();
final Map<String, String> credentials = {
'email': credentialsFromStorage['email']!,
'password': credentialsFromStorage['password']!,
};
final response = await http.post(
Uri.parse(baseUrl + '/api/login'),
headers: {'Content-Type': 'application/json'},
body: json.encode(credentials),
encoding: utf8,
);
var res = await jsonDecode(response.body);
final token = res['token'];
await TokenStorage.saveTokenInStorage(token);
await Future.delayed(Duration.zero, () => GoRouter.of(context).go('/my-profile-screen'));
await sl<ProfileAvatarCubit>().getMyProfile();
}
@override
void initState() {
super.initState();
needLogout = widget.needLogout;
_controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..addJavaScriptChannel(
'FlutterChannel',
onMessageReceived: (JavaScriptMessage message) {
final data = jsonDecode(message.message);
email = data['email'];
password = data['password'];
},
)
..setNavigationDelegate(
NavigationDelegate(
onPageFinished: (String url) async {
final bool tokenInStorage = await TokenStorage.haveTokenInStorage();
final bool credentialsInStorage = await CredentialsStorage.haveCredentialsInStorage();
if (needLogout) {
await logoutFromWeb();
needLogout = false;
} else if (!url.contains('profile') && !url.contains('registration')) {
await _controller.runJavaScript(jsChannelAuthScript);
} else if (url.contains('profile')) {
if (credentialsInStorage) {
await loginInApplication();
} else {
if (email.isNotEmpty && password.isNotEmpty) {
await CredentialsStorage.saveCredentials(email, password);
await loginInApplication();
} else {
await logoutFromWeb();
}
}
} else {
if (tokenInStorage && credentialsInStorage) {
GoRouter.of(context).go('/my-profile-screen');
} else if (!tokenInStorage && credentialsInStorage) {
await loginInApplication();
}
}
},
),
)
..loadRequest(Uri.parse(baseUrl));
}
@override
Widget build(BuildContext context) {
FlutterNativeSplash.remove();
return Scaffold(
appBar: AppBar(
toolbarHeight: 0,
),
body: SafeArea(
child: WebViewWidget(controller: _controller),
),
);
}
}

View File

@@ -1,22 +0,0 @@
const String jsChannelAuthScript = '''
function initializeListeners() {
const emailInput = document.getElementById("inputEmail_main");
const passwordInput = document.getElementById("inputPassword_main");
if (emailInput && passwordInput) {
function sendToFlutter() {
const email = emailInput.value;
const password = passwordInput.value;
const data = JSON.stringify({ email: email, password: password });
if (window.FlutterChannel) {
window.FlutterChannel.postMessage(data);
}
}
emailInput.addEventListener("input", sendToFlutter);
passwordInput.addEventListener("input", sendToFlutter);
} else {
console.error("Email or Password input not found.");
}
}
document.addEventListener("DOMContentLoaded", initializeListeners);
initializeListeners();
''';

View File

@@ -0,0 +1,15 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'credentials_model.freezed.dart';
part 'credentials_model.g.dart';
@freezed
class CredentialsModel with _$CredentialsModel {
const factory CredentialsModel({
required String email,
required String password,
}) = _CredentialsModel;
factory CredentialsModel.fromJson(Map<String, Object?> json) => _$CredentialsModelFromJson(json);
}

View File

@@ -0,0 +1,184 @@
// 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 'credentials_model.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');
CredentialsModel _$CredentialsModelFromJson(Map<String, dynamic> json) {
return _CredentialsModel.fromJson(json);
}
/// @nodoc
mixin _$CredentialsModel {
String get email => throw _privateConstructorUsedError;
String get password => throw _privateConstructorUsedError;
/// Serializes this CredentialsModel to a JSON map.
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
/// Create a copy of CredentialsModel
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
$CredentialsModelCopyWith<CredentialsModel> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $CredentialsModelCopyWith<$Res> {
factory $CredentialsModelCopyWith(
CredentialsModel value, $Res Function(CredentialsModel) then) =
_$CredentialsModelCopyWithImpl<$Res, CredentialsModel>;
@useResult
$Res call({String email, String password});
}
/// @nodoc
class _$CredentialsModelCopyWithImpl<$Res, $Val extends CredentialsModel>
implements $CredentialsModelCopyWith<$Res> {
_$CredentialsModelCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
/// Create a copy of CredentialsModel
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? email = null,
Object? password = null,
}) {
return _then(_value.copyWith(
email: null == email
? _value.email
: email // ignore: cast_nullable_to_non_nullable
as String,
password: null == password
? _value.password
: password // ignore: cast_nullable_to_non_nullable
as String,
) as $Val);
}
}
/// @nodoc
abstract class _$$CredentialsModelImplCopyWith<$Res>
implements $CredentialsModelCopyWith<$Res> {
factory _$$CredentialsModelImplCopyWith(_$CredentialsModelImpl value,
$Res Function(_$CredentialsModelImpl) then) =
__$$CredentialsModelImplCopyWithImpl<$Res>;
@override
@useResult
$Res call({String email, String password});
}
/// @nodoc
class __$$CredentialsModelImplCopyWithImpl<$Res>
extends _$CredentialsModelCopyWithImpl<$Res, _$CredentialsModelImpl>
implements _$$CredentialsModelImplCopyWith<$Res> {
__$$CredentialsModelImplCopyWithImpl(_$CredentialsModelImpl _value,
$Res Function(_$CredentialsModelImpl) _then)
: super(_value, _then);
/// Create a copy of CredentialsModel
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? email = null,
Object? password = null,
}) {
return _then(_$CredentialsModelImpl(
email: null == email
? _value.email
: email // ignore: cast_nullable_to_non_nullable
as String,
password: null == password
? _value.password
: password // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
/// @nodoc
@JsonSerializable()
class _$CredentialsModelImpl implements _CredentialsModel {
const _$CredentialsModelImpl({required this.email, required this.password});
factory _$CredentialsModelImpl.fromJson(Map<String, dynamic> json) =>
_$$CredentialsModelImplFromJson(json);
@override
final String email;
@override
final String password;
@override
String toString() {
return 'CredentialsModel(email: $email, password: $password)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$CredentialsModelImpl &&
(identical(other.email, email) || other.email == email) &&
(identical(other.password, password) ||
other.password == password));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType, email, password);
/// Create a copy of CredentialsModel
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@override
@pragma('vm:prefer-inline')
_$$CredentialsModelImplCopyWith<_$CredentialsModelImpl> get copyWith =>
__$$CredentialsModelImplCopyWithImpl<_$CredentialsModelImpl>(
this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$$CredentialsModelImplToJson(
this,
);
}
}
abstract class _CredentialsModel implements CredentialsModel {
const factory _CredentialsModel(
{required final String email,
required final String password}) = _$CredentialsModelImpl;
factory _CredentialsModel.fromJson(Map<String, dynamic> json) =
_$CredentialsModelImpl.fromJson;
@override
String get email;
@override
String get password;
/// Create a copy of CredentialsModel
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
_$$CredentialsModelImplCopyWith<_$CredentialsModelImpl> get copyWith =>
throw _privateConstructorUsedError;
}

View File

@@ -0,0 +1,21 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'credentials_model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_$CredentialsModelImpl _$$CredentialsModelImplFromJson(
Map<String, dynamic> json) =>
_$CredentialsModelImpl(
email: json['email'] as String,
password: json['password'] as String,
);
Map<String, dynamic> _$$CredentialsModelImplToJson(
_$CredentialsModelImpl instance) =>
<String, dynamic>{
'email': instance.email,
'password': instance.password,
};

View File

@@ -0,0 +1,14 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'token_model.freezed.dart';
part 'token_model.g.dart';
@freezed
class TokenModel with _$TokenModel {
const factory TokenModel({
required String token,
}) = _TokenModel;
factory TokenModel.fromJson(Map<String, Object?> json) => _$TokenModelFromJson(json);
}

View File

@@ -0,0 +1,164 @@
// 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 'token_model.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');
TokenModel _$TokenModelFromJson(Map<String, dynamic> json) {
return _TokenModel.fromJson(json);
}
/// @nodoc
mixin _$TokenModel {
String get token => throw _privateConstructorUsedError;
/// Serializes this TokenModel to a JSON map.
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
/// Create a copy of TokenModel
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
$TokenModelCopyWith<TokenModel> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $TokenModelCopyWith<$Res> {
factory $TokenModelCopyWith(
TokenModel value, $Res Function(TokenModel) then) =
_$TokenModelCopyWithImpl<$Res, TokenModel>;
@useResult
$Res call({String token});
}
/// @nodoc
class _$TokenModelCopyWithImpl<$Res, $Val extends TokenModel>
implements $TokenModelCopyWith<$Res> {
_$TokenModelCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
/// Create a copy of TokenModel
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? token = null,
}) {
return _then(_value.copyWith(
token: null == token
? _value.token
: token // ignore: cast_nullable_to_non_nullable
as String,
) as $Val);
}
}
/// @nodoc
abstract class _$$TokenModelImplCopyWith<$Res>
implements $TokenModelCopyWith<$Res> {
factory _$$TokenModelImplCopyWith(
_$TokenModelImpl value, $Res Function(_$TokenModelImpl) then) =
__$$TokenModelImplCopyWithImpl<$Res>;
@override
@useResult
$Res call({String token});
}
/// @nodoc
class __$$TokenModelImplCopyWithImpl<$Res>
extends _$TokenModelCopyWithImpl<$Res, _$TokenModelImpl>
implements _$$TokenModelImplCopyWith<$Res> {
__$$TokenModelImplCopyWithImpl(
_$TokenModelImpl _value, $Res Function(_$TokenModelImpl) _then)
: super(_value, _then);
/// Create a copy of TokenModel
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? token = null,
}) {
return _then(_$TokenModelImpl(
token: null == token
? _value.token
: token // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
/// @nodoc
@JsonSerializable()
class _$TokenModelImpl implements _TokenModel {
const _$TokenModelImpl({required this.token});
factory _$TokenModelImpl.fromJson(Map<String, dynamic> json) =>
_$$TokenModelImplFromJson(json);
@override
final String token;
@override
String toString() {
return 'TokenModel(token: $token)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$TokenModelImpl &&
(identical(other.token, token) || other.token == token));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType, token);
/// Create a copy of TokenModel
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@override
@pragma('vm:prefer-inline')
_$$TokenModelImplCopyWith<_$TokenModelImpl> get copyWith =>
__$$TokenModelImplCopyWithImpl<_$TokenModelImpl>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$$TokenModelImplToJson(
this,
);
}
}
abstract class _TokenModel implements TokenModel {
const factory _TokenModel({required final String token}) = _$TokenModelImpl;
factory _TokenModel.fromJson(Map<String, dynamic> json) =
_$TokenModelImpl.fromJson;
@override
String get token;
/// Create a copy of TokenModel
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
_$$TokenModelImplCopyWith<_$TokenModelImpl> get copyWith =>
throw _privateConstructorUsedError;
}

View File

@@ -0,0 +1,17 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'token_model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_$TokenModelImpl _$$TokenModelImplFromJson(Map<String, dynamic> json) =>
_$TokenModelImpl(
token: json['token'] as String,
);
Map<String, dynamic> _$$TokenModelImplToJson(_$TokenModelImpl instance) =>
<String, dynamic>{
'token': instance.token,
};

View File

@@ -0,0 +1,39 @@
import 'package:eatvio_app/core/app_router.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/token_storage.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/auth_state.dart';
import 'package:eatvio_app/features/auth/repositories/auth_repository.dart';
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
class AuthCubit extends Cubit<AuthState> {
final AuthRepository authRepository;
AuthCubit({
required this.authRepository,
}) : super(AuthState());
getTokenByCredentials(String email, String password) async {
emit(AuthState.loading());
try {
final token = (await authRepository.getTokenByCredentials(
email,
password,
))
.token;
print(token);
emit(
AuthState.loaded(
token: token,
),
);
await TokenStorage.saveTokenInStorage(token);
await sl<ProfileAvatarCubit>().getMyProfile();
AppRouter.navigatorKey.currentContext?.go('/my-profile-screen');
} catch (e) {
print(e);
emit(AuthState.error(errorMessage: '$e'));
}
}
}

View File

@@ -0,0 +1,18 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'auth_state.freezed.dart';
@freezed
class AuthState with _$AuthState {
const factory AuthState() = _AuthState;
const factory AuthState.loading() = AuthStateLoading;
const factory AuthState.loaded({
required String token,
}) = AuthStateLoaded;
const factory AuthState.error({
required String errorMessage,
}) = AuthStateError;
}

View File

@@ -0,0 +1,632 @@
// 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 'auth_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 _$AuthState {
@optionalTypeArgs
TResult when<TResult extends Object?>(
TResult Function() $default, {
required TResult Function() loading,
required TResult Function(String token) loaded,
required TResult Function(String errorMessage) error,
}) =>
throw _privateConstructorUsedError;
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function()? $default, {
TResult? Function()? loading,
TResult? Function(String token)? loaded,
TResult? Function(String errorMessage)? error,
}) =>
throw _privateConstructorUsedError;
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function()? $default, {
TResult Function()? loading,
TResult Function(String token)? loaded,
TResult Function(String errorMessage)? error,
required TResult orElse(),
}) =>
throw _privateConstructorUsedError;
@optionalTypeArgs
TResult map<TResult extends Object?>(
TResult Function(_AuthState value) $default, {
required TResult Function(AuthStateLoading value) loading,
required TResult Function(AuthStateLoaded value) loaded,
required TResult Function(AuthStateError value) error,
}) =>
throw _privateConstructorUsedError;
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>(
TResult? Function(_AuthState value)? $default, {
TResult? Function(AuthStateLoading value)? loading,
TResult? Function(AuthStateLoaded value)? loaded,
TResult? Function(AuthStateError value)? error,
}) =>
throw _privateConstructorUsedError;
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>(
TResult Function(_AuthState value)? $default, {
TResult Function(AuthStateLoading value)? loading,
TResult Function(AuthStateLoaded value)? loaded,
TResult Function(AuthStateError value)? error,
required TResult orElse(),
}) =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $AuthStateCopyWith<$Res> {
factory $AuthStateCopyWith(AuthState value, $Res Function(AuthState) then) =
_$AuthStateCopyWithImpl<$Res, AuthState>;
}
/// @nodoc
class _$AuthStateCopyWithImpl<$Res, $Val extends AuthState>
implements $AuthStateCopyWith<$Res> {
_$AuthStateCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
/// Create a copy of AuthState
/// with the given fields replaced by the non-null parameter values.
}
/// @nodoc
abstract class _$$AuthStateImplCopyWith<$Res> {
factory _$$AuthStateImplCopyWith(
_$AuthStateImpl value, $Res Function(_$AuthStateImpl) then) =
__$$AuthStateImplCopyWithImpl<$Res>;
}
/// @nodoc
class __$$AuthStateImplCopyWithImpl<$Res>
extends _$AuthStateCopyWithImpl<$Res, _$AuthStateImpl>
implements _$$AuthStateImplCopyWith<$Res> {
__$$AuthStateImplCopyWithImpl(
_$AuthStateImpl _value, $Res Function(_$AuthStateImpl) _then)
: super(_value, _then);
/// Create a copy of AuthState
/// with the given fields replaced by the non-null parameter values.
}
/// @nodoc
class _$AuthStateImpl implements _AuthState {
const _$AuthStateImpl();
@override
String toString() {
return 'AuthState()';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is _$AuthStateImpl);
}
@override
int get hashCode => runtimeType.hashCode;
@override
@optionalTypeArgs
TResult when<TResult extends Object?>(
TResult Function() $default, {
required TResult Function() loading,
required TResult Function(String token) loaded,
required TResult Function(String errorMessage) error,
}) {
return $default();
}
@override
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function()? $default, {
TResult? Function()? loading,
TResult? Function(String token)? loaded,
TResult? Function(String errorMessage)? error,
}) {
return $default?.call();
}
@override
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function()? $default, {
TResult Function()? loading,
TResult Function(String token)? loaded,
TResult Function(String errorMessage)? error,
required TResult orElse(),
}) {
if ($default != null) {
return $default();
}
return orElse();
}
@override
@optionalTypeArgs
TResult map<TResult extends Object?>(
TResult Function(_AuthState value) $default, {
required TResult Function(AuthStateLoading value) loading,
required TResult Function(AuthStateLoaded value) loaded,
required TResult Function(AuthStateError value) error,
}) {
return $default(this);
}
@override
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>(
TResult? Function(_AuthState value)? $default, {
TResult? Function(AuthStateLoading value)? loading,
TResult? Function(AuthStateLoaded value)? loaded,
TResult? Function(AuthStateError value)? error,
}) {
return $default?.call(this);
}
@override
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>(
TResult Function(_AuthState value)? $default, {
TResult Function(AuthStateLoading value)? loading,
TResult Function(AuthStateLoaded value)? loaded,
TResult Function(AuthStateError value)? error,
required TResult orElse(),
}) {
if ($default != null) {
return $default(this);
}
return orElse();
}
}
abstract class _AuthState implements AuthState {
const factory _AuthState() = _$AuthStateImpl;
}
/// @nodoc
abstract class _$$AuthStateLoadingImplCopyWith<$Res> {
factory _$$AuthStateLoadingImplCopyWith(_$AuthStateLoadingImpl value,
$Res Function(_$AuthStateLoadingImpl) then) =
__$$AuthStateLoadingImplCopyWithImpl<$Res>;
}
/// @nodoc
class __$$AuthStateLoadingImplCopyWithImpl<$Res>
extends _$AuthStateCopyWithImpl<$Res, _$AuthStateLoadingImpl>
implements _$$AuthStateLoadingImplCopyWith<$Res> {
__$$AuthStateLoadingImplCopyWithImpl(_$AuthStateLoadingImpl _value,
$Res Function(_$AuthStateLoadingImpl) _then)
: super(_value, _then);
/// Create a copy of AuthState
/// with the given fields replaced by the non-null parameter values.
}
/// @nodoc
class _$AuthStateLoadingImpl implements AuthStateLoading {
const _$AuthStateLoadingImpl();
@override
String toString() {
return 'AuthState.loading()';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is _$AuthStateLoadingImpl);
}
@override
int get hashCode => runtimeType.hashCode;
@override
@optionalTypeArgs
TResult when<TResult extends Object?>(
TResult Function() $default, {
required TResult Function() loading,
required TResult Function(String token) loaded,
required TResult Function(String errorMessage) error,
}) {
return loading();
}
@override
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function()? $default, {
TResult? Function()? loading,
TResult? Function(String token)? loaded,
TResult? Function(String errorMessage)? error,
}) {
return loading?.call();
}
@override
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function()? $default, {
TResult Function()? loading,
TResult Function(String token)? loaded,
TResult Function(String errorMessage)? error,
required TResult orElse(),
}) {
if (loading != null) {
return loading();
}
return orElse();
}
@override
@optionalTypeArgs
TResult map<TResult extends Object?>(
TResult Function(_AuthState value) $default, {
required TResult Function(AuthStateLoading value) loading,
required TResult Function(AuthStateLoaded value) loaded,
required TResult Function(AuthStateError value) error,
}) {
return loading(this);
}
@override
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>(
TResult? Function(_AuthState value)? $default, {
TResult? Function(AuthStateLoading value)? loading,
TResult? Function(AuthStateLoaded value)? loaded,
TResult? Function(AuthStateError value)? error,
}) {
return loading?.call(this);
}
@override
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>(
TResult Function(_AuthState value)? $default, {
TResult Function(AuthStateLoading value)? loading,
TResult Function(AuthStateLoaded value)? loaded,
TResult Function(AuthStateError value)? error,
required TResult orElse(),
}) {
if (loading != null) {
return loading(this);
}
return orElse();
}
}
abstract class AuthStateLoading implements AuthState {
const factory AuthStateLoading() = _$AuthStateLoadingImpl;
}
/// @nodoc
abstract class _$$AuthStateLoadedImplCopyWith<$Res> {
factory _$$AuthStateLoadedImplCopyWith(_$AuthStateLoadedImpl value,
$Res Function(_$AuthStateLoadedImpl) then) =
__$$AuthStateLoadedImplCopyWithImpl<$Res>;
@useResult
$Res call({String token});
}
/// @nodoc
class __$$AuthStateLoadedImplCopyWithImpl<$Res>
extends _$AuthStateCopyWithImpl<$Res, _$AuthStateLoadedImpl>
implements _$$AuthStateLoadedImplCopyWith<$Res> {
__$$AuthStateLoadedImplCopyWithImpl(
_$AuthStateLoadedImpl _value, $Res Function(_$AuthStateLoadedImpl) _then)
: super(_value, _then);
/// Create a copy of AuthState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? token = null,
}) {
return _then(_$AuthStateLoadedImpl(
token: null == token
? _value.token
: token // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
/// @nodoc
class _$AuthStateLoadedImpl implements AuthStateLoaded {
const _$AuthStateLoadedImpl({required this.token});
@override
final String token;
@override
String toString() {
return 'AuthState.loaded(token: $token)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$AuthStateLoadedImpl &&
(identical(other.token, token) || other.token == token));
}
@override
int get hashCode => Object.hash(runtimeType, token);
/// Create a copy of AuthState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@override
@pragma('vm:prefer-inline')
_$$AuthStateLoadedImplCopyWith<_$AuthStateLoadedImpl> get copyWith =>
__$$AuthStateLoadedImplCopyWithImpl<_$AuthStateLoadedImpl>(
this, _$identity);
@override
@optionalTypeArgs
TResult when<TResult extends Object?>(
TResult Function() $default, {
required TResult Function() loading,
required TResult Function(String token) loaded,
required TResult Function(String errorMessage) error,
}) {
return loaded(token);
}
@override
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function()? $default, {
TResult? Function()? loading,
TResult? Function(String token)? loaded,
TResult? Function(String errorMessage)? error,
}) {
return loaded?.call(token);
}
@override
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function()? $default, {
TResult Function()? loading,
TResult Function(String token)? loaded,
TResult Function(String errorMessage)? error,
required TResult orElse(),
}) {
if (loaded != null) {
return loaded(token);
}
return orElse();
}
@override
@optionalTypeArgs
TResult map<TResult extends Object?>(
TResult Function(_AuthState value) $default, {
required TResult Function(AuthStateLoading value) loading,
required TResult Function(AuthStateLoaded value) loaded,
required TResult Function(AuthStateError value) error,
}) {
return loaded(this);
}
@override
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>(
TResult? Function(_AuthState value)? $default, {
TResult? Function(AuthStateLoading value)? loading,
TResult? Function(AuthStateLoaded value)? loaded,
TResult? Function(AuthStateError value)? error,
}) {
return loaded?.call(this);
}
@override
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>(
TResult Function(_AuthState value)? $default, {
TResult Function(AuthStateLoading value)? loading,
TResult Function(AuthStateLoaded value)? loaded,
TResult Function(AuthStateError value)? error,
required TResult orElse(),
}) {
if (loaded != null) {
return loaded(this);
}
return orElse();
}
}
abstract class AuthStateLoaded implements AuthState {
const factory AuthStateLoaded({required final String token}) =
_$AuthStateLoadedImpl;
String get token;
/// Create a copy of AuthState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
_$$AuthStateLoadedImplCopyWith<_$AuthStateLoadedImpl> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class _$$AuthStateErrorImplCopyWith<$Res> {
factory _$$AuthStateErrorImplCopyWith(_$AuthStateErrorImpl value,
$Res Function(_$AuthStateErrorImpl) then) =
__$$AuthStateErrorImplCopyWithImpl<$Res>;
@useResult
$Res call({String errorMessage});
}
/// @nodoc
class __$$AuthStateErrorImplCopyWithImpl<$Res>
extends _$AuthStateCopyWithImpl<$Res, _$AuthStateErrorImpl>
implements _$$AuthStateErrorImplCopyWith<$Res> {
__$$AuthStateErrorImplCopyWithImpl(
_$AuthStateErrorImpl _value, $Res Function(_$AuthStateErrorImpl) _then)
: super(_value, _then);
/// Create a copy of AuthState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? errorMessage = null,
}) {
return _then(_$AuthStateErrorImpl(
errorMessage: null == errorMessage
? _value.errorMessage
: errorMessage // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
/// @nodoc
class _$AuthStateErrorImpl implements AuthStateError {
const _$AuthStateErrorImpl({required this.errorMessage});
@override
final String errorMessage;
@override
String toString() {
return 'AuthState.error(errorMessage: $errorMessage)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$AuthStateErrorImpl &&
(identical(other.errorMessage, errorMessage) ||
other.errorMessage == errorMessage));
}
@override
int get hashCode => Object.hash(runtimeType, errorMessage);
/// Create a copy of AuthState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@override
@pragma('vm:prefer-inline')
_$$AuthStateErrorImplCopyWith<_$AuthStateErrorImpl> get copyWith =>
__$$AuthStateErrorImplCopyWithImpl<_$AuthStateErrorImpl>(
this, _$identity);
@override
@optionalTypeArgs
TResult when<TResult extends Object?>(
TResult Function() $default, {
required TResult Function() loading,
required TResult Function(String token) loaded,
required TResult Function(String errorMessage) error,
}) {
return error(errorMessage);
}
@override
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function()? $default, {
TResult? Function()? loading,
TResult? Function(String token)? loaded,
TResult? Function(String errorMessage)? error,
}) {
return error?.call(errorMessage);
}
@override
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function()? $default, {
TResult Function()? loading,
TResult Function(String token)? loaded,
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(_AuthState value) $default, {
required TResult Function(AuthStateLoading value) loading,
required TResult Function(AuthStateLoaded value) loaded,
required TResult Function(AuthStateError value) error,
}) {
return error(this);
}
@override
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>(
TResult? Function(_AuthState value)? $default, {
TResult? Function(AuthStateLoading value)? loading,
TResult? Function(AuthStateLoaded value)? loaded,
TResult? Function(AuthStateError value)? error,
}) {
return error?.call(this);
}
@override
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>(
TResult Function(_AuthState value)? $default, {
TResult Function(AuthStateLoading value)? loading,
TResult Function(AuthStateLoaded value)? loaded,
TResult Function(AuthStateError value)? error,
required TResult orElse(),
}) {
if (error != null) {
return error(this);
}
return orElse();
}
}
abstract class AuthStateError implements AuthState {
const factory AuthStateError({required final String errorMessage}) =
_$AuthStateErrorImpl;
String get errorMessage;
/// Create a copy of AuthState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
_$$AuthStateErrorImplCopyWith<_$AuthStateErrorImpl> get copyWith =>
throw _privateConstructorUsedError;
}

View File

@@ -0,0 +1,152 @@
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/utils/image_constant.dart';
import 'package:eatvio_app/core/widgets/custom_text_form_field.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:go_router/go_router.dart';
import 'package:url_launcher/url_launcher.dart';
class AuthScreen extends StatefulWidget {
const AuthScreen();
@override
State<AuthScreen> createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen> {
final emailController = TextEditingController();
final passwordController = TextEditingController();
bool checkboxState = false;
bool hidePassword = true;
final authCubit = sl<AuthCubit>();
@override
Widget build(BuildContext context) {
final s = S.of(context);
FlutterNativeSplash.remove();
return BlocProvider<AuthCubit>(
create: (BuildContext context) => authCubit,
child: Scaffold(
appBar: AppBar(
centerTitle: true,
title: SvgPicture.asset(
ImageConstant.imgLogoEatvio,
height: 48,
fit: BoxFit.contain,
),
),
body: SafeArea(
child: Padding(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(s.email),
const SizedBox(height: 4),
CustomTextFormField(
controller: emailController,
textInputAction: TextInputAction.next,
keyboardType: TextInputType.emailAddress,
textInputType: TextInputType.emailAddress,
hintText: 'Введите email',
),
const SizedBox(height: 16),
Text(s.password),
const SizedBox(height: 4),
CustomTextFormField(
obscureText: hidePassword,
controller: passwordController,
hintText: 'Введите пароль',
suffix: IconButton(
onPressed: () {
setState(() {
hidePassword = !hidePassword;
});
},
icon: Icon(
hidePassword ? Icons.visibility_outlined : Icons.visibility_off_outlined,
color: Colors.grey,
),
),
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Нет аккаунта? '),
GestureDetector(
onTap: () => GoRouter.of(context).goNamed('webViewRegistrationScreen'),
child: Text(
'Зарегистрироваться',
style: TextStyle(
color: appTheme.blueA400,
decorationColor: appTheme.blueA400,
decoration: TextDecoration.underline,
),
),
),
],
),
Spacer(),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Нажимая "Войти", Вы соглашаетесь с ',
style: TextStyle(
fontSize: 12,
),
),
GestureDetector(
onTap: () async {
await launchUrl(Uri.parse(baseUrl + '/oferta_bs.pdf'));
},
child: Text(
'Публичной офертой',
style: TextStyle(
fontSize: 12,
color: appTheme.blueA400,
decorationColor: appTheme.blueA400,
decoration: TextDecoration.underline,
),
),
),
],
),
const SizedBox(height: 16),
Container(
height: 48,
width: MediaQuery.of(context).size.width - 32,
child: FloatingActionButton.extended(
heroTag: 'authButton',
highlightElevation: 0,
elevation: 0,
focusElevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
backgroundColor: appTheme.blueA400,
onPressed: () => authCubit.getTokenByCredentials(
emailController.text,
passwordController.text,
),
label: Text(
'Войти',
style: theme.textTheme.titleSmall!.copyWith(color: Colors.white),
),
),
),
],
),
),
),
),
);
}
}

View File

@@ -0,0 +1,25 @@
import 'package:eatvio_app/features/auth/models/credentials_model.dart';
import 'package:eatvio_app/features/auth/models/token_model.dart';
import 'package:eatvio_app/features/auth/services/auth_service.dart';
class AuthRepository {
final AuthService authService;
AuthRepository({required this.authService});
Future<TokenModel> getTokenByCredentials(
String email,
String password,
) async {
try {
return await authService.getTokenByCredentials(
credentials: CredentialsModel(
email: email,
password: password,
),
);
} catch (e) {
rethrow;
}
}
}

View File

@@ -0,0 +1,16 @@
import 'package:dio/dio.dart';
import 'package:eatvio_app/features/auth/models/credentials_model.dart';
import 'package:eatvio_app/features/auth/models/token_model.dart';
import 'package:retrofit/retrofit.dart';
part 'auth_service.g.dart';
@RestApi()
abstract class AuthService {
factory AuthService(Dio dio, {String? baseUrl}) = _AuthService;
@POST('/api/login')
Future<TokenModel> getTokenByCredentials({
@Body() required CredentialsModel credentials,
});
}

View File

@@ -0,0 +1,75 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'auth_service.dart';
// **************************************************************************
// RetrofitGenerator
// **************************************************************************
// ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers,unused_element,unnecessary_string_interpolations
class _AuthService implements AuthService {
_AuthService(this._dio, {this.baseUrl, this.errorLogger});
final Dio _dio;
String? baseUrl;
final ParseErrorLogger? errorLogger;
@override
Future<TokenModel> getTokenByCredentials({
required CredentialsModel credentials,
}) async {
final _extra = <String, dynamic>{};
final queryParameters = <String, dynamic>{};
final _headers = <String, dynamic>{};
final _data = credentials;
final _options = _setStreamType<TokenModel>(
Options(method: 'POST', headers: _headers, extra: _extra)
.compose(
_dio.options,
'/api/login',
queryParameters: queryParameters,
data: _data,
)
.copyWith(baseUrl: _combineBaseUrls(_dio.options.baseUrl, baseUrl)),
);
final _result = await _dio.fetch<Map<String, dynamic>>(_options);
late TokenModel _value;
try {
_value = TokenModel.fromJson(_result.data!);
} on Object catch (e, s) {
errorLogger?.logError(e, s, _options);
rethrow;
}
return _value;
}
RequestOptions _setStreamType<T>(RequestOptions requestOptions) {
if (T != dynamic &&
!(requestOptions.responseType == ResponseType.bytes ||
requestOptions.responseType == ResponseType.stream)) {
if (T == String) {
requestOptions.responseType = ResponseType.plain;
} else {
requestOptions.responseType = ResponseType.json;
}
}
return requestOptions;
}
String _combineBaseUrls(String dioBaseUrl, String? baseUrl) {
if (baseUrl == null || baseUrl.trim().isEmpty) {
return dioBaseUrl;
}
final url = Uri.parse(baseUrl);
if (url.isAbsolute) {
return url.toString();
}
return Uri.parse(dioBaseUrl).resolveUri(url).toString();
}
}

View File

@@ -4,8 +4,7 @@ import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/new_
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_state.dart';
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_cubit.dart';
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/notifications_cubit/notifications_state.dart';
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_state.dart';
import 'package:eatvio_app/features/profile/models/profile_model.dart';
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_state.dart';
import 'package:eatvio_app/generated/l10n.dart';
@@ -15,14 +14,14 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:go_router/go_router.dart';
int currentBottomNavBarIndex = 0;
class BottomNavigationBarWidget extends StatefulWidget {
final ProfileModel profileModel;
final Widget child;
const BottomNavigationBarWidget({
super.key,
required this.child,
required this.profileModel,
});
@override
@@ -30,32 +29,42 @@ class BottomNavigationBarWidget extends StatefulWidget {
}
class _BottomNavigationBarWidgetState extends State<BottomNavigationBarWidget> {
int currentBottomNavBarIndex = 0;
late final List<String> pages;
@override
void initState() {
super.initState();
if (widget.profileModel.roles.contains('consultant')) {
pages = [
'/my-profile-screen',
'/feed-screen',
'/diary-screen',
'/consultations-screen',
'/chat-select-screen',
'/notifications-screen',
'/menu-screen',
];
} else {
pages = [
'/my-profile-screen',
'/feed-screen',
'/diary-screen',
'/chat-select-screen',
'/notifications-screen',
'/menu-screen',
];
}
}
void _onItemTapped(int index) async {
if (currentBottomNavBarIndex != index) {
setState(() {
currentBottomNavBarIndex = index;
});
}
switch (currentBottomNavBarIndex) {
case 0:
GoRouter.of(context).replace('/my-profile-screen');
break;
case 1:
GoRouter.of(context).replace('/feed-screen');
break;
case 2:
GoRouter.of(context).replace('/diary-screen');
break;
case 3:
GoRouter.of(context).replace('/chat-select-screen');
break;
case 4:
GoRouter.of(context).replace('/notifications-screen');
break;
case 5:
GoRouter.of(context).replace('/menu-screen');
break;
}
GoRouter.of(context).replace(pages[currentBottomNavBarIndex]);
}
@override
@@ -73,19 +82,9 @@ class _BottomNavigationBarWidgetState extends State<BottomNavigationBarWidget> {
items: [
BottomNavigationBarItem(
label: '',
icon: BlocBuilder<ProfileAvatarCubit, ProfileAvatarState>(
builder: (BuildContext context, ProfileAvatarState state) {
if (state is ProfileAvatarStateLoaded) {
return CircleAvatar(
backgroundImage: NetworkImage(state.profile.profilePhotoUrl),
radius: 16,
);
}
return CircleAvatar(
radius: 16,
backgroundColor: Colors.black12,
);
},
icon: CircleAvatar(
backgroundImage: NetworkImage(widget.profileModel.profilePhotoUrl),
radius: 16,
),
),
BottomNavigationBarItem(
@@ -136,6 +135,31 @@ class _BottomNavigationBarWidgetState extends State<BottomNavigationBarWidget> {
),
),
),
if (widget.profileModel.roles.contains('consultant'))
BottomNavigationBarItem(
label: 'Консультации',
icon: Padding(
padding: const EdgeInsets.only(bottom: 2),
child: SvgPicture.asset(
colorFilter: ColorFilter.mode(Colors.grey, BlendMode.srcIn),
'assets/icons/consultations.svg',
width: 20,
height: 20,
),
),
activeIcon: Padding(
padding: const EdgeInsets.only(bottom: 2),
child: SvgPicture.asset(
'assets/icons/consultations.svg',
width: 20,
height: 20,
colorFilter: ColorFilter.mode(
appTheme.blueA400,
BlendMode.srcIn,
),
),
),
),
BottomNavigationBarItem(
label: s.chat,
icon: BlocBuilder<ChatsCubit, ChatsState>(
@@ -160,7 +184,7 @@ class _BottomNavigationBarWidgetState extends State<BottomNavigationBarWidget> {
ImageConstant.icnChat,
width: 20,
height: 20,
colorFilter: currentBottomNavBarIndex == 3
colorFilter: pages[currentBottomNavBarIndex] == '/chat-select-screen'
? ColorFilter.mode(
appTheme.blueA400,
BlendMode.srcIn,
@@ -190,7 +214,7 @@ class _BottomNavigationBarWidgetState extends State<BottomNavigationBarWidget> {
padding: const EdgeInsets.only(bottom: 2),
child: SvgPicture.asset(
ImageConstant.icnBell,
colorFilter: currentBottomNavBarIndex == 4
colorFilter: pages[currentBottomNavBarIndex] == '/notifications-screen'
? ColorFilter.mode(
appTheme.blueA400,
BlendMode.srcIn,

View File

@@ -0,0 +1,82 @@
import 'dart:math';
class ConsultationsEntity {
final String name; // Имя и фамилия пользователя который проходит план
final String planName; // Название плана который проходит
final String clientSlug; // Слаг пользователя который проходит
final String photoUrl; // Ссылка на аватрку пользователя
final DateTime startPlanDate; // Дата начала прохождения плана
final DateTime endPlanDate; // Дата окончания прохождения плана
final int paymentAmount; // Сумма выплаты которую получит консультант
final int currentDayOfPlan; // Текущий день прохождения плана
final int totalDaysOfPlan; // Общее число дней в плане
final List<DayOfPlanEntity> days; // Дни плана
final bool haveUnreadMessages; // Есть ли непрочитанные сообщения в чате от пользователя
ConsultationsEntity({
required this.name,
required this.planName,
required this.clientSlug,
required this.photoUrl,
required this.startPlanDate,
required this.endPlanDate,
required this.paymentAmount,
required this.days,
required this.haveUnreadMessages,
required this.currentDayOfPlan,
required this.totalDaysOfPlan,
});
}
enum LegendOfPlanDay {
Empty, // Дневник не заполнялся и никаких движений в тот день не было.
NotCompleted, // Начат дневник питания, но не закончен.
EndBuyUserDontCheck, // Дневник закончен и прокомментирован консультантом но не просмотрен пользователем.
CompletedButConsultantCommentEmpty, // Дневник заполнен, но не прокомментирован консультантом.
FullCompleted, // Дневник заполнен, прокомментирован консультантом и после этого клиент просмотрел комментарии.
}
class DayOfPlanEntity {
final DateTime dateTime;
final List<LegendOfPlanDay> daysLegends;
DayOfPlanEntity({
required this.dateTime,
required this.daysLegends,
});
}
List<ConsultationsEntity> generateTestData() {
final random = Random();
final List<String> names = ["Иван Петров", "Анна Смирнова", "Дмитрий Соколов", "Елена Козлова", "Алексей Иванов"];
final List<String> plans = ["Похудение", "Набор массы", "Детокс", "Здоровое питание", "Вегетарианство"];
List<ConsultationsEntity> testConsultations = List.generate(20, (index) {
DateTime startDate = DateTime.now().subtract(Duration(days: random.nextInt(30)));
DateTime endDate = startDate.add(Duration(days: 30));
List<DayOfPlanEntity> days = List.generate(30, (i) {
DateTime dayDate = startDate.add(Duration(days: i));
List<LegendOfPlanDay> legends = List.generate(random.nextInt(3) + 1, (j) => LegendOfPlanDay.values[random.nextInt(LegendOfPlanDay.values.length)]);
return DayOfPlanEntity(dateTime: dayDate, daysLegends: legends);
});
return ConsultationsEntity(
name: names[random.nextInt(names.length)],
planName: plans[random.nextInt(plans.length)],
clientSlug: "client_${index + 1}",
startPlanDate: startDate,
endPlanDate: endDate,
paymentAmount: (random.nextInt(10) + 1) * 1000,
days: days,
haveUnreadMessages: random.nextBool(),
photoUrl: '',
currentDayOfPlan: Random().nextInt(6) + 1,
totalDaysOfPlan: Random().nextInt(7) + 14,
);
});
return testConsultations;
}
List<ConsultationsEntity> testData = generateTestData();

View File

@@ -0,0 +1,28 @@
import 'package:eatvio_app/features/consultations/entities/consultations_entity.dart';
import 'package:eatvio_app/features/consultations/presentation/widgets/consultation_card_widget.dart';
import 'package:flutter/material.dart';
class ConsultationsScreen extends StatelessWidget {
const ConsultationsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFFF0F2F5),
appBar: AppBar(
title: Text('Консультации'),
centerTitle: true,
),
body: ListView.separated(
padding: EdgeInsets.symmetric(vertical: 12),
itemBuilder: (context, index) => ConsultationCardWidget(
consultationsEntity: testData[index],
),
separatorBuilder: (context, index) => const SizedBox(
height: 12,
),
itemCount: testData.length,
),
);
}
}

View File

@@ -0,0 +1,268 @@
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/widgets/custom_divider.dart';
import 'package:eatvio_app/features/consultations/entities/consultations_entity.dart';
import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';
class ConsultationCardWidget extends StatelessWidget {
final List<String> titles = const [
'Дневник не заполнялся и никаких движений в тот день не было.',
'Показывает границы плана питания или публичной диеты в будущем.',
'Начат дневник питания, но не закончен.',
'Дневник закончен и прокомментирован консультантом но не просмотрен пользователем.',
'Дневник заполнен, но не прокомментирован консультантом.',
'Дневник заполнен, прокомментирован консультантом и после этого клиент просмотрел комментарии.',
];
final List<Color> legendColors = const [
Colors.white,
Color(0xFFCAC9C9),
Color(0xFFF0C497),
Color(0xFF2F80ED),
Color(0xFFFF9500),
Color(0xFF4CD964),
];
final ConsultationsEntity consultationsEntity;
const ConsultationCardWidget({
super.key,
required this.consultationsEntity,
});
@override
Widget build(BuildContext context) {
return Material(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
CircleAvatar(
radius: 30,
),
const SizedBox(width: 12),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
consultationsEntity.name,
style: TextStyle(
height: 1,
color: Color(0xFF323F4B),
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 4),
Text(
consultationsEntity.planName,
style: TextStyle(
height: 1,
color: Color(0xFF88949F),
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
],
),
],
),
const SizedBox(height: 12),
Text(
'Анкета пользователя',
style: TextStyle(
color: appTheme.blueA400,
decoration: TextDecoration.underline,
decorationColor: appTheme.blueA400,
fontWeight: FontWeight.w500,
height: 1,
),
),
const SizedBox(height: 12),
CustomDivider(),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'День ${consultationsEntity.currentDayOfPlan} из ${consultationsEntity.totalDaysOfPlan}',
style: TextStyle(
height: 1,
color: Color(0xFF323F4B),
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
GestureDetector(
onTap: () {
showModalBottomSheet(
context: context,
useSafeArea: true,
useRootNavigator: true,
showDragHandle: true,
builder: (context) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Легенда',
style: TextStyle(
height: 1,
fontSize: 20,
fontWeight: FontWeight.w700,
color: Color(0xFF323F4B),
),
),
const SizedBox(height: 16),
ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemBuilder: (context, index) => _legendTitle(titles[index], legendColors[index]),
separatorBuilder: (context, index) => SizedBox(height: 16),
itemCount: titles.length,
),
const SizedBox(height: 16),
],
),
),
);
},
child: Icon(
Icons.help_outline_rounded,
color: Color(0xFF323F4B),
size: 20,
),
),
],
),
const SizedBox(height: 16),
TableCalendar(
focusedDay: DateTime.now(),
firstDay: DateTime.utc(2020, 10, 16),
lastDay: DateTime.utc(2030, 3, 14),
locale: 'ru_RU',
startingDayOfWeek: StartingDayOfWeek.monday,
headerVisible: false,
calendarFormat: CalendarFormat.week,
calendarStyle: CalendarStyle(
weekendDecoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
defaultDecoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
selectedDecoration: BoxDecoration(
color: appTheme.blueA400,
shape: BoxShape.circle,
),
todayTextStyle: TextStyle(
color: Colors.black,
),
todayDecoration: BoxDecoration(
border: Border.all(
color: appTheme.blueA400,
width: 2,
),
color: Colors.white,
shape: BoxShape.circle,
),
),
),
const SizedBox(height: 16),
CustomDivider(),
const SizedBox(height: 12),
Text(
'${consultationsEntity.paymentAmount} ₽',
style: TextStyle(
color: Color(0xFF019A3E),
fontSize: 20,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 16),
Row(
children: [
InkWell(
borderRadius: BorderRadius.circular(20),
onTap: () {},
child: Ink(
width: MediaQuery.of(context).size.width - 32 - 52 - 8,
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: appTheme.blueA400,
),
child: Center(
child: Text(
'Комментировать отчёт',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
),
),
),
const SizedBox(width: 8),
InkWell(
borderRadius: BorderRadius.circular(20),
onTap: () {},
child: Ink(
height: 52,
width: 52,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Color(0xFFF6F6F6),
),
child: Center(
child: Icon(
Icons.chat_outlined,
size: 24,
),
),
),
),
],
),
],
),
),
);
}
_legendTitle(String text, Color color) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
height: 20,
width: 20,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: color,
),
),
const SizedBox(width: 12),
Flexible(
child: Text(
text,
style: TextStyle(
height: 1,
fontSize: 16,
fontWeight: FontWeight.w500,
color: Color(0xFF323F4B),
),
),
),
],
);
}
}

View File

@@ -21,7 +21,9 @@ class FeedConsultantModel with _$FeedConsultantModel {
const factory FeedConsultantModel({
required String slug,
required String name,
@JsonKey(name: 'rating_place') required int ratingPlace,
@JsonKey(name: 'additional_info') required String description,
@JsonKey(name: 'rating_place') int? ratingPlace,
@JsonKey(name: 'total_scores') required int totalScores,
@JsonKey(name: 'profile_photo_url') required String photo,
required List<BadgeModel> badges,
}) = _FeedConsultantModel;

View File

@@ -258,8 +258,12 @@ FeedConsultantModel _$FeedConsultantModelFromJson(Map<String, dynamic> json) {
mixin _$FeedConsultantModel {
String get slug => throw _privateConstructorUsedError;
String get name => throw _privateConstructorUsedError;
@JsonKey(name: 'additional_info')
String get description => throw _privateConstructorUsedError;
@JsonKey(name: 'rating_place')
int get ratingPlace => throw _privateConstructorUsedError;
int? get ratingPlace => throw _privateConstructorUsedError;
@JsonKey(name: 'total_scores')
int get totalScores => throw _privateConstructorUsedError;
@JsonKey(name: 'profile_photo_url')
String get photo => throw _privateConstructorUsedError;
List<BadgeModel> get badges => throw _privateConstructorUsedError;
@@ -283,7 +287,9 @@ abstract class $FeedConsultantModelCopyWith<$Res> {
$Res call(
{String slug,
String name,
@JsonKey(name: 'rating_place') int ratingPlace,
@JsonKey(name: 'additional_info') String description,
@JsonKey(name: 'rating_place') int? ratingPlace,
@JsonKey(name: 'total_scores') int totalScores,
@JsonKey(name: 'profile_photo_url') String photo,
List<BadgeModel> badges});
}
@@ -305,7 +311,9 @@ class _$FeedConsultantModelCopyWithImpl<$Res, $Val extends FeedConsultantModel>
$Res call({
Object? slug = null,
Object? name = null,
Object? ratingPlace = null,
Object? description = null,
Object? ratingPlace = freezed,
Object? totalScores = null,
Object? photo = null,
Object? badges = null,
}) {
@@ -318,9 +326,17 @@ class _$FeedConsultantModelCopyWithImpl<$Res, $Val extends FeedConsultantModel>
? _value.name
: name // ignore: cast_nullable_to_non_nullable
as String,
ratingPlace: null == ratingPlace
description: null == description
? _value.description
: description // ignore: cast_nullable_to_non_nullable
as String,
ratingPlace: freezed == ratingPlace
? _value.ratingPlace
: ratingPlace // ignore: cast_nullable_to_non_nullable
as int?,
totalScores: null == totalScores
? _value.totalScores
: totalScores // ignore: cast_nullable_to_non_nullable
as int,
photo: null == photo
? _value.photo
@@ -345,7 +361,9 @@ abstract class _$$FeedConsultantModelImplCopyWith<$Res>
$Res call(
{String slug,
String name,
@JsonKey(name: 'rating_place') int ratingPlace,
@JsonKey(name: 'additional_info') String description,
@JsonKey(name: 'rating_place') int? ratingPlace,
@JsonKey(name: 'total_scores') int totalScores,
@JsonKey(name: 'profile_photo_url') String photo,
List<BadgeModel> badges});
}
@@ -365,7 +383,9 @@ class __$$FeedConsultantModelImplCopyWithImpl<$Res>
$Res call({
Object? slug = null,
Object? name = null,
Object? ratingPlace = null,
Object? description = null,
Object? ratingPlace = freezed,
Object? totalScores = null,
Object? photo = null,
Object? badges = null,
}) {
@@ -378,9 +398,17 @@ class __$$FeedConsultantModelImplCopyWithImpl<$Res>
? _value.name
: name // ignore: cast_nullable_to_non_nullable
as String,
ratingPlace: null == ratingPlace
description: null == description
? _value.description
: description // ignore: cast_nullable_to_non_nullable
as String,
ratingPlace: freezed == ratingPlace
? _value.ratingPlace
: ratingPlace // ignore: cast_nullable_to_non_nullable
as int?,
totalScores: null == totalScores
? _value.totalScores
: totalScores // ignore: cast_nullable_to_non_nullable
as int,
photo: null == photo
? _value.photo
@@ -400,7 +428,9 @@ class _$FeedConsultantModelImpl implements _FeedConsultantModel {
const _$FeedConsultantModelImpl(
{required this.slug,
required this.name,
@JsonKey(name: 'rating_place') required this.ratingPlace,
@JsonKey(name: 'additional_info') required this.description,
@JsonKey(name: 'rating_place') this.ratingPlace,
@JsonKey(name: 'total_scores') required this.totalScores,
@JsonKey(name: 'profile_photo_url') required this.photo,
required final List<BadgeModel> badges})
: _badges = badges;
@@ -413,8 +443,14 @@ class _$FeedConsultantModelImpl implements _FeedConsultantModel {
@override
final String name;
@override
@JsonKey(name: 'additional_info')
final String description;
@override
@JsonKey(name: 'rating_place')
final int ratingPlace;
final int? ratingPlace;
@override
@JsonKey(name: 'total_scores')
final int totalScores;
@override
@JsonKey(name: 'profile_photo_url')
final String photo;
@@ -428,7 +464,7 @@ class _$FeedConsultantModelImpl implements _FeedConsultantModel {
@override
String toString() {
return 'FeedConsultantModel(slug: $slug, name: $name, ratingPlace: $ratingPlace, photo: $photo, badges: $badges)';
return 'FeedConsultantModel(slug: $slug, name: $name, description: $description, ratingPlace: $ratingPlace, totalScores: $totalScores, photo: $photo, badges: $badges)';
}
@override
@@ -438,15 +474,26 @@ class _$FeedConsultantModelImpl implements _FeedConsultantModel {
other is _$FeedConsultantModelImpl &&
(identical(other.slug, slug) || other.slug == slug) &&
(identical(other.name, name) || other.name == name) &&
(identical(other.description, description) ||
other.description == description) &&
(identical(other.ratingPlace, ratingPlace) ||
other.ratingPlace == ratingPlace) &&
(identical(other.totalScores, totalScores) ||
other.totalScores == totalScores) &&
(identical(other.photo, photo) || other.photo == photo) &&
const DeepCollectionEquality().equals(other._badges, _badges));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType, slug, name, ratingPlace, photo,
int get hashCode => Object.hash(
runtimeType,
slug,
name,
description,
ratingPlace,
totalScores,
photo,
const DeepCollectionEquality().hash(_badges));
/// Create a copy of FeedConsultantModel
@@ -470,7 +517,9 @@ abstract class _FeedConsultantModel implements FeedConsultantModel {
const factory _FeedConsultantModel(
{required final String slug,
required final String name,
@JsonKey(name: 'rating_place') required final int ratingPlace,
@JsonKey(name: 'additional_info') required final String description,
@JsonKey(name: 'rating_place') final int? ratingPlace,
@JsonKey(name: 'total_scores') required final int totalScores,
@JsonKey(name: 'profile_photo_url') required final String photo,
required final List<BadgeModel> badges}) = _$FeedConsultantModelImpl;
@@ -482,8 +531,14 @@ abstract class _FeedConsultantModel implements FeedConsultantModel {
@override
String get name;
@override
@JsonKey(name: 'additional_info')
String get description;
@override
@JsonKey(name: 'rating_place')
int get ratingPlace;
int? get ratingPlace;
@override
@JsonKey(name: 'total_scores')
int get totalScores;
@override
@JsonKey(name: 'profile_photo_url')
String get photo;

View File

@@ -30,7 +30,9 @@ _$FeedConsultantModelImpl _$$FeedConsultantModelImplFromJson(
_$FeedConsultantModelImpl(
slug: json['slug'] as String,
name: json['name'] as String,
ratingPlace: (json['rating_place'] as num).toInt(),
description: json['additional_info'] as String,
ratingPlace: (json['rating_place'] as num?)?.toInt(),
totalScores: (json['total_scores'] as num).toInt(),
photo: json['profile_photo_url'] as String,
badges: (json['badges'] as List<dynamic>)
.map((e) => BadgeModel.fromJson(e as Map<String, dynamic>))
@@ -42,7 +44,9 @@ Map<String, dynamic> _$$FeedConsultantModelImplToJson(
<String, dynamic>{
'slug': instance.slug,
'name': instance.name,
'additional_info': instance.description,
'rating_place': instance.ratingPlace,
'total_scores': instance.totalScores,
'profile_photo_url': instance.photo,
'badges': instance.badges,
};

View File

@@ -81,7 +81,14 @@ class ImtChartWidget extends StatelessWidget {
series: _getSplineSeries(),
tooltipBehavior: TooltipBehavior(enable: true),
),
if (weightPoints.isEmpty) Text('Индекс Массы Тела рассчитывается при указанных весе и росте'),
if (weightPoints.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Text(
'Индекс Массы Тела рассчитывается при указанных весе и росте',
textAlign: TextAlign.center,
),
),
],
),
],

View File

@@ -0,0 +1,45 @@
import 'package:eatvio_app/core/const.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:webview_flutter/webview_flutter.dart';
class WebViewRegistrationScreen extends StatefulWidget {
const WebViewRegistrationScreen();
@override
State<WebViewRegistrationScreen> createState() => _WebViewRegistrationScreenState();
}
class _WebViewRegistrationScreenState extends State<WebViewRegistrationScreen> {
late final WebViewController _controller;
@override
void initState() {
super.initState();
_controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(
onNavigationRequest: (NavigationRequest request) {
if (request.url.contains('profile')) {
GoRouter.of(context).go('authScreen');
}
return NavigationDecision.navigate;
},
),
)
..loadRequest(Uri.parse(baseUrl + '/registration/step1'));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
toolbarHeight: 0,
),
body: SafeArea(
child: WebViewWidget(controller: _controller),
),
);
}
}