Создание коллекций

This commit is contained in:
2025-03-25 20:53:53 +03:00
parent cb6ce05059
commit e6517402d3
375 changed files with 1775 additions and 1519 deletions

View File

@@ -8,9 +8,7 @@ import 'package:flutter_displaymode/flutter_displaymode.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fps_widget/fps_widget.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:remever/common/events/common_events.dart';
import 'package:remever/common/events/events.dart';
import 'package:remever/common/functions.dart';
import 'package:remever/common/getters.dart';
@@ -19,8 +17,6 @@ import 'package:remever/common/storage.dart';
import 'package:remever/components/notifiers/app_settings.dart';
import 'package:remever/components/listeners/theme_listener.dart';
import 'package:remever/i18n/strings.g.dart';
import 'package:remever/inject.dart';
import 'package:remever/router.dart';
import 'package:remever/theme/custom_theme.dart';
final Completer<GlobalKey<NavigatorState>> navKeyCompleter =
@@ -148,43 +144,39 @@ class _MyAppState extends State<MyApp>
localizationsDelegates: GlobalMaterialLocalizations.delegates,
routerConfig: globalRouter.config(),
builder: (BuildContext context, Widget? child) {
return OKToast(
position: ToastPosition.bottom,
backgroundColor: Colors.black.withOpacity(0.7),
child: MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.noScaling),
child: ChangeNotifierProvider<AppSettingsNotifier>(
create: (_) => settingsNotifier,
builder: (BuildContext context, Widget? nchild) {
if (nchild != null) return nchild;
return MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.noScaling),
child: ChangeNotifierProvider<AppSettingsNotifier>(
create: (_) => settingsNotifier,
builder: (BuildContext context, Widget? nchild) {
if (nchild != null) return nchild;
return Consumer<AppSettingsNotifier>(
// TIP: должно убрать мерцание
key: const Key('consumer AppSettingsNotifier'),
child: child,
builder: (
BuildContext context,
AppSettingsNotifier value,
Widget? nchild,
) {
final Widget result = nchild ?? const SizedBox();
return Consumer<AppSettingsNotifier>(
// TIP: должно убрать мерцание
key: const Key('consumer AppSettingsNotifier'),
child: child,
builder: (
BuildContext context,
AppSettingsNotifier value,
Widget? nchild,
) {
final Widget result = nchild ?? const SizedBox();
if (value.showFps) {
return Material(
child: FPSWidget(
alignment: Alignment.centerLeft,
child: result,
),
);
}
if (value.showFps) {
return Material(
child: FPSWidget(
alignment: Alignment.centerLeft,
child: result,
),
);
}
return result;
},
);
},
),
return result;
},
);
},
),
);
},

View File

@@ -1,5 +1,6 @@
// Flutter imports:
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
// Package imports:
import 'package:get_it/get_it.dart';
@@ -16,6 +17,33 @@ AppRouter get globalRouter {
return GetIt.I.get<AppRouter>();
}
///
/// Показ тоста
///
void showErrorToast(String text) {
Fluttertoast.showToast(
msg: text,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.TOP,
timeInSecForIosWeb: 1,
backgroundColor: AppColors.danger,
textColor: AppColors.white,
fontSize: 16,
);
}
void showSuccessToast(String text) {
Fluttertoast.showToast(
msg: text,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.TOP,
timeInSecForIosWeb: 1,
backgroundColor: AppColors.additional_blue,
textColor: AppColors.white,
fontSize: 16,
);
}
///
/// Глобальный показ ошибки
///

View File

@@ -1,37 +0,0 @@
// Flutter imports:
import 'package:flutter/widgets.dart';
// Package imports:
import 'package:oktoast/oktoast.dart' show ToastPosition, showToastWidget;
import 'package:remever/common/resources.dart';
import 'package:remever/common/widgets/info_toast.dart';
// Project imports:
///
/// Класс для отображения тостов
///
final class Toast {
///
/// Показать информационный тост
///
static void show(Widget child, {Duration? duration}) {
showToastWidget(
InfoToast(child: child),
duration: duration,
handleTouch: true,
);
}
///
/// Показать тост с иконкой для закрытия
///
static void showDismissible(String message, {Duration? duration}) {
showToastWidget(
InfoToast.dismissible(message: message, bgColor: AppColors.white),
position: ToastPosition.top.copyWith(offset: 50),
duration: duration,
handleTouch: true,
);
}
}

View File

@@ -1,162 +0,0 @@
// Flutter imports:
import 'package:flutter/material.dart';
// Package imports:
import 'package:oktoast/oktoast.dart' show dismissAllToast;
import 'package:remever/common/resources.dart';
import 'package:remever/common/widgets/typography.dart';
import 'package:remever/common/widgets/wspace.dart';
import 'package:remever/components/extensions/context.dart';
// Project imports:
import 'package:remever/gen/assets.gen.dart';
enum ToastType {
///
/// Стандартный тост
///
DEFAULT,
///
/// Закрываемый вручную тост
///
DISMISSIBLE,
}
class InfoToast extends StatelessWidget {
///
/// Виджет отображающийся при использовании [Toast.show]
///
const InfoToast({required this.child, super.key})
: toastType = ToastType.DEFAULT,
message = '',
type = null,
textColor = null,
bgColor = null;
const InfoToast.dismissible({
required this.message,
this.type,
this.textColor,
this.bgColor,
super.key,
}) : toastType = ToastType.DISMISSIBLE,
child = const SizedBox();
/// Сообщение в [ToastType.DISMISSIBLE]
final String message;
/// Сообщение в [ToastType.DEFAULT]
final Widget child;
/// Тип тоста
final ToastType toastType;
/// Тип типографии
final TypographyType? type;
/// Цвет текста
final Color? textColor;
/// Фоновый цвет
final Color? bgColor;
@override
Widget build(BuildContext context) {
return switch (toastType) {
ToastType.DEFAULT => _Toast(child: child),
ToastType.DISMISSIBLE => _DismissibleToast(
message: message,
type: type,
textColor: textColor,
bgColor: bgColor,
),
};
}
}
class _DismissibleToast extends StatelessWidget {
const _DismissibleToast({
required this.message,
this.type,
this.textColor,
this.bgColor,
});
final String message;
final TypographyType? type;
final Color? textColor;
final Color? bgColor;
@override
Widget build(BuildContext context) {
return Material(
child: SizedBox(
width: MediaQuery.sizeOf(context).width * 0.9,
// height: 60.h,
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: 60.h),
child: DecoratedBox(
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(8)).r,
color: bgColor ?? AppColors.white,
border: Border.all(color: AppColors.gray, width: 0.5.w),
),
child: Padding(
padding: const EdgeInsets.all(12).r,
child: Row(
children: <Widget>[
Assets.icons.typeDanger.image(height: 24.h, width: 24.w),
const WSpace(8),
Flexible(
fit: FlexFit.tight,
child: AppTypography(
message,
type: type,
color: textColor ?? AppColors.white,
textAlign: TextAlign.start,
maxLines: 3,
),
),
InkWell(
onTap: dismissAllToast,
child: SizedBox.square(
dimension: 24.r,
child: const DecoratedBox(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: AppColors.gray_bg,
),
child: Icon(Icons.close, color: AppColors.disabled),
),
),
),
],
),
),
),
),
),
);
}
}
class _Toast extends StatelessWidget {
const _Toast({required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return Material(
child: SizedBox(
height: 40,
width: MediaQuery.sizeOf(context).width * 0.6,
child: ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(15)).r,
child: child,
),
),
);
}
}

View File

