feat(app): Recipe layouts

This commit is contained in:
2024-06-05 16:20:14 +03:00
parent f4b331f280
commit 6947b9bea0
14 changed files with 1574 additions and 374 deletions

View File

@@ -16,6 +16,9 @@ class RecipeEditBloc extends Bloc<RecipeEditEvent, RecipeEditState> {
RecipeEditBloc(RecipeEditState initialState) : super(initialState) {
on<RecipeEditInitialEvent>(_onInitialize);
on<EditRecipe>(_editRecipe);
on<AddStep>(_addStep);
on<RemoveStep>(_removeStep);
on<ReloadScreen>(_reloadScreen);
}
_onInitialize(
@@ -44,16 +47,44 @@ class RecipeEditBloc extends Bloc<RecipeEditEvent, RecipeEditState> {
var currentState = state as RecipeEditLoadedState;
emit(currentState.copyWith(
recipeModelObj: currentState.recipeModelObj,
recipe: currentState.recipe,
title: currentState.title,
token: currentState.token,
recipe: currentState.recipe,
description: currentState.description,
video_url: currentState.video_url));
video_url: currentState.video_url,
steps: currentState.steps,
stepDescriptions: currentState.stepDescriptions,
tags: currentState.tags));
} else {
final Map<String, dynamic> defaultStep = {
'description': '',
'image': '',
};
List<dynamic> steps = data['steps'];
List<TextEditingController> stepDescriptions = [];
if (data['steps'] == null) {
stepDescriptions.add(TextEditingController());
data['steps'].add(defaultStep);
} else {
for (var step in steps) {
stepDescriptions
.add(TextEditingController(text: step['description']));
}
}
emit(RecipeEditLoadedState(
recipe: data,
title: TextEditingController(text: data['title']),
description: TextEditingController(text: data['description']),
video_url: TextEditingController(text: data['video_url'])));
token: token,
recipe: data,
title: TextEditingController(text: data['title']),
description: TextEditingController(text: data['description']),
video_url: TextEditingController(text: data['video_url']),
tagsController: TextEditingController(),
tags: await _fetchTags(data['id']),
stepDescriptions: stepDescriptions,
steps: steps,
));
}
} else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку
@@ -92,6 +123,42 @@ class RecipeEditBloc extends Bloc<RecipeEditEvent, RecipeEditState> {
}
}
FutureOr<void> _addStep(AddStep event, Emitter<RecipeEditState> emit) async {
if (state is RecipeEditLoadedState) {
var currentState = state as RecipeEditLoadedState;
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<RecipeEditState> emit) async {
if (state is RecipeEditLoadedState) {
var currentState = state as RecipeEditLoadedState;
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<http.Response> sendRecipe(
Map<String, dynamic>? recipe,
String? title,
@@ -123,4 +190,49 @@ class RecipeEditBloc extends Bloc<RecipeEditEvent, RecipeEditState> {
return response;
}
_fetchTags(int id) async {
final box = await Hive.openBox('token');
final token = box.get('token');
if (token == null) {
NavigatorService.popAndPushNamed(
AppRoutes.authScreen,
);
}
final response = await http.get(
Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipe/getTags/$id'),
headers: {
'Authorization': 'Bearer $token',
},
);
final data = jsonDecode(response.body);
return data;
}
FutureOr<void> _reloadScreen(
RecipeEditEvent? event, Emitter<RecipeEditState> emit) async {
print('Reloading..');
final box = await Hive.openBox('token');
final token = box.get('token');
if (token == null) {
NavigatorService.popAndPushNamed(
AppRoutes.authScreen,
);
}
if (state is RecipeEditLoadedState) {
var currentState = state as RecipeEditLoadedState;
emit(currentState.copyWith(
recipeModelObj: currentState.recipeModelObj,
recipe: currentState.recipe,
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

@@ -19,3 +19,22 @@ class EditRecipe extends RecipeEditEvent {
@override
List<Object?> get props => [];
}
class AddStep extends RecipeEditEvent {
AddStep();
@override
List<Object?> get props => [];
}
class RemoveStep extends RecipeEditEvent {
RemoveStep(this.id);
final int id;
@override
List<Object?> get props => [id];
}
class ReloadScreen extends RecipeEditEvent {
ReloadScreen();
@override
List<Object?> get props => [];
}

View File

@@ -24,32 +24,52 @@ class RecipeEditState extends Equatable {
class RecipeEditLoadedState extends RecipeEditState {
RecipeEditLoadedState(
{this.recipeModelObj,
this.token,
this.recipe,
this.title,
this.description,
this.video_url});
this.video_url,
this.tagsController,
this.stepDescriptions,
this.tags,
this.steps});
RecipeEditModel? recipeModelObj;
Map<String, dynamic>? recipe;
String? token;
TextEditingController? title;
TextEditingController? description;
TextEditingController? video_url;
TextEditingController? tagsController;
List<dynamic>? steps;
List<dynamic>? tags;
List<TextEditingController>? stepDescriptions;
@override
List<Object?> get props =>
[recipeModelObj, recipe, title, description, video_url];
RecipeEditLoadedState copyWith({
RecipeEditModel? recipeModelObj,
Map<String, dynamic>? recipe,
String? token,
TextEditingController? title,
TextEditingController? description,
TextEditingController? video_url,
TextEditingController? tagsController,
List<dynamic>? steps,
List<dynamic>? tags,
List<TextEditingController>? stepDescriptions,
}) {
return RecipeEditLoadedState(
recipeModelObj: recipeModelObj ?? this.recipeModelObj,
token: token ?? this.token,
recipe: recipe ?? this.recipe,
title: title ?? this.title,
description: description ?? this.description,
video_url: video_url ?? this.video_url,
tagsController: tagsController ?? this.tagsController,
steps: steps ?? this.steps,
tags: tags ?? this.tags,
stepDescriptions: stepDescriptions ?? this.stepDescriptions,
);
}
}

View File

@@ -1,17 +1,23 @@
import 'bloc/recipe_edit_bloc.dart';
import 'models/recipe_edit_model.dart';
import 'package:eatvio_app/core/app_export.dart';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:eatvio_app/core/app_export.dart';
import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart';
import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart';
import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart';
import 'package:eatvio_app/widgets/custom_text_form_field.dart';
import 'package:eatvio_app/widgets/custom_outlined_button.dart';
class RecipeEditScreen extends StatelessWidget {
const RecipeEditScreen({Key? key}) : super(key: key);
static Widget builder(BuildContext context) {
final recipeID = ModalRoute.of(context)!.settings.arguments;
return BlocProvider<RecipeEditBloc>(
create: (context) => RecipeEditBloc(RecipeEditState(recipeModelObj: RecipeEditModel(recipeID: recipeID.toString())))..add(RecipeEditInitialEvent()),
create: (context) => RecipeEditBloc(RecipeEditState(
recipeModelObj: RecipeEditModel(recipeID: recipeID.toString())))
..add(RecipeEditInitialEvent()),
child: RecipeEditScreen());
}
@@ -39,78 +45,385 @@ class RecipeEditScreen extends StatelessWidget {
_buildRecipeEdit(BuildContext context, RecipeEditLoadedState state) {
mediaQueryData = MediaQuery.of(context);
return SafeArea(
child: Scaffold(
resizeToAvoidBottomInset: false,
body: Container(
width: double.maxFinite,
decoration: AppDecoration.fillGray,
child: ListView(
children: [
SizedBox(height: 30.v),
Container(
margin: EdgeInsets.only(
left: 16.h,
right: 20.h,
bottom: 10.h,
),
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),
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: SafeArea(
child: Scaffold(
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,
),
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CachedNetworkImage(
imageUrl: dotenv.env['STORAGE_URL']! + (state.recipe?['image'] ?? ''),
imageBuilder: (context, imageProvider) => CircleAvatar(
backgroundImage: imageProvider,
radius: 25,
),
placeholder: (context, url) => CircularProgressIndicator(),
errorWidget: (context, url, error) => CircleAvatar(
child: Icon(Icons.person),
backgroundColor: Colors.white,
radius: 25,
),
),
SizedBox(height: 16.0),
TextFormField(
controller: state.title,
decoration: InputDecoration(labelText: 'Заголовок'),
),
SizedBox(height: 16.0),
TextFormField(
controller: state.description,
decoration: InputDecoration(labelText: 'Описание'),
),
SizedBox(height: 16.0),
TextFormField(
controller: state.video_url,
decoration: InputDecoration(labelText: 'Ссылка'),
),
SizedBox(height: 16.0),
// Здесь нужно добавить виджет для загрузки картинки
ElevatedButton(
onPressed: () => context.read<RecipeEditBloc>().add(EditRecipe()),
child: Text('Сохранить'),
)
],
),
)
],
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(RecipeEditLoadedState 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("Изображение")),
if (state.recipe?['image'] != null)
CachedNetworkImage(
imageUrl: dotenv.env['STORAGE_URL']! + (state.recipe?['image']),
width: double
.infinity, // Установите ширину равной ширине родительского элемента
height: 200.0,
fit: BoxFit.cover,
placeholder: (context, url) => CircularProgressIndicator(),
errorWidget: (context, url, error) => Icon(Icons.error),
)
else
_buildAddPhoto(context, state),
SizedBox(height: 16.0),
Align(alignment: Alignment.centerLeft, child: Text("Название рецепта")),
CustomTextFormField(
controller: state.title,
hintText: "Введите название рецепта",
fillColor: appTheme.gray50,
borderDecoration: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.h),
borderSide: BorderSide(
color: appTheme.gray50,
width: 1,
),
),
),
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<RecipeEditBloc>().add(ReloadScreen());
};
}
_buildAddPhoto(BuildContext context, RecipeEditLoadedState 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, RecipeEditLoadedState 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),
if (state.steps?[i]['image'] != null)
CachedNetworkImage(
imageUrl: dotenv.env['STORAGE_URL']! + (state.steps?[i]['image']),
width: double
.infinity, // Установите ширину равной ширине родительского элемента
height: 200.0, // Задайте постоянную высоту элемента
fit: BoxFit.cover,
placeholder: (context, url) => CircularProgressIndicator(),
errorWidget: (context, url, error) => Icon(Icons.error),
)
else
_buildAddPhoto(context, state),
SizedBox(height: 16.0),
if (isFirstStep && isLastStep)
CustomOutlinedButton(
onPressed: () => context.read<RecipeEditBloc>().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<RecipeEditBloc>().add(AddStep()),
text: "Добавить шаг",
buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
),
),
SizedBox(width: 8), // Add some spacing between the buttons
Flexible(
flex: 1,
child: CustomOutlinedButton(
text: "х",
onPressed: () =>
context.read<RecipeEditBloc>().add(RemoveStep(i)),
buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
),
),
],
),
],
),
if (!isLastStep && !isFirstStep)
CustomOutlinedButton(
onPressed: () => context.read<RecipeEditBloc>().add(RemoveStep(i)),
text: "x",
buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
),
]),
);
}
_buildAdditional(BuildContext context, RecipeEditLoadedState 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("Теги")),
_buildEditableTags(state.tags),
SizedBox(height: 8.0),
Align(
alignment: Alignment.centerLeft,
child: Text("Ссылка на видео (необязательно)")),
CustomTextFormField(
controller: state.video_url,
hintText: "YouTube",
fillColor: appTheme.gray50,
borderDecoration: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.h),
borderSide: BorderSide(
color: appTheme.gray50,
width: 1,
),
),
),
SizedBox(height: 16.0),
CustomOutlinedButton(
text: "Добавить рецепт",
buttonStyle: CustomButtonStyles.outlinePrimaryTL15,
),
]),
);
}
_buildEditableTags(List<dynamic>? tags) {
String initialText = tags!.map((tag) => tag['name']).join(', ');
return CustomTextFormField(
initialValue: initialText,
fillColor: appTheme.gray50,
borderDecoration: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.h),
borderSide: BorderSide(
color: appTheme.gray50,
width: 1,
),
),
onChanged: _trimTags,
);
}
void _trimTags(newValue) {
List<String> newTagNames =
newValue!.split(',').map((tag) => tag.trim()).toList();
List<Map<String, dynamic>> newTags =
newTagNames.map((tagName) => {'name': tagName}).toList();
print(newTags);
}
Function onTapBack(BuildContext context) {
return () {
onTapArrowLeft(context);
};
}
onTapArrowLeft(BuildContext context) {
NavigatorService.goBack();
}
}