feat(recipe): Models, service and repository for eecpe create. Recipe create now uses cubit

This commit is contained in:
2024-08-14 14:36:06 +03:00
parent c53fa419d7
commit f697f403f4
26 changed files with 2817 additions and 913 deletions

View File

@@ -1,193 +0,0 @@
import 'dart:async';
import 'dart:convert';
import 'package:eatvio_app/app_router.dart';
import 'package:eatvio_app/presentation/recipe/recipe_create_screen/models/recipe_create_model.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:hive/hive.dart';
import 'package:http/http.dart' as http;
import '/core/app_export.dart';
part 'recipe_create_event.dart';
part 'recipe_create_state.dart';
/// A bloc that manages the state of a RecipeCreate according to the event that is dispatched to it.
class RecipeCreateBloc extends Bloc<RecipeCreateEvent, RecipeCreateState> {
RecipeCreateBloc(RecipeCreateState initialState) : super(initialState) {
on<RecipeCreateInitialEvent>(_onInitialize);
on<CreateRecipe>(_createRecipe);
on<AddStep>(_addStep);
on<RemoveStep>(_removeStep);
on<ReloadScreen>(_reloadScreen);
}
_onInitialize(
RecipeCreateInitialEvent event,
Emitter<RecipeCreateState> emit,
) async {
final box = await Hive.openBox('token');
final token = box.get('token');
if (token == null) {
AppRouter.navigatorKey.currentContext?.goNamed('authScreen');
}
if (state is RecipeCreateLoadedState) {
var currentState = state as RecipeCreateLoadedState;
emit(
currentState.copyWith(
recipeModelObj: currentState.recipeModelObj,
title: currentState.title,
token: currentState.token,
description: currentState.description,
video_url: currentState.video_url,
steps: currentState.steps,
stepDescriptions: currentState.stepDescriptions,
tags: currentState.tags,
),
);
} else {
final Map<String, dynamic> step = {
'description': '',
'image': '',
};
emit(
RecipeCreateLoadedState(
token: token,
title: TextEditingController(),
description: TextEditingController(),
video_url: TextEditingController(),
tags: TextEditingController(),
stepDescriptions: [TextEditingController()],
steps: [step],
),
);
}
}
FutureOr<void> _addStep(
AddStep event,
Emitter<RecipeCreateState> emit,
) async {
if (state is RecipeCreateLoadedState) {
var currentState = state as RecipeCreateLoadedState;
List<dynamic>? updatedSteps = currentState.steps;
List<TextEditingController>? updatedStepDescriptions = currentState.stepDescriptions;
updatedSteps!.add({
'description': '',
'image': '',
});
updatedStepDescriptions!.add(TextEditingController());
emit(
currentState.copyWith(
steps: updatedSteps,
stepDescriptions: updatedStepDescriptions,
),
);
await _reloadScreen(event, emit);
}
}
FutureOr<void> _removeStep(
RemoveStep event,
Emitter<RecipeCreateState> emit,
) async {
if (state is RecipeCreateLoadedState) {
var currentState = state as RecipeCreateLoadedState;
List<dynamic>? updatedSteps = currentState.steps;
List<TextEditingController>? updatedStepDescriptions = currentState.stepDescriptions;
updatedSteps!.removeAt(event.id);
updatedStepDescriptions!.removeAt(event.id);
emit(
currentState.copyWith(
steps: updatedSteps,
stepDescriptions: updatedStepDescriptions,
),
);
await _reloadScreen(event, emit);
}
}
FutureOr<void> _createRecipe(
CreateRecipe event,
Emitter<RecipeCreateState> emit,
) async {
if (state is RecipeCreateLoadedState) {
var currentState = state as RecipeCreateLoadedState;
var response = await sendRecipe(
currentState.title?.text,
currentState.video_url?.text,
currentState.description?.text,
currentState.steps,
);
if (response.statusCode == 200) {
AppRouter.navigatorKey.currentContext?.goNamed('recipeSelectScreen');
} else {
print(
'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}',
);
}
}
}
FutureOr<http.Response> sendRecipe(
String? title,
String? video_url,
String? description,
List<dynamic>? steps,
) async {
String url = '${baseUrl}/api/recipe/create';
final Map<String, dynamic> credentials = {
'title': title,
'description': description,
'video_url': video_url,
'steps': steps,
'status': 'active',
};
var response = await http.post(
Uri.parse(url),
headers: {
'Content-Type': 'application/json',
},
body: json.encode(credentials),
encoding: utf8,
);
return response;
}
FutureOr<void> _reloadScreen(
RecipeCreateEvent? event,
Emitter<RecipeCreateState> emit,
) async {
print('Reloading..');
final box = await Hive.openBox('token');
final token = box.get('token');
if (token == null) {
AppRouter.navigatorKey.currentContext?.goNamed('authScreen');
}
if (state is RecipeCreateLoadedState) {
var currentState = state as RecipeCreateLoadedState;
emit(
currentState.copyWith(
recipeModelObj: currentState.recipeModelObj,
title: currentState.title,
token: currentState.token,
description: currentState.description,
video_url: currentState.video_url,
steps: currentState.steps,
stepDescriptions: currentState.stepDescriptions,
tags: currentState.tags,
),
);
}
}
}