@@ -2,6 +2,7 @@
import 'package:drift/drift.dart';
import 'package:remever/database/database.dart';
import 'package:remever/database/tables.dart';
import 'package:remever/models/collection_dto.dart';
part 'collections_dao.g.dart';
@@ -13,10 +14,20 @@ class CollectionsDao extends DatabaseAccessor<AppDatabase>
///
CollectionsDao(super.attachedDatabase);
///
/// Получение коллекций из базы данных
///
Stream<List<Collection>> getCollections() {
return db.managers.collections.watch();
}
/// Создание коллекции
Future<void> createCollection(CollectionDto dto) async {
await db.managers.collections.create(
(o) => o(
title: dto.title,
desc: dto.desc,
isPublic: Value<bool>(dto.isPublic),
image: Value<String?>(dto.avatar),
),
);
}
}

View File

@@ -63,13 +63,9 @@ mixin _Deletable on Table {
@DataClassName('Collection')
class Collections extends Table with _UuidPrimaryKey, _Timestampable {
TextColumn get title => text()();
TextColumn get desc => text()();
TextColumn get image => text().nullable()();
TextColumn get payload => text().nullable()();
IntColumn get likesCount => integer().withDefault(Constant(0))();
BoolColumn get isLiked => boolean().withDefault(Constant(false))();
BoolColumn get isPublic => boolean().withDefault(Constant(false))();

View File

@@ -6,7 +6,7 @@
/// Locales: 2
/// Strings: 20 (10 per locale)
///
/// Built on 2025-03-03 at 20:52 UTC
/// Built on 2025-03-25 at 14:49 UTC
// coverage:ignore-file
// ignore_for_file: type=lint, unused_import

View File

@@ -13,8 +13,10 @@ import 'package:get_it/get_it.dart' as _i174;
import 'package:injectable/injectable.dart' as _i526;
import 'database/database.dart' as _i565;
import 'services/auth_interface.dart' as _i78;
import 'services/auth_service.dart' as _i706;
import 'services/auth/auth_interface.dart' as _i580;
import 'services/auth/auth_service.dart' as _i975;
import 'services/collection/collections_interface.dart' as _i764;
import 'services/collection/collections_service.dart' as _i1001;
import 'services/core/enc_keys_service.dart' as _i439;
import 'services/core/lang_service.dart' as _i68;
import 'services/core/theme_service.dart' as _i84;
@@ -31,7 +33,8 @@ extension GetItInjectableX on _i174.GetIt {
gh.factory<_i439.EncKeysService>(() => _i439.EncKeysService());
gh.factory<_i84.ThemeService>(() => _i84.ThemeService());
gh.singleton<_i565.AppDatabase>(() => _i565.AppDatabase());
gh.singleton<_i78.AuthInterface>(() => _i706.AuthService());
gh.singleton<_i764.CollectionsInterface>(() => _i1001.CollectionsService());
gh.singleton<_i580.AuthInterface>(() => _i975.AuthService());
await gh.singletonAsync<_i564.WarmupService>(() {
final i = _i564.WarmupService(
gh<_i84.ThemeService>(),

View File

@@ -0,0 +1,27 @@
// To parse this JSON data, do
//
// final collectionDto = collectionDtoFromJson(jsonString);
import 'package:freezed_annotation/freezed_annotation.dart';
import 'dart:convert';
part 'collection_dto.freezed.dart';
part 'collection_dto.g.dart';
CollectionDto collectionDtoFromJson(String str) =>
CollectionDto.fromJson(json.decode(str));
String collectionDtoToJson(CollectionDto data) => json.encode(data.toJson());
@freezed
class CollectionDto with _$CollectionDto {
const factory CollectionDto({
required String desc,
required String title,
required bool isPublic,
String? avatar,
}) = _CollectionDto;
factory CollectionDto.fromJson(Map<String, dynamic> json) =>
_$CollectionDtoFromJson(json);
}

View File

@@ -0,0 +1,238 @@
// 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 'collection_dto.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',
);
CollectionDto _$CollectionDtoFromJson(Map<String, dynamic> json) {
return _CollectionDto.fromJson(json);
}
/// @nodoc
mixin _$CollectionDto {
String get desc => throw _privateConstructorUsedError;
String get title => throw _privateConstructorUsedError;
bool get isPublic => throw _privateConstructorUsedError;
String? get avatar => throw _privateConstructorUsedError;
/// Serializes this CollectionDto to a JSON map.
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
/// Create a copy of CollectionDto
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
$CollectionDtoCopyWith<CollectionDto> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $CollectionDtoCopyWith<$Res> {
factory $CollectionDtoCopyWith(
CollectionDto value,
$Res Function(CollectionDto) then,
) = _$CollectionDtoCopyWithImpl<$Res, CollectionDto>;
@useResult
$Res call({String desc, String title, bool isPublic, String? avatar});
}
/// @nodoc
class _$CollectionDtoCopyWithImpl<$Res, $Val extends CollectionDto>
implements $CollectionDtoCopyWith<$Res> {
_$CollectionDtoCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
/// Create a copy of CollectionDto
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? desc = null,
Object? title = null,
Object? isPublic = null,
Object? avatar = freezed,
}) {
return _then(
_value.copyWith(
desc:
null == desc
? _value.desc
: desc // ignore: cast_nullable_to_non_nullable
as String,
title:
null == title
? _value.title
: title // ignore: cast_nullable_to_non_nullable
as String,
isPublic:
null == isPublic
? _value.isPublic
: isPublic // ignore: cast_nullable_to_non_nullable
as bool,
avatar:
freezed == avatar
? _value.avatar
: avatar // ignore: cast_nullable_to_non_nullable
as String?,
)
as $Val,
);
}
}
/// @nodoc
abstract class _$$CollectionDtoImplCopyWith<$Res>
implements $CollectionDtoCopyWith<$Res> {
factory _$$CollectionDtoImplCopyWith(
_$CollectionDtoImpl value,
$Res Function(_$CollectionDtoImpl) then,
) = __$$CollectionDtoImplCopyWithImpl<$Res>;
@override
@useResult
$Res call({String desc, String title, bool isPublic, String? avatar});
}
/// @nodoc
class __$$CollectionDtoImplCopyWithImpl<$Res>
extends _$CollectionDtoCopyWithImpl<$Res, _$CollectionDtoImpl>
implements _$$CollectionDtoImplCopyWith<$Res> {
__$$CollectionDtoImplCopyWithImpl(
_$CollectionDtoImpl _value,
$Res Function(_$CollectionDtoImpl) _then,
) : super(_value, _then);
/// Create a copy of CollectionDto
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? desc = null,
Object? title = null,
Object? isPublic = null,
Object? avatar = freezed,
}) {
return _then(
_$CollectionDtoImpl(
desc:
null == desc
? _value.desc
: desc // ignore: cast_nullable_to_non_nullable
as String,
title:
null == title
? _value.title
: title // ignore: cast_nullable_to_non_nullable
as String,
isPublic:
null == isPublic
? _value.isPublic
: isPublic // ignore: cast_nullable_to_non_nullable
as bool,
avatar:
freezed == avatar
? _value.avatar
: avatar // ignore: cast_nullable_to_non_nullable
as String?,
),
);
}
}
/// @nodoc
@JsonSerializable()
class _$CollectionDtoImpl implements _CollectionDto {
const _$CollectionDtoImpl({
required this.desc,
required this.title,
required this.isPublic,
this.avatar,
});
factory _$CollectionDtoImpl.fromJson(Map<String, dynamic> json) =>
_$$CollectionDtoImplFromJson(json);
@override
final String desc;
@override
final String title;
@override
final bool isPublic;
@override
final String? avatar;
@override
String toString() {
return 'CollectionDto(desc: $desc, title: $title, isPublic: $isPublic, avatar: $avatar)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$CollectionDtoImpl &&
(identical(other.desc, desc) || other.desc == desc) &&
(identical(other.title, title) || other.title == title) &&
(identical(other.isPublic, isPublic) ||
other.isPublic == isPublic) &&
(identical(other.avatar, avatar) || other.avatar == avatar));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType, desc, title, isPublic, avatar);
/// Create a copy of CollectionDto
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@override
@pragma('vm:prefer-inline')
_$$CollectionDtoImplCopyWith<_$CollectionDtoImpl> get copyWith =>
__$$CollectionDtoImplCopyWithImpl<_$CollectionDtoImpl>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$$CollectionDtoImplToJson(this);
}
}
abstract class _CollectionDto implements CollectionDto {
const factory _CollectionDto({
required final String desc,
required final String title,
required final bool isPublic,
final String? avatar,
}) = _$CollectionDtoImpl;
factory _CollectionDto.fromJson(Map<String, dynamic> json) =
_$CollectionDtoImpl.fromJson;
@override
String get desc;
@override
String get title;
@override
bool get isPublic;
@override
String? get avatar;
/// Create a copy of CollectionDto
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
_$$CollectionDtoImplCopyWith<_$CollectionDtoImpl> get copyWith =>
throw _privateConstructorUsedError;
}

View File

@@ -0,0 +1,23 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'collection_dto.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_$CollectionDtoImpl _$$CollectionDtoImplFromJson(Map<String, dynamic> json) =>
_$CollectionDtoImpl(
desc: json['desc'] as String,
title: json['title'] as String,
isPublic: json['isPublic'] as bool,
avatar: json['avatar'] as String?,
);
Map<String, dynamic> _$$CollectionDtoImplToJson(_$CollectionDtoImpl instance) =>
<String, dynamic>{
'desc': instance.desc,
'title': instance.title,
'isPublic': instance.isPublic,
'avatar': instance.avatar,
};

View File

@@ -10,8 +10,7 @@
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:auto_route/auto_route.dart' as _i12;
import 'package:flutter/cupertino.dart' as _i14;
import 'package:flutter/material.dart' as _i13;
import 'package:flutter/cupertino.dart' as _i13;
import 'package:remever/screens/auth/auth_screen.dart' as _i1;
import 'package:remever/screens/collections/collection_detail_screen.dart'
as _i2;
@@ -60,38 +59,20 @@ class CollectionDetailRoute extends _i12.PageRouteInfo<void> {
/// generated route for
/// [_i3.CollectionScreen]
class CollectionRoute extends _i12.PageRouteInfo<CollectionRouteArgs> {
CollectionRoute({_i13.Key? key, List<_i12.PageRouteInfo>? children})
: super(
CollectionRoute.name,
args: CollectionRouteArgs(key: key),
initialChildren: children,
);
class CollectionRoute extends _i12.PageRouteInfo<void> {
const CollectionRoute({List<_i12.PageRouteInfo>? children})
: super(CollectionRoute.name, initialChildren: children);
static const String name = 'CollectionRoute';
static _i12.PageInfo page = _i12.PageInfo(
name,
builder: (data) {
final args = data.argsAs<CollectionRouteArgs>(
orElse: () => const CollectionRouteArgs(),
);
return _i3.CollectionScreen(key: args.key);
return const _i3.CollectionScreen();
},
);
}
class CollectionRouteArgs {
const CollectionRouteArgs({this.key});
final _i13.Key? key;
@override
String toString() {
return 'CollectionRouteArgs{key: $key}';
}
}
/// generated route for
/// [_i4.CreateScreen]
class CreateRoute extends _i12.PageRouteInfo<void> {
@@ -113,10 +94,12 @@ class CreateRoute extends _i12.PageRouteInfo<void> {
class CrudCollectionFullscreenField
extends _i12.PageRouteInfo<CrudCollectionFullscreenFieldArgs> {
CrudCollectionFullscreenField({
_i14.Key? key,
_i13.Key? key,
String title = '',
String? hint,
String? content,
double height = 92,
required void Function(String?) onEditingComplete,
List<_i12.PageRouteInfo>? children,
}) : super(
CrudCollectionFullscreenField.name,
@@ -124,7 +107,9 @@ class CrudCollectionFullscreenField
key: key,
title: title,
hint: hint,
content: content,
height: height,
onEditingComplete: onEditingComplete,
),
initialChildren: children,
);
@@ -134,14 +119,14 @@ class CrudCollectionFullscreenField
static _i12.PageInfo page = _i12.PageInfo(
name,
builder: (data) {
final args = data.argsAs<CrudCollectionFullscreenFieldArgs>(
orElse: () => const CrudCollectionFullscreenFieldArgs(),
);
final args = data.argsAs<CrudCollectionFullscreenFieldArgs>();
return _i5.CrudCollectionFullscreenField(
key: args.key,
title: args.title,
hint: args.hint,
content: args.content,
height: args.height,
onEditingComplete: args.onEditingComplete,
);
},
);
@@ -152,20 +137,26 @@ class CrudCollectionFullscreenFieldArgs {
this.key,
this.title = '',
this.hint,
this.content,
this.height = 92,
required this.onEditingComplete,
});
final _i14.Key? key;
final _i13.Key? key;
final String title;
final String? hint;
final String? content;
final double height;
final void Function(String?) onEditingComplete;
@override
String toString() {
return 'CrudCollectionFullscreenFieldArgs{key: $key, title: $title, hint: $hint, height: $height}';
return 'CrudCollectionFullscreenFieldArgs{key: $key, title: $title, hint: $hint, content: $content, height: $height, onEditingComplete: $onEditingComplete}';
}
}
@@ -173,7 +164,7 @@ class CrudCollectionFullscreenFieldArgs {
/// [_i6.CrudCollectionScreen]
class CrudCollectionRoute extends _i12.PageRouteInfo<CrudCollectionRouteArgs> {
CrudCollectionRoute({
_i14.Key? key,
_i13.Key? key,
_i6.CrudType crudType = _i6.CrudType.CREATE,
List<_i12.PageRouteInfo>? children,
}) : super(
@@ -201,7 +192,7 @@ class CrudCollectionRouteArgs {
this.crudType = _i6.CrudType.CREATE,
});
final _i14.Key? key;
final _i13.Key? key;
final _i6.CrudType crudType;

View File

@@ -3,7 +3,7 @@ import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:remever/common/functions.dart';
import 'package:remever/inject.dart';
import 'package:remever/router.gr.dart';
import 'package:remever/services/auth_interface.dart';
import 'package:remever/services/auth/auth_interface.dart';
part 'auth_state.dart';
part 'auth_cubit.freezed.dart';

View File

@@ -1,75 +1,111 @@
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get_it_mixin/get_it_mixin.dart';
import 'package:flutter/rendering.dart';
import 'package:remever/common/resources.dart';
import 'package:remever/common/widgets/typography.dart';
import 'package:remever/components/extensions/context.dart';
import 'package:remever/components/notifiers/home_screen_data.dart';
import 'package:remever/database/database.dart';
import 'package:remever/database/tables.dart';
import 'package:remever/inject.dart';
import 'package:remever/router.gr.dart';
import 'package:remever/screens/collections/cubit/collection_cubit.dart';
import 'package:remever/screens/collections/widgets/collection_card.dart';
import 'package:remever/screens/collections/widgets/collections_app_bar.dart';
import 'package:remever/screens/collections/widgets/collections_filters.dart';
import 'package:remever/services/collection/collections_interface.dart';
@RoutePage()
class CollectionScreen extends StatelessWidget with GetItMixin {
CollectionScreen({super.key});
class CollectionScreen extends StatefulWidget {
const CollectionScreen({super.key});
/// Флаг что надо показывать Fab
bool get _showFab {
return watchOnly<CollectionData, bool>((CollectionData d) => d.showFAB);
@override
State<CollectionScreen> createState() => _CollectionScreenState();
}
class _CollectionScreenState extends State<CollectionScreen> {
/// Контроллер скролла для коллекции
final ScrollController _scrollController = ScrollController();
/// Показ FAB'а
bool _showFab = true;
@override
void initState() {
super.initState();
_initScrollListener();
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
/// Инициализация слушателя скролла
void _initScrollListener() {
_scrollController.addListener(() {
setState(() {
_showFab =
_scrollController.position.userScrollDirection ==
ScrollDirection.reverse
? false
: true;
});
});
}
@override
Widget build(BuildContext context) {
return BlocProvider<CollectionCubit>(
create: (context) => CollectionCubit(),
child: Scaffold(
backgroundColor: AppColors.bg,
appBar: const CollectionsAppBar(),
body: _buildMain(context),
floatingActionButton: Builder(
builder: (BuildContext context) {
return AnimatedOpacity(
opacity: _showFab ? 1.0 : 0.0,
duration: const Duration(milliseconds: 200),
child: FloatingActionButton(
backgroundColor: AppColors.primary,
onPressed: () {
context.pushRoute(CrudCollectionRoute());
},
// context.read<HomeCubit>().toCrudCollection(CrudType.CREATE),
child: const Icon(Icons.add),
),
);
},
return Scaffold(
backgroundColor: AppColors.bg,
appBar: const CollectionsAppBar(),
body: _buildMain(context),
floatingActionButton: AnimatedOpacity(
opacity: _showFab ? 1.0 : 0.0,
duration: const Duration(milliseconds: 200),
child: FloatingActionButton(
backgroundColor: AppColors.primary,
onPressed: () => context.pushRoute(CrudCollectionRoute()),
child: const Icon(Icons.add),
),
),
);
}
///
/// Построение основго экрана
///
/// Построение основного экрана
Widget _buildMain(BuildContext context) {
return BlocBuilder<CollectionCubit, CollectionState>(
builder: (context, state) {
return Column(
children: [
CollectionsFilters(),
state.when(
loading: () => _LoadingList(),
data: () => _CollectionList(),
empty: () => _EmptyList(),
error: () => _ErrorList(),
),
],
);
},
return Column(
children: [
const CollectionsFilters(),
Expanded(
child: StreamBuilder<List<Collection>>(
stream: getIt<CollectionsInterface>().getCollectionsList(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const _LoadingList();
}
if (snapshot.hasError) {
return const _ErrorList();
}
final collections = snapshot.data;
if (collections == null || collections.isEmpty) {
return const _EmptyList();
}
return ListView.builder(
controller: _scrollController,
itemCount: collections.length,
padding: const EdgeInsets.symmetric(horizontal: 16).r,
itemBuilder:
(context, index) => Padding(
padding: const EdgeInsets.only(bottom: 8).r,
child: CollectionCard(collection: collections[index]),
),
);
},
),
),
],
);
}
}
@@ -111,54 +147,3 @@ class _EmptyList extends StatelessWidget {
);
}
}
class _CollectionList extends StatelessWidget {
const _CollectionList();
// @override
@override
Widget build(BuildContext context) {
print('build _CollectionList');
final CollectionCubit collectionCubit = context.read<CollectionCubit>();
collectionCubit.initScrollListener();
return Expanded(
child: StreamBuilder(
stream: getIt<AppDatabase>().collectionsDao.getCollections(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(color: AppColors.primary),
);
}
if (snapshot.connectionState == ConnectionState.active ||
snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return _ErrorList();
}
if (snapshot.data == null || snapshot.data!.isEmpty) {
return _EmptyList();
}
return ListView.builder(
controller: collectionCubit.collectionController,
itemCount: snapshot.data!.length,
padding: const EdgeInsets.symmetric(horizontal: 16).r,
itemBuilder:
(BuildContext context, int index) => Padding(
padding: const EdgeInsets.only(bottom: 8).r,
child: const CollectionCard(),
),
);
}
return Center(
child: CircularProgressIndicator(color: AppColors.primary),
);
},
),
);
}
}

View File

@@ -1,62 +0,0 @@
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:remever/components/notifiers/home_screen_data.dart';
import 'package:remever/database/database.dart';
import 'package:remever/inject.dart';
part 'collection_state.dart';
part 'collection_cubit.freezed.dart';
class CollectionCubit extends Cubit<CollectionState> {
CollectionCubit() : super(CollectionState.data());
/// Нотифаер домашнего экрана
CollectionData get _cd => getIt<CollectionData>();
/// Контроллер скролла для коллекции
final ScrollController collectionController = ScrollController();
/// Позиция скролле
double _previousScrollOffset = 0.0;
/// Индекс выбранной фильтрации коллекции
int collectionFiltersIndex = 0;
void initScrollListener() {
collectionController.addListener(() {
final double currentScrollOffset = collectionController.offset;
final bool isScrollingDown = currentScrollOffset > _previousScrollOffset;
if (isScrollingDown) {
_cd.showFab(false);
} else {
_cd.showFab(true);
}
_previousScrollOffset = currentScrollOffset;
});
}
@override
Future<void> close() {
collectionController.dispose();
return super.close();
}
Future<void> toLoadingState() async {
emit(CollectionState.loading());
}
Future<void> toDataState() async {
emit(CollectionState.data());
}
Future<void> toEmptyState() async {
emit(CollectionState.empty());
}
Future<void> toErrorState() async {
emit(CollectionState.error());
}
}

View File

@@ -1,560 +0,0 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'collection_cubit.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 _$CollectionState {
@optionalTypeArgs
TResult when<TResult extends Object?>({
required TResult Function() loading,
required TResult Function() data,
required TResult Function() empty,
required TResult Function() error,
}) => throw _privateConstructorUsedError;
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>({
TResult? Function()? loading,
TResult? Function()? data,
TResult? Function()? empty,
TResult? Function()? error,
}) => throw _privateConstructorUsedError;
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>({
TResult Function()? loading,
TResult Function()? data,
TResult Function()? empty,
TResult Function()? error,
required TResult orElse(),
}) => throw _privateConstructorUsedError;
@optionalTypeArgs
TResult map<TResult extends Object?>({
required TResult Function(_Loading value) loading,
required TResult Function(_Data value) data,
required TResult Function(_Empty value) empty,
required TResult Function(_Error value) error,
}) => throw _privateConstructorUsedError;
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>({
TResult? Function(_Loading value)? loading,
TResult? Function(_Data value)? data,
TResult? Function(_Empty value)? empty,
TResult? Function(_Error value)? error,
}) => throw _privateConstructorUsedError;
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>({
TResult Function(_Loading value)? loading,
TResult Function(_Data value)? data,
TResult Function(_Empty value)? empty,
TResult Function(_Error value)? error,
required TResult orElse(),
}) => throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $CollectionStateCopyWith<$Res> {
factory $CollectionStateCopyWith(
CollectionState value,
$Res Function(CollectionState) then,
) = _$CollectionStateCopyWithImpl<$Res, CollectionState>;
}
/// @nodoc
class _$CollectionStateCopyWithImpl<$Res, $Val extends CollectionState>
implements $CollectionStateCopyWith<$Res> {
_$CollectionStateCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
/// Create a copy of CollectionState
/// with the given fields replaced by the non-null parameter values.
}
/// @nodoc
abstract class _$$LoadingImplCopyWith<$Res> {
factory _$$LoadingImplCopyWith(
_$LoadingImpl value,
$Res Function(_$LoadingImpl) then,
) = __$$LoadingImplCopyWithImpl<$Res>;
}
/// @nodoc
class __$$LoadingImplCopyWithImpl<$Res>
extends _$CollectionStateCopyWithImpl<$Res, _$LoadingImpl>
implements _$$LoadingImplCopyWith<$Res> {
__$$LoadingImplCopyWithImpl(
_$LoadingImpl _value,
$Res Function(_$LoadingImpl) _then,
) : super(_value, _then);
/// Create a copy of CollectionState
/// with the given fields replaced by the non-null parameter values.
}
/// @nodoc
class _$LoadingImpl implements _Loading {
const _$LoadingImpl();
@override
String toString() {
return 'CollectionState.loading()';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is _$LoadingImpl);
}
@override
int get hashCode => runtimeType.hashCode;
@override
@optionalTypeArgs
TResult when<TResult extends Object?>({
required TResult Function() loading,
required TResult Function() data,
required TResult Function() empty,
required TResult Function() error,
}) {
return loading();
}
@override
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>({
TResult? Function()? loading,
TResult? Function()? data,
TResult? Function()? empty,
TResult? Function()? error,
}) {
return loading?.call();
}
@override
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>({
TResult Function()? loading,
TResult Function()? data,
TResult Function()? empty,
TResult Function()? error,
required TResult orElse(),
}) {
if (loading != null) {
return loading();
}
return orElse();
}
@override
@optionalTypeArgs
TResult map<TResult extends Object?>({
required TResult Function(_Loading value) loading,
required TResult Function(_Data value) data,
required TResult Function(_Empty value) empty,
required TResult Function(_Error value) error,
}) {
return loading(this);
}
@override
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>({
TResult? Function(_Loading value)? loading,
TResult? Function(_Data value)? data,
TResult? Function(_Empty value)? empty,
TResult? Function(_Error value)? error,
}) {
return loading?.call(this);
}
@override
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>({
TResult Function(_Loading value)? loading,
TResult Function(_Data value)? data,
TResult Function(_Empty value)? empty,
TResult Function(_Error value)? error,
required TResult orElse(),
}) {
if (loading != null) {
return loading(this);
}
return orElse();
}
}
abstract class _Loading implements CollectionState {
const factory _Loading() = _$LoadingImpl;
}
/// @nodoc
abstract class _$$DataImplCopyWith<$Res> {
factory _$$DataImplCopyWith(
_$DataImpl value,
$Res Function(_$DataImpl) then,
) = __$$DataImplCopyWithImpl<$Res>;
}
/// @nodoc
class __$$DataImplCopyWithImpl<$Res>
extends _$CollectionStateCopyWithImpl<$Res, _$DataImpl>
implements _$$DataImplCopyWith<$Res> {
__$$DataImplCopyWithImpl(_$DataImpl _value, $Res Function(_$DataImpl) _then)
: super(_value, _then);
/// Create a copy of CollectionState
/// with the given fields replaced by the non-null parameter values.
}
/// @nodoc
class _$DataImpl implements _Data {
const _$DataImpl();
@override
String toString() {
return 'CollectionState.data()';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is _$DataImpl);
}
@override
int get hashCode => runtimeType.hashCode;
@override
@optionalTypeArgs
TResult when<TResult extends Object?>({
required TResult Function() loading,
required TResult Function() data,
required TResult Function() empty,
required TResult Function() error,
}) {
return data();
}
@override
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>({
TResult? Function()? loading,
TResult? Function()? data,
TResult? Function()? empty,
TResult? Function()? error,
}) {
return data?.call();
}
@override
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>({
TResult Function()? loading,
TResult Function()? data,
TResult Function()? empty,
TResult Function()? error,
required TResult orElse(),
}) {
if (data != null) {
return data();
}
return orElse();
}
@override
@optionalTypeArgs
TResult map<TResult extends Object?>({
required TResult Function(_Loading value) loading,
required TResult Function(_Data value) data,
required TResult Function(_Empty value) empty,
required TResult Function(_Error value) error,
}) {
return data(this);
}
@override
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>({
TResult? Function(_Loading value)? loading,
TResult? Function(_Data value)? data,
TResult? Function(_Empty value)? empty,
TResult? Function(_Error value)? error,
}) {
return data?.call(this);
}
@override
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>({
TResult Function(_Loading value)? loading,
TResult Function(_Data value)? data,
TResult Function(_Empty value)? empty,
TResult Function(_Error value)? error,
required TResult orElse(),
}) {
if (data != null) {
return data(this);
}
return orElse();
}
}
abstract class _Data implements CollectionState {
const factory _Data() = _$DataImpl;
}
/// @nodoc
abstract class _$$EmptyImplCopyWith<$Res> {
factory _$$EmptyImplCopyWith(
_$EmptyImpl value,
$Res Function(_$EmptyImpl) then,
) = __$$EmptyImplCopyWithImpl<$Res>;
}
/// @nodoc
class __$$EmptyImplCopyWithImpl<$Res>
extends _$CollectionStateCopyWithImpl<$Res, _$EmptyImpl>
implements _$$EmptyImplCopyWith<$Res> {
__$$EmptyImplCopyWithImpl(
_$EmptyImpl _value,
$Res Function(_$EmptyImpl) _then,
) : super(_value, _then);
/// Create a copy of CollectionState
/// with the given fields replaced by the non-null parameter values.
}
/// @nodoc
class _$EmptyImpl implements _Empty {
const _$EmptyImpl();
@override
String toString() {
return 'CollectionState.empty()';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is _$EmptyImpl);
}
@override
int get hashCode => runtimeType.hashCode;
@override
@optionalTypeArgs
TResult when<TResult extends Object?>({
required TResult Function() loading,
required TResult Function() data,
required TResult Function() empty,
required TResult Function() error,
}) {
return empty();
}
@override
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>({
TResult? Function()? loading,
TResult? Function()? data,
TResult? Function()? empty,
TResult? Function()? error,
}) {
return empty?.call();
}
@override
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>({
TResult Function()? loading,
TResult Function()? data,
TResult Function()? empty,
TResult Function()? error,
required TResult orElse(),
}) {
if (empty != null) {
return empty();
}
return orElse();
}
@override
@optionalTypeArgs
TResult map<TResult extends Object?>({
required TResult Function(_Loading value) loading,
required TResult Function(_Data value) data,
required TResult Function(_Empty value) empty,
required TResult Function(_Error value) error,
}) {
return empty(this);
}
@override
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>({
TResult? Function(_Loading value)? loading,
TResult? Function(_Data value)? data,
TResult? Function(_Empty value)? empty,
TResult? Function(_Error value)? error,
}) {
return empty?.call(this);
}
@override
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>({
TResult Function(_Loading value)? loading,
TResult Function(_Data value)? data,
TResult Function(_Empty value)? empty,
TResult Function(_Error value)? error,
required TResult orElse(),
}) {
if (empty != null) {
return empty(this);
}
return orElse();
}
}
abstract class _Empty implements CollectionState {
const factory _Empty() = _$EmptyImpl;
}
/// @nodoc
abstract class _$$ErrorImplCopyWith<$Res> {
factory _$$ErrorImplCopyWith(
_$ErrorImpl value,
$Res Function(_$ErrorImpl) then,
) = __$$ErrorImplCopyWithImpl<$Res>;
}
/// @nodoc
class __$$ErrorImplCopyWithImpl<$Res>
extends _$CollectionStateCopyWithImpl<$Res, _$ErrorImpl>
implements _$$ErrorImplCopyWith<$Res> {
__$$ErrorImplCopyWithImpl(
_$ErrorImpl _value,
$Res Function(_$ErrorImpl) _then,
) : super(_value, _then);
/// Create a copy of CollectionState
/// with the given fields replaced by the non-null parameter values.
}
/// @nodoc
class _$ErrorImpl implements _Error {
const _$ErrorImpl();
@override
String toString() {
return 'CollectionState.error()';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is _$ErrorImpl);
}
@override
int get hashCode => runtimeType.hashCode;
@override
@optionalTypeArgs
TResult when<TResult extends Object?>({
required TResult Function() loading,
required TResult Function() data,
required TResult Function() empty,
required TResult Function() error,
}) {
return error();
}
@override
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>({
TResult? Function()? loading,
TResult? Function()? data,
TResult? Function()? empty,
TResult? Function()? error,
}) {
return error?.call();
}
@override
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>({
TResult Function()? loading,
TResult Function()? data,
TResult Function()? empty,
TResult Function()? error,
required TResult orElse(),
}) {
if (error != null) {
return error();
}
return orElse();
}
@override
@optionalTypeArgs
TResult map<TResult extends Object?>({
required TResult Function(_Loading value) loading,
required TResult Function(_Data value) data,
required TResult Function(_Empty value) empty,
required TResult Function(_Error value) error,
}) {
return error(this);
}
@override
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>({
TResult? Function(_Loading value)? loading,
TResult? Function(_Data value)? data,
TResult? Function(_Empty value)? empty,
TResult? Function(_Error value)? error,
}) {
return error?.call(this);
}
@override
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>({
TResult Function(_Loading value)? loading,
TResult Function(_Data value)? data,
TResult Function(_Empty value)? empty,
TResult Function(_Error value)? error,
required TResult orElse(),
}) {
if (error != null) {
return error(this);
}
return orElse();
}
}
abstract class _Error implements CollectionState {
const factory _Error() = _$ErrorImpl;
}

View File

@@ -1,9 +0,0 @@
part of 'collection_cubit.dart';
@freezed
sealed class CollectionState with _$CollectionState {
const factory CollectionState.loading() = _Loading;
const factory CollectionState.data() = _Data;
const factory CollectionState.empty() = _Empty;
const factory CollectionState.error() = _Error;
}

View File

@@ -1,3 +1,4 @@
import 'dart:convert';
import 'dart:math';
import 'package:auto_route/auto_route.dart';
@@ -6,15 +7,19 @@ import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:remever/common/functions.dart';
import 'package:remever/common/resources.dart';
import 'package:remever/common/widgets/typography.dart';
import 'package:remever/common/widgets/w_if.dart';
import 'package:remever/common/widgets/wspace.dart';
import 'package:remever/components/extensions/context.dart';
import 'package:remever/database/database.dart';
import 'package:remever/gen/assets.gen.dart';
import 'package:remever/router.gr.dart';
import 'package:remever/screens/collections/widgets/collection_progress_bar.dart';
import 'package:remever/screens/dialogs/action_dialog.dart';
class CollectionCard extends StatelessWidget {
const CollectionCard({super.key});
const CollectionCard({super.key, required this.collection});
final Collection collection;
@override
Widget build(BuildContext context) {
@@ -36,7 +41,10 @@ class CollectionCard extends StatelessWidget {
context: context,
backgroundColor: const Color(0xFFFFE4E6),
foregroundColor: const Color(0xFFFF5C69),
icon: Icons.favorite_border,
icon:
collection.isLiked
? Icons.favorite_outlined
: Icons.favorite_border,
onPressed: () {},
),
const WSpace(8),
@@ -113,13 +121,16 @@ class CollectionCard extends StatelessWidget {
_buildIconWithText(
icon: Assets.icons.typeCards,
color: AppColors.disabled,
text: Random().nextInt(654).toString(),
text: collection.likesCount.toString(),
),
const WSpace(8),
_buildIconWithText(
icon: Assets.icons.typeLike1818,
icon:
collection.isLiked
? Assets.icons.typeLike1818
: Assets.icons.typeLike,
color: AppColors.danger,
text: Random().nextInt(7689).toString(),
text: collection.likesCount.toString(),
),
],
);
@@ -130,7 +141,7 @@ class CollectionCard extends StatelessWidget {
///
Widget _buildTitle() {
return AppTypography(
'Астрономия',
collection.title,
type: Medium16px(),
maxLines: 2,
softWrap: true,
@@ -141,6 +152,31 @@ class CollectionCard extends StatelessWidget {
/// Обложка коллекции
///
Widget _buildAvatar() {
return SizedBox.square(
dimension: 50.r,
child: DecoratedBox(
decoration: BoxDecoration(shape: BoxShape.circle, color: AppColors.bg),
child: Wif(
condition: collection.image != null,
builder:
(context) => ClipOval(
child: Image.memory(
base64Decode(collection.image!),
fit: BoxFit.cover,
),
),
fallback:
(context) => Center(
child: AppTypography(
collection.title.substring(0, 1),
type: Bold34px(),
),
),
),
),
);
return SizedBox.square(
dimension: 50.r,
child: DecoratedBox(

View File

@@ -4,7 +4,6 @@ import 'package:remever/common/resources.dart';
import 'package:remever/common/widgets/typography.dart';
import 'package:remever/components/extensions/context.dart';
import 'package:remever/components/extensions/state.dart';
import 'package:remever/screens/collections/cubit/collection_cubit.dart';
class CollectionsFilters extends StatefulWidget {
const CollectionsFilters({super.key});
@@ -21,36 +20,15 @@ class _CollectionsFiltersState extends State<CollectionsFilters> {
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
_buildFilterButton(
context.read<CollectionCubit>().collectionFiltersIndex == 0
? AppColors.white
: AppColors.gray_bg,
'Все',
() {
context.read<CollectionCubit>().collectionFiltersIndex = 0;
safeSetState(() {});
},
),
_buildFilterButton(
context.read<CollectionCubit>().collectionFiltersIndex == 1
? AppColors.white
: AppColors.gray_bg,
'Публичные',
() {
context.read<CollectionCubit>().collectionFiltersIndex = 1;
safeSetState(() {});
},
),
_buildFilterButton(
context.read<CollectionCubit>().collectionFiltersIndex == 2
? AppColors.white
: AppColors.gray_bg,
'Подписки',
() {
context.read<CollectionCubit>().collectionFiltersIndex = 2;
safeSetState(() {});
},
),
_buildFilterButton(AppColors.white, 'Все', () {
safeSetState(() {});
}),
_buildFilterButton(AppColors.gray_bg, 'Публичные', () {
safeSetState(() {});
}),
_buildFilterButton(AppColors.gray_bg, 'Подписки', () {
safeSetState(() {});
}),
],
),
);

View File

@@ -68,6 +68,7 @@ class CreateScreen extends StatelessWidget {
title: 'Вопрос',
hint: '',
height: 313,
onEditingComplete: (p0) {},
),
);
},
@@ -83,6 +84,7 @@ class CreateScreen extends StatelessWidget {
title: 'Ответ',
hint: '',
height: 313,
onEditingComplete: (p0) {},
),
);
},

View File

@@ -1,19 +1,25 @@
import 'dart:convert';
import 'dart:io';
import 'package:auto_route/auto_route.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:remever/common/functions.dart';
import 'package:remever/common/resources.dart';
import 'package:remever/common/toast.dart';
import 'package:remever/common/widgets/bottom_safe_space.dart';
import 'package:remever/common/widgets/typography.dart';
import 'package:remever/common/widgets/w_if.dart';
import 'package:remever/common/widgets/wspace.dart';
import 'package:remever/components/extensions/context.dart';
import 'package:remever/gen/assets.gen.dart';
import 'package:remever/inject.dart';
import 'package:remever/models/collection_dto.dart';
import 'package:remever/router.gr.dart';
import 'package:remever/screens/crud_collection/widgets/crud_collection_field.dart';
import 'package:remever/screens/dialogs/alert_dialog.dart';
import 'package:remever/screens/dialogs/tags_dialog.dart';
import 'package:remever/services/collection/collections_interface.dart';
import 'package:remever/widgets/primary_button.dart';
import '../../../components/extensions/state.dart';
@@ -34,11 +40,49 @@ class _CrudCollectionScreenState extends State<CrudCollectionScreen> {
/// Флаг публичности коллекции
bool _isPublic = false;
CollectionDto? _collection;
/// Смена публичности
void _setPublic(bool public) {
_collection = _collection?.copyWith(isPublic: public);
safeSetState(() => _isPublic = public);
}
@override
void initState() {
_collection = CollectionDto(desc: '', title: '', isPublic: false);
super.initState();
}
void _pickImage() async {
final result = await FilePicker.platform.pickFiles();
if (result == null || result.files.isEmpty) {
showErrorToast('Файл не выбран');
return;
}
final filePath = result.files.single.path;
if (filePath == null) {
showErrorToast('Не удалось получить путь к файлу');
return;
}
final file = File(filePath);
final bytes = await file.readAsBytes();
final base64String = base64Encode(bytes);
_collection = _collection?.copyWith(avatar: base64String);
safeSetState(() {});
print('Base64 строка: $base64String');
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -88,16 +132,18 @@ class _CrudCollectionScreenState extends State<CrudCollectionScreen> {
Widget _buildCreateBtn(BuildContext context) {
return PrimaryButton(
height: 52,
onTap: () {
if (true) {
Toast.showDismissible(
onTap: () async {
if (_collection!.desc.isEmpty && _collection!.title.isEmpty) {
showErrorToast(
'Для создания публичной коллекции добавьте описание и тэги',
);
return;
}
// context.read<HomeCubit>().toCollection();
getIt<CollectionsInterface>().createCollection(_collection!);
context.back();
},
color: AppColors.primary,
child: AppTypography(
@@ -238,9 +284,19 @@ class _CrudCollectionScreenState extends State<CrudCollectionScreen> {
height: 110,
width: 348,
hint: 'Добавить описание',
content: _collection?.desc,
onTap: () {
context.pushRoute(
CrudCollectionFullscreenField(title: 'Описание', height: 333),
CrudCollectionFullscreenField(
title: 'Описание',
height: 333,
content: _collection?.desc,
onEditingComplete: (res) {
safeSetState(
() => _collection = _collection?.copyWith(desc: res ?? ''),
);
},
),
);
},
),
@@ -265,11 +321,18 @@ class _CrudCollectionScreenState extends State<CrudCollectionScreen> {
height: 91,
width: 225,
hint: 'Добавить название',
content: _collection?.title,
onTap: () {
context.pushRoute(
CrudCollectionFullscreenField(
title: 'Название',
hint: 'Максимальное количество символов - 250',
content: _collection?.title,
onEditingComplete: (res) {
safeSetState(
() => _collection = _collection?.copyWith(title: res ?? ''),
);
},
),
);
},
@@ -280,26 +343,40 @@ class _CrudCollectionScreenState extends State<CrudCollectionScreen> {
/// Построение обложки
Widget _buildPhoto() {
return SizedBox.square(
dimension: 115.r,
child: DecoratedBox(
decoration: const BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(
colors: <Color>[Color(0xFFB6AAFE), Color(0xFFDBD7F4)],
begin: Alignment.bottomLeft,
end: Alignment.topRight,
),
),
child: SizedBox.square(
dimension: 32.r,
child: Center(
child: Assets.icons.typePhoto.image(
height: 32.h,
width: 32.w,
color: AppColors.primary,
return GestureDetector(
onTap: () => _pickImage(),
child: SizedBox.square(
dimension: 115.r,
child: DecoratedBox(
decoration: const BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(
colors: <Color>[Color(0xFFB6AAFE), Color(0xFFDBD7F4)],
begin: Alignment.bottomLeft,
end: Alignment.topRight,
),
),
child: Wif(
condition: _collection!.avatar != null,
builder:
(context) => ClipOval(
child: Image.memory(
base64Decode(_collection!.avatar!),
fit: BoxFit.cover,
),
),
fallback:
(context) => SizedBox.square(
dimension: 32.r,
child: Center(
child: Assets.icons.typePhoto.image(
height: 32.h,
width: 32.w,
color: AppColors.primary,
),
),
),
),
),
),
);

View File

@@ -33,8 +33,8 @@ class CrudCollectionField extends StatelessWidget {
child: Padding(
padding: const EdgeInsets.all(12).r,
child:
content != null
? AppTypography(hint, maxLines: 99, type: Regular16px())
content != null && content!.isNotEmpty
? AppTypography(content!, maxLines: 99, type: Regular16px())
: AppTypography(
hint,
maxLines: 99,

View File

@@ -1,6 +1,7 @@
import 'package:auto_route/auto_route.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_keyboard_size/flutter_keyboard_size.dart';
import 'package:remever/common/functions.dart';
import 'package:remever/common/resources.dart';
@@ -11,55 +12,86 @@ import 'package:remever/gen/assets.gen.dart';
import 'package:remever/screens/dialogs/alert_dialog.dart';
@RoutePage()
class CrudCollectionFullscreenField extends StatelessWidget {
CrudCollectionFullscreenField({
class CrudCollectionFullscreenField extends StatefulWidget {
const CrudCollectionFullscreenField({
super.key,
this.title = '',
this.hint,
this.content,
this.height = 92,
required this.onEditingComplete,
});
final String title;
final double height;
final String? hint;
final String? content;
final void Function(String?) onEditingComplete;
@override
State<CrudCollectionFullscreenField> createState() =>
_CrudCollectionFullscreenFieldState();
}
class _CrudCollectionFullscreenFieldState
extends State<CrudCollectionFullscreenField> {
final TextEditingController _controller = TextEditingController();
@override
void initState() {
if (widget.content != null) {
_controller.text = widget.content!;
}
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return KeyboardSizeProvider(
child: Scaffold(
backgroundColor: AppColors.gray_bg,
appBar: _buildAppBar(context),
body: _buildMainBody(context),
child: SafeArea(
top: false,
child: Scaffold(
backgroundColor: AppColors.gray_bg,
appBar: _buildAppBar(context),
body: _buildMainBody(context),
),
),
);
}
/// Построение основного тела экрана
Widget _buildMainBody(BuildContext context) {
return Column(
children: <Widget>[
return Stack(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16).r,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const HSpace(16),
_buildField(context),
if (hint != null) ...<Widget>[
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const HSpace(16),
AppTypography(
hint!,
type: Regular14px(),
color: AppColors.disabled,
),
_buildField(context),
if (widget.hint != null) ...[
const HSpace(16),
AppTypography(
widget.hint!,
type: Regular14px(),
color: AppColors.disabled,
),
],
const HSpace(50),
],
],
),
),
),
const Spacer(),
_buildMenu(),
Align(alignment: Alignment.bottomCenter, child: _buildMenu()),
],
);
}
@@ -67,9 +99,10 @@ class CrudCollectionFullscreenField extends StatelessWidget {
/// Построение интерактивной плашки меню
Widget _buildMenu() {
return Consumer<ScreenHeight>(
builder: (BuildContext context, ScreenHeight res, Widget? child) {
builder: (context, screenHeight, _) {
return AnimatedOpacity(
opacity: res.isOpen ? 1 : 0,
// opacity: screenHeight.isOpen ? 1 : 0,
opacity: 1,
duration: const Duration(milliseconds: 500),
child: Container(
height: 64.h,
@@ -81,37 +114,10 @@ class CrudCollectionFullscreenField extends StatelessWidget {
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
GestureDetector(
onTap: () {},
child: Assets.icons.typePaste.image(
height: 24.h,
width: 24.w,
),
),
GestureDetector(
onTap: () {},
child: Assets.icons.typeCopy.image(height: 24.h, width: 24.w),
),
GestureDetector(
onTap: () => context.back(),
child: SizedBox.square(
dimension: 32.r,
child: DecoratedBox(
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: AppColors.primary,
),
child: Center(
child: Assets.icons.typeCheck.image(
height: 24.h,
width: 24.w,
color: AppColors.white,
),
),
),
),
),
children: [
_buildPasteButton(),
_buildCopyButton(),
_buildSubmitButton(),
],
),
),
@@ -120,14 +126,96 @@ class CrudCollectionFullscreenField extends StatelessWidget {
);
}
/// Кнопка "Вставить из буфера обмена"
Widget _buildPasteButton() {
return GestureDetector(
onTap: _onPasteTap,
child: Assets.icons.typePaste.image(height: 24.h, width: 24.w),
);
}
/// Обработка нажатия на кнопку "Вставить"
void _onPasteTap() async {
try {
final ClipboardData? data = await Clipboard.getData('text/plain');
if (data?.text == null || data!.text!.isEmpty) {
showErrorToast('Не удалось получить текст из буфера обмена');
return;
}
_controller.text += ' ${data.text}';
showSuccessToast('Текст вставлен из буфера обмена');
} catch (e) {
showErrorToast('Ошибка при вставке текста: $e');
}
}
/// Кнопка "Скопировать в буфер обмена"
Widget _buildCopyButton() {
return GestureDetector(
onTap: _onCopyTap,
child: Assets.icons.typeCopy.image(height: 24.h, width: 24.w),
);
}
/// Обработка нажатия на кнопку "Копировать"
void _onCopyTap() async {
if (_controller.text.isEmpty) {
showErrorToast('Нет содержимого для отправки в буфер обмена');
return;
}
try {
await Clipboard.setData(ClipboardData(text: _controller.text));
showSuccessToast('Текст скопирован в буфер обмена');
} catch (e) {
showErrorToast('Ошибка при копировании текста: $e');
}
}
/// Кнопка "Подтвердить"
Widget _buildSubmitButton() {
return GestureDetector(
onTap: _onSubmitTap,
child: SizedBox.square(
dimension: 32.r,
child: DecoratedBox(
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: AppColors.primary,
),
child: Center(
child: Assets.icons.typeCheck.image(
height: 24.h,
width: 24.w,
color: AppColors.white,
),
),
),
),
);
}
/// Обработка нажатия на кнопку "Подтвердить"
void _onSubmitTap() {
if (_controller.text.isEmpty) {
showErrorToast(
'Для создания публичной коллекции добавьте описание и тэги',
);
return;
}
widget.onEditingComplete(_controller.text);
context.back();
}
/// Построение поля ввода
Widget _buildField(BuildContext context) {
return SizedBox(
height: height.h,
height: widget.height.h,
child: DecoratedBox(
decoration: BoxDecoration(
color: AppColors.white,
borderRadius: const BorderRadius.all(Radius.circular(12)).r,
borderRadius: BorderRadius.circular(12).r,
),
child: Padding(
padding: const EdgeInsets.all(12).r,
@@ -136,6 +224,7 @@ class CrudCollectionFullscreenField extends StatelessWidget {
controller: _controller,
textCapitalization: TextCapitalization.sentences,
maxLines: 99,
maxLength: 250,
cursorColor: AppColors.danger,
decoration: const InputDecoration.collapsed(
hintText: 'Введите содержимое',
@@ -154,50 +243,23 @@ class CrudCollectionFullscreenField extends StatelessWidget {
backgroundColor: AppColors.white,
shadowColor: Colors.transparent,
leading: IconButton(
onPressed: () async {
context.back();
},
onPressed: () => _handleBackPress(context),
icon: const Icon(CupertinoIcons.left_chevron, color: Colors.black),
),
centerTitle: true,
title: GestureDetector(
onLongPress: () async {
final bool? res = await showCuperModalBottomSheet(
context: context,
height: 262.h,
builder:
(BuildContext context) => const AlertInfoDialog(
title:
'Вы хотите выйти из режима создания описания коллекции?',
acceptTitle: 'Выйти, не сохранять',
declineTitle: 'Сохранить и выйти',
),
);
if (res != null && res) context.back();
},
// onLongPress: () => _showExitDialog(context),
child: AppTypography(
title,
widget.title,
type: SemiBold20px(),
color: AppColors.body_text,
),
),
actions: <Widget>[
actions: [
Padding(
padding: const EdgeInsets.only(right: 16).r,
child: GestureDetector(
onTap: () {
showCuperModalBottomSheet(
context: context,
height: 262.h,
builder:
(BuildContext context) => const AlertInfoDialog(
title: 'Вы хотите сбросить все внесенные изменения?',
acceptTitle: 'Да, сбросить',
declineTitle: 'Нет, оставить',
),
);
},
onTap: () => _showResetDialog(context),
child: Assets.icons.typeTrash.image(
height: 24.h,
width: 24.w,
@@ -208,4 +270,40 @@ class CrudCollectionFullscreenField extends StatelessWidget {
],
);
}
/// Обработка нажатия на кнопку "Назад"
void _handleBackPress(BuildContext context) async {
// final bool? shouldExit = await _showExitDialog(context);
// if (shouldExit ?? false) {
context.back();
// }
}
/// Показать диалог выхода
Future<bool?> _showExitDialog(BuildContext context) async {
return showCuperModalBottomSheet(
context: context,
height: 262.h,
builder:
(context) => const AlertInfoDialog(
title: 'Вы хотите выйти из режима создания описания коллекции?',
acceptTitle: 'Выйти, не сохранять',
declineTitle: 'Сохранить и выйти',
),
);
}
/// Показать диалог сброса
void _showResetDialog(BuildContext context) {
// showCuperModalBottomSheet(
// context: context,
// height: 262.h,
// builder:
// (context) => const AlertInfoDialog(
// title: 'Вы хотите сбросить все внесенные изменения?',
// acceptTitle: 'Да, сбросить',
// declineTitle: 'Нет, оставить',
// ),
// );
}
}

View File

@@ -7,7 +7,7 @@ import 'package:remever/components/extensions/context.dart';
import 'package:remever/components/extensions/state.dart';
import 'package:remever/gen/assets.gen.dart';
import 'package:remever/router.gr.dart';
import 'package:remever/services/auth_interface.dart';
import 'package:remever/services/auth/auth_interface.dart';
@RoutePage()
class SplashScreen extends StatefulWidget {
@@ -51,7 +51,8 @@ class _SplashScreenState extends State<SplashScreen> {
safeSetState(() => _launchLogo = !_launchLogo);
});
Future<void>.delayed(const Duration(seconds: 4), _navigate);
// Future<void>.delayed(const Duration(seconds: 4), _navigate);
Future<void>.delayed(const Duration(seconds: 1), _navigate);
});
super.initState();

View File

@@ -5,7 +5,7 @@ import 'package:remever/common/resources.dart';
import 'package:remever/common/services/api_client.dart';
import 'package:remever/common/storage.dart';
import 'package:remever/common/typedef.dart';
import 'package:remever/services/auth_interface.dart';
import 'package:remever/services/auth/auth_interface.dart';
///
/// Сервис авторизации

View File

@@ -0,0 +1,13 @@
import 'package:remever/database/database.dart';
import 'package:remever/models/collection_dto.dart';
///
/// Интерфейс взаимодействия с коллекциями
///
abstract interface class CollectionsInterface {
/// Получение списка коллекций
Stream<List<Collection>> getCollectionsList();
/// Создание новой коллекции
Future<void> createCollection(CollectionDto dto);
}

View File

@@ -0,0 +1,22 @@
import 'package:injectable/injectable.dart';
import 'package:remever/database/database.dart';
import 'package:remever/inject.dart';
import 'package:remever/models/collection_dto.dart';
import 'package:remever/services/collection/collections_interface.dart';
///
/// Сервис авторизации
///
@Singleton(as: CollectionsInterface)
final class CollectionsService implements CollectionsInterface {
@override
Stream<List<Collection>> getCollectionsList() {
return getIt<AppDatabase>().collectionsDao.getCollections();
}
@override
Future<void> createCollection(CollectionDto dto) async {
return await getIt<AppDatabase>().collectionsDao.createCollection(dto);
}
}