View File

@@ -1,44 +0,0 @@
// ignore_for_file: must_be_immutable
part of 'recipe_create_bloc.dart';
/// Abstract class for all events that can be dispatched from the
///RecipeCreate widget.
///
/// Events must be immutable and implement the [Equatable] interface.
@immutable
abstract class RecipeCreateEvent extends Equatable {}
/// Event that is dispatched when the RecipeCreate widget is first created.
class RecipeCreateInitialEvent extends RecipeCreateEvent {
@override
List<Object?> get props => [];
}
class CreateRecipe extends RecipeCreateEvent {
@override
List<Object?> get props => [];
}
class AddStep extends RecipeCreateEvent {
AddStep();
@override
List<Object?> get props => [];
}
class RemoveStep extends RecipeCreateEvent {
RemoveStep(this.id);
final int id;
@override
List<Object?> get props => [id];
}
class ReloadScreen extends RecipeCreateEvent {
ReloadScreen();
@override
List<Object?> get props => [];
}

View File

@@ -1,92 +0,0 @@
// ignore_for_file: must_be_immutable
part of 'recipe_create_bloc.dart';
/// Represents the state of RecipeCreate in the application.
///
class RecipeCreateState extends Equatable {
RecipeCreateState({
this.recipeModelObj,
});
RecipeCreateModel? recipeModelObj;
@override
List<Object?> get props => [recipeModelObj];
RecipeCreateState copyWith({RecipeCreateModel? recipeModelObj}) {
return RecipeCreateState(
recipeModelObj: recipeModelObj ?? this.recipeModelObj,
);
}
}
class RecipeCreateLoadedState extends RecipeCreateState {
RecipeCreateLoadedState({
this.recipeModelObj,
this.token,
this.title,
this.description,
this.video_url,
this.tags,
this.stepDescriptions,
this.steps,
});
RecipeCreateModel? recipeModelObj;
String? token;
TextEditingController? title;
TextEditingController? description;
TextEditingController? video_url;
TextEditingController? tags;
List<dynamic>? steps;
List<TextEditingController>? stepDescriptions;
@override
List<Object?> get props => [
recipeModelObj,
title,
token,
description,
video_url,
steps,
tags,
stepDescriptions,
];
RecipeCreateLoadedState copyWith({
RecipeCreateModel? recipeModelObj,
String? token,
TextEditingController? title,
TextEditingController? description,
TextEditingController? video_url,
TextEditingController? tags,
List<dynamic>? steps,
List<TextEditingController>? stepDescriptions,
}) {
return RecipeCreateLoadedState(
recipeModelObj: recipeModelObj ?? this.recipeModelObj,
title: title ?? this.title,
description: description ?? this.description,
video_url: video_url ?? this.video_url,
token: token ?? this.token,
steps: steps ?? this.steps,
tags: tags ?? this.tags,
stepDescriptions: stepDescriptions ?? this.stepDescriptions,
);
}
}
class RecipeCreateErrorState extends RecipeCreateState {
final String errorMessage;
RecipeCreateErrorState(this.errorMessage);
@override
List<Object> get props => [errorMessage];
}
class RecipeCreateInitialState extends RecipeCreateState {
RecipeCreateInitialState({required RecipeCreateModel recipeModelObj}) : super(recipeModelObj: recipeModelObj);
}

View File

@@ -1,17 +0,0 @@
// ignore_for_file: must_be_immutable
import 'package:equatable/equatable.dart';
/// This class defines the variables used in the [recipe_create_screen],
/// and is typically used to hold data that is passed between different parts of the application.
class RecipeCreateModel extends Equatable {
RecipeCreateModel();
RecipeCreateModel copyWith() {
return RecipeCreateModel();
}
@override
List<Object?> get props => [];
}

View File

@@ -1,413 +0,0 @@
import 'package:eatvio_app/core/app_export.dart';
import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart';
import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart';
import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart';
import 'package:eatvio_app/widgets/custom_outlined_button.dart';
import 'package:eatvio_app/widgets/custom_text_form_field.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'bloc/recipe_create_bloc.dart';
import 'models/recipe_create_model.dart';
class RecipeCreateScreen extends StatelessWidget {
const RecipeCreateScreen({Key? key}) : super(key: key);
static Widget builder(BuildContext context) {
return BlocProvider<RecipeCreateBloc>(
create: (context) => RecipeCreateBloc(
RecipeCreateState(recipeModelObj: RecipeCreateModel()))
..add(RecipeCreateInitialEvent()),
child: RecipeCreateScreen(),
);
}
Widget build(BuildContext context) {
return BlocBuilder<RecipeCreateBloc, RecipeCreateState>(
builder: (context, state) {
if (state is RecipeCreateInitialState) {
// Это начальное состояние, данные ещё не загружены.
return Container(
color: Colors.white,
);
} else if (state is RecipeCreateLoadedState) {
// Данные загружены, можно строить экран.
return _buildRecipeCreate(context, state);
} else if (state is RecipeCreateErrorState) {
// Произошла ошибка при загрузке данных.
return Center(child: Text(state.errorMessage));
} else {
// Другие состояния, если они есть.
return Container(); // Пустой контейнер для необработанных состояний.
}
},
);
}
_buildRecipeCreate(BuildContext context, RecipeCreateLoadedState state) {
mediaQueryData = MediaQuery.of(context);
List<Widget> steps = [];
if (state.steps != null) {
for (int i = 0; i < state.steps!.length; i++) {
steps.add(_buildStep(context, state, i));
}
}
return RefreshIndicator(
onRefresh: refreshPage(context),
child: Scaffold(
appBar: AppBar(
toolbarHeight: 0,
automaticallyImplyLeading: false,
),
resizeToAvoidBottomInset: false,
body: Container(
width: double.maxFinite,
decoration: BoxDecoration(color: Colors.grey[200]),
child: ListView(
children: [
_buldAppBar(context),
SizedBox(height: 20.v),
_buildRecipeInfo(state, context),
SizedBox(height: 20.v),
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: steps,
),
SizedBox(height: 20.v),
_buildAdditional(context, state),
],
),
),
),
);
}
_buldAppBar(BuildContext context) {
return Container(
margin: EdgeInsets.all(16.h),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.all(Radius.circular(12)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 5,
offset: Offset(0, 3),
),
],
),
child: CustomAppBar(
height: 54.v,
leadingWidth: 28.h,
leading: AppbarLeadingImage(
imagePath: ImageConstant.imgArrowLeft,
margin: EdgeInsets.only(left: 16.h, top: 15.v, bottom: 15.v),
onTap: onTapBack(context),
),
title: Align(
alignment: Alignment.center,
child: AppbarSubtitle(
text: "Добавление рецепта",
),
),
),
);
}
_buildRecipeInfo(RecipeCreateLoadedState state, BuildContext context) {
return Container(
margin: EdgeInsets.only(
left: 16.h,
right: 16.h,
bottom: 10.h,
),
padding: EdgeInsets.all(12.h),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.all(Radius.circular(12)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 5,
offset: Offset(0, 3),
),
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(height: 16.0),
Align(alignment: Alignment.centerLeft, child: Text("Изображение")),
_buildAddPhoto(context, state),
SizedBox(height: 16.0),
Align(
alignment: Alignment.centerLeft, child: Text("Название рецепта")),
CustomTextFormField(
controller: state.title,
hintText: "Введите название рецепта",
fillColor: appTheme.gray50,
borderDecoration: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.h),
borderSide: BorderSide(
color: appTheme.gray50,
width: 1,
),
),
),
SizedBox(height: 16.0),
Align(alignment: Alignment.centerLeft, child: Text("Описание")),
CustomTextFormField(
controller: state.description,
hintText: "Введите описание рецепта",
maxLines: 4,
fillColor: appTheme.gray50,
borderDecoration: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.h),
borderSide: BorderSide(
color: appTheme.gray50,
width: 1,
),
),
),
SizedBox(height: 16.0),
],
),
);
}
refreshPage(BuildContext context) {
return () async {
context.read<RecipeCreateBloc>().add(ReloadScreen());
};
}
_buildAddPhoto(BuildContext context, RecipeCreateLoadedState state) {
bool isLoading = false;
return GestureDetector(
child: Stack(
children: [
if (!isLoading)
Container(
padding: EdgeInsets.symmetric(
horizontal: 40.h,
vertical: 80.v,
),
decoration: AppDecoration.fillGray.copyWith(
borderRadius: BorderRadiusStyle.roundedBorder5,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: EdgeInsets.only(
left: 7.h,
top: 5.v,
),
child: Text(
"Добавить фото",
selectionColor: appTheme.blueA400,
),
),
Spacer(),
Icon(
Icons.photo_library,
color: appTheme.blueGray300,
),
],
),
),
/*if (isLoading)
Container(
margin: EdgeInsets.symmetric(horizontal: 10.h),
padding: EdgeInsets.symmetric(
horizontal: 40.h,
vertical: 80.v,
),
decoration: AppDecoration.fillGray.copyWith(
borderRadius: BorderRadiusStyle.roundedBorder5,
),
child: Center(
child: CircularProgressIndicator(
color: appTheme
.blueGray300), // Замените на свой прелоадер при необходимости
),
),*/
],
),
);
}
_buildStep(BuildContext context, RecipeCreateLoadedState state, int i) {
bool isLastStep = i == state.steps!.length - 1;
bool isFirstStep = i == 0;
return Container(
margin: EdgeInsets.only(
left: 16.h,
right: 16.h,
bottom: 10.h,
),
padding: EdgeInsets.all(12.h),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.all(Radius.circular(12)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 5,
offset: Offset(0, 3),
),
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Align(
alignment: Alignment.centerLeft,
child: Text(
"Шаг ${i + 1}",
style: CustomTextStyles.titleMediumSemiBold,
),
),
SizedBox(height: 8.0),
CustomTextFormField(
controller: state.stepDescriptions?[i],
hintText: "Введите описание шага",
maxLines: 4,
fillColor: appTheme.gray50,
borderDecoration: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.h),
borderSide: BorderSide(
color: appTheme.gray50,
width: 1,
),
),
),
SizedBox(height: 16.0),
_buildAddPhoto(context, state),
SizedBox(height: 16.0),
if (isFirstStep && isLastStep)
CustomOutlinedButton(
onPressed: () => context.read<RecipeCreateBloc>().add(AddStep()),
text: "Добавить шаг",
buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
),
if (isLastStep &&
!isFirstStep) // Добавляем кнопку "Добавить шаг" только для последнего шага
Column(
children: [
SizedBox(height: 16.0),
Row(
children: [
Flexible(
flex: 5,
child: CustomOutlinedButton(
onPressed: () =>
context.read<RecipeCreateBloc>().add(AddStep()),
text: "Добавить шаг",
buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
),
),
SizedBox(width: 8), // Add some spacing between the buttons
Flexible(
flex: 1,
child: CustomOutlinedButton(
text: "х",
onPressed: () =>
context.read<RecipeCreateBloc>().add(RemoveStep(i)),
buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
),
),
],
),
],
),
if (!isLastStep && !isFirstStep)
CustomOutlinedButton(
onPressed: () =>
context.read<RecipeCreateBloc>().add(RemoveStep(i)),
text: "x",
buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
),
],
),
);
}
_buildAdditional(BuildContext context, RecipeCreateLoadedState state) {
return Container(
margin: EdgeInsets.only(
left: 16.h,
right: 16.h,
bottom: 10.h,
),
padding: EdgeInsets.all(12.h),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.all(Radius.circular(12)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 5,
offset: Offset(0, 3),
),
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Align(alignment: Alignment.centerLeft, child: Text("Теги")),
CustomTextFormField(
controller: state.tags,
hintText: "Введите теги, через запятую",
fillColor: appTheme.gray50,
borderDecoration: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.h),
borderSide: BorderSide(
color: appTheme.gray50,
width: 1,
),
),
),
SizedBox(height: 8.0),
Align(
alignment: Alignment.centerLeft,
child: Text("Ссылка на видео (необязательно)")),
CustomTextFormField(
controller: state.video_url,
hintText: "YouTube",
fillColor: appTheme.gray50,
borderDecoration: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.h),
borderSide: BorderSide(
color: appTheme.gray50,
width: 1,
),
),
),
SizedBox(height: 16.0),
CustomOutlinedButton(
text: "Добавить рецепт",
buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
),
],
),
);
}
Function onTapBack(BuildContext context) {
return () {
onTapArrowLeft(context);
};
}
onTapArrowLeft(BuildContext context) {
GoRouter.of(context).pop();
}
}