feat(app): Feed, recipe, blog posts, diet and plan show and index pages, state management, API implementation and layouts

This commit is contained in:
2024-05-08 14:11:18 +03:00
parent 404b22e78a
commit 76a29ebf67
45 changed files with 2759 additions and 21 deletions

View File

@@ -0,0 +1,70 @@
//import 'package:eatvio_app/presentation/auth/auth_screen/auth_screen.dart';
import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import '/core/app_export.dart';
import 'package:eatvio_app/presentation/recipe/recipe_select_screen/models/recipe_select_model.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:hive/hive.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:image_picker/image_picker.dart';
part 'recipe_select_event.dart';
part 'recipe_select_state.dart';
/// A bloc that manages the state of a RecipeSelect according to the event that is dispatched to it.
class RecipeSelectBloc extends Bloc<RecipeSelectEvent, RecipeSelectState> {
RecipeSelectBloc(RecipeSelectState initialState) : super(initialState) {
on<RecipeSelectInitialEvent>(_onInitialize);
}
Future<void> _onInitialize(
RecipeSelectInitialEvent event,
Emitter<RecipeSelectState> emit,
) async {
try {
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/index'),
);
print('Got response');
if (response.statusCode == 200) {
print('Got 200');
final data = jsonDecode(response.body);
if (data is List<dynamic>) {
print('Got List');
if (state is RecipeSelectLoadedState) {
print('Got loaded');
var currentState = state as RecipeSelectLoadedState;
emit((currentState).copyWith(
posts: data,
myProfileModelObj: currentState.myProfileModelObj,
));
} else {
print('Got unloaded');
emit(RecipeSelectLoadedState(
posts: data,
));
}
} else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку
emit(RecipeSelectErrorState('Неверный формат ответа API.'));
}
} else {
// Статус ответа не равен 200, обрабатываем ошибку
emit(RecipeSelectErrorState('Ошибка сервера: ${response.statusCode}'));
}
} catch (e) {
// Ошибка при декодировании JSON или другая ошибка выполнения
emit(RecipeSelectErrorState('Ошибка при получении данных ленты: $e'));
}
}
}

View File

@@ -0,0 +1,23 @@
// ignore_for_file: must_be_immutable
part of 'recipe_select_bloc.dart';
/// Abstract class for all events that can be dispatched from the
///RecipeSelect widget.
///
/// Events must be immutable and implement the [Equatable] interface.
@immutable
abstract class RecipeSelectEvent extends Equatable {}
/// Event that is dispatched when the RecipeSelect widget is first created.
class RecipeSelectInitialEvent extends RecipeSelectEvent {
@override
List<Object?> get props => [];
}
class UploadAvatar extends RecipeSelectEvent {
UploadAvatar(this.image);
final XFile image;
@override
List<Object> get props => [image];
}

View File

@@ -0,0 +1,49 @@
// ignore_for_file: must_be_immutable
part of 'recipe_select_bloc.dart';
class RecipeSelectState extends Equatable {
const RecipeSelectState({this.myProfileModelObj});
final RecipeSelectModel? myProfileModelObj;
@override
List<Object?> get props => [myProfileModelObj];
}
class RecipeSelectInitialState extends RecipeSelectState {
RecipeSelectInitialState({required RecipeSelectModel myProfileModelObj})
: super(myProfileModelObj: myProfileModelObj);
}
/// Represents the state of RecipeSelect in the application.
class RecipeSelectLoadedState extends RecipeSelectState {
RecipeSelectLoadedState({this.myProfileModelObj, this.posts})
: super(myProfileModelObj: null);
RecipeSelectModel? myProfileModelObj;
List<dynamic>? posts;
@override
List<Object?> get props => [
myProfileModelObj,
posts,
];
RecipeSelectLoadedState copyWith({
RecipeSelectModel? myProfileModelObj,
List<dynamic>? posts,
}) {
return RecipeSelectLoadedState(
myProfileModelObj: myProfileModelObj ?? this.myProfileModelObj,
posts: posts ?? this.posts,
);
}
}
class RecipeSelectErrorState extends RecipeSelectState {
final String errorMessage;
const RecipeSelectErrorState(this.errorMessage);
@override
List<Object> get props => [errorMessage];
}

View File

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

View File

@@ -0,0 +1,169 @@
import 'bloc/recipe_select_bloc.dart';
import 'models/recipe_select_model.dart';
import 'package:eatvio_app/core/app_export.dart';
import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart';
import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart';
import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart';
import 'package:eatvio_app/widgets/custom_bottom_bar.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter/material.dart';
class RecipeSelectScreen extends StatelessWidget {
static Widget builder(BuildContext context) {
return BlocProvider<RecipeSelectBloc>(
create: (context) => RecipeSelectBloc(
RecipeSelectState(myProfileModelObj: RecipeSelectModel()))
..add(RecipeSelectInitialEvent()),
child: RecipeSelectScreen());
}
Widget build(BuildContext context) {
return BlocBuilder<RecipeSelectBloc, RecipeSelectState>(
builder: (context, state) {
if (state is RecipeSelectInitialState) {
// Это начальное состояние, данные ещё не загружены.
return CircularProgressIndicator(
color: Colors.white,
backgroundColor: Colors.white,
);
} else if (state is RecipeSelectLoadedState) {
// Данные загружены, можно строить экран.
return _buildSetingsScreen(context, state);
} else {
// Другие состояния, если они есть.
return Container(); // Пустой контейнер для необработанных состояний.
}
},
);
}
_buildSetingsScreen(BuildContext context, RecipeSelectLoadedState state) {
mediaQueryData = MediaQuery.of(context);
print(state.posts);
return SafeArea(
child: Scaffold(
backgroundColor: Colors.grey[200],
resizeToAvoidBottomInset: true,
body: SingleChildScrollView(
child: Container(
width: double.maxFinite,
decoration: BoxDecoration(color: Colors.grey[200]),
child: Padding(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(height: 10),
Container(
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: Padding(
padding: EdgeInsets.only(left: 20.h),
child: Row(
children: [
AppbarSubtitle(
text: "Рецепты",
margin: EdgeInsets.only(
left: 80.h, top: 12.v, bottom: 9.v),
),
],
),
),
),
),
SizedBox(height: 20),
ListView.builder(
shrinkWrap: true, // Add this line
itemCount: state.posts?.length ?? 0,
itemBuilder: (context, index) {
final post = state.posts?[index];
return Container(
margin: EdgeInsets.only(bottom: 10),
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: ListTile(
leading: CachedNetworkImage(
imageUrl:
dotenv.env['STORAGE_URL']! + post['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,
),
),
title: Text(
post?['title'] ?? '',
style: CustomTextStyles.titleMediumSemiBold,
),
subtitle: Text(post?['description'] ?? ''),
onTap: () => Navigator.pushNamed(
context,
AppRoutes.recipeScreen,
arguments: post?['id'].toString(),
),
));
},
),
],
),
),
),
),
bottomNavigationBar: _buildBottomBar(context),
),
);
}
Function onTapBack(BuildContext context) {
return () {
onTapArrowLeft(context);
};
}
_buildBottomBar(BuildContext context) {
return CustomBottomBar(onChanged: (BottomBarEnum type) {});
}
onTapArrowLeft(BuildContext context) {
NavigatorService.goBack();
}
}

View File

@@ -0,0 +1,62 @@
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:hive/hive.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import '/core/app_export.dart';
import 'package:eatvio_app/presentation/recipe/recipe_show_screen/models/recipe_show_model.dart';
part 'recipe_show_event.dart';
part 'recipe_show_state.dart';
/// A bloc that manages the state of a Recipe according to the event that is dispatched to it.
class RecipeBloc extends Bloc<RecipeEvent, RecipeState> {
RecipeBloc(RecipeState initialState) : super(initialState) {
on<RecipeInitialEvent>(_onInitialize);
}
_onInitialize(
RecipeInitialEvent event,
Emitter<RecipeState> emit,
) async {
try {
final box = await Hive.openBox('token');
final token = box.get('token');
if (token == null) {
NavigatorService.popAndPushNamed(
AppRoutes.authScreen,
);
}
final String? recipeID = state.recipeModelObj?.recipeID;
final response = await http.get(
Uri.parse(dotenv.env['SERVER_ROOT']! + '/recipe/show/$recipeID'),
headers: {
'Authorization': 'Bearer $token',
},
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
if (data is Map<String, dynamic>) {
if (state is RecipeLoadedState) {
var currentState = state as RecipeLoadedState;
emit(currentState.copyWith(
recipeModelObj: currentState.recipeModelObj,
recipe: currentState.recipe));
} else {
emit(RecipeLoadedState(recipe: data));
print(data);
}
} else {
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку
emit(RecipeErrorState('Некоторые необходимые данные отсутствуют.'));
}
} else {
// Статус ответа не равен 200, обрабатываем ошибку
emit(RecipeErrorState('Ошибка сервера: ${response.statusCode}'));
}
} catch (e) {
// Ошибка при декодировании JSON или другая ошибка выполнения
emit(RecipeErrorState('Ошибка при получении данных о чатах: $e'));
}
}
}

View File

@@ -0,0 +1,16 @@
// ignore_for_file: must_be_immutable
part of 'recipe_show_bloc.dart';
/// Abstract class for all events that can be dispatched from the
///Recipe widget.
///
/// Events must be immutable and implement the [Equatable] interface.
@immutable
abstract class RecipeEvent extends Equatable {}
/// Event that is dispatched when the Recipe widget is first created.
class RecipeInitialEvent extends RecipeEvent {
@override
List<Object?> get props => [];
}

View File

@@ -0,0 +1,52 @@
// ignore_for_file: must_be_immutable
part of 'recipe_show_bloc.dart';
/// Represents the state of Recipe in the application.
///
class RecipeState extends Equatable {
RecipeState({
this.recipeModelObj,
});
RecipeModel? recipeModelObj;
@override
List<Object?> get props => [recipeModelObj];
RecipeState copyWith({RecipeModel? recipeModelObj}) {
return RecipeState(
recipeModelObj: recipeModelObj ?? this.recipeModelObj,
);
}
}
class RecipeLoadedState extends RecipeState {
RecipeLoadedState({this.recipeModelObj, this.recipe});
RecipeModel? recipeModelObj;
Map<String, dynamic>? recipe;
@override
List<Object?> get props => [recipeModelObj, recipe];
RecipeLoadedState copyWith(
{RecipeModel? recipeModelObj, Map<String, dynamic>? recipe}) {
return RecipeLoadedState(
recipeModelObj: recipeModelObj ?? this.recipeModelObj,
recipe: recipe ?? this.recipe,
);
}
}
class RecipeErrorState extends RecipeState {
final String errorMessage;
RecipeErrorState(this.errorMessage);
@override
List<Object> get props => [errorMessage];
}
class RecipeInitialState extends RecipeState {
RecipeInitialState({required RecipeModel recipeModelObj})
: super(recipeModelObj: recipeModelObj);
}

View File

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

View File

@@ -0,0 +1,199 @@
import 'bloc/recipe_show_bloc.dart';
import 'models/recipe_show_model.dart';
import 'package:eatvio_app/core/app_export.dart';
import 'package:flutter/material.dart';
import 'package:eatvio_app/widgets/app_bar/custom_app_bar.dart';
import 'package:eatvio_app/widgets/app_bar/appbar_subtitle.dart';
import 'package:eatvio_app/widgets/app_bar/appbar_leading_image.dart';
import 'package:eatvio_app/widgets/app_bar/appbar_title_image.dart';
import 'package:eatvio_app/widgets/custom_bottom_bar.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
class RecipeScreen extends StatelessWidget {
const RecipeScreen({Key? key}) : super(key: key);
static Widget builder(BuildContext context) {
final recipeID = ModalRoute.of(context)!.settings.arguments;
return BlocProvider<RecipeBloc>(
create: (context) => RecipeBloc(RecipeState(
recipeModelObj: RecipeModel(recipeID: recipeID.toString())))
..add(RecipeInitialEvent()),
child: RecipeScreen());
}
Widget build(BuildContext context) {
return BlocBuilder<RecipeBloc, RecipeState>(
builder: (context, state) {
if (state is RecipeInitialState) {
// Это начальное состояние, данные ещё не загружены.
return Container(
color: Colors.white,
);
} else if (state is RecipeLoadedState) {
// Данные загружены, можно строить экран.
return _buildRecipe(context, state);
} else if (state is RecipeErrorState) {
// Произошла ошибка при загрузке данных.
return Center(child: Text(state.errorMessage));
} else {
// Другие состояния, если они есть.
return Container(); // Пустой контейнер для необработанных состояний.
}
},
);
}
_buildRecipe(BuildContext context, RecipeLoadedState state) {
print(state.recipe);
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),
),
],
),
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),
Text(state.recipe?['title'],
style: CustomTextStyles.titleMediumBlack),
SizedBox(height: 8.0),
Text(
state.recipe?['description'],
),
SizedBox(height: 16.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
onPressed: () {
// Действие для редактирования
},
child: Text('Редактировать'),
),
ElevatedButton(
onPressed: () {
// Действие для удаления
},
child: Text('Удалить'),
),
],
)
]),
)
],
),
),
bottomNavigationBar: _buildBottomBar(context)));
}
/// Section Widget
_buildAppbar(BuildContext context) {
return CustomAppBar(
leadingWidth: 26.h,
leading: AppbarLeadingImage(
imagePath: ImageConstant.imgArrowLeft,
margin: EdgeInsets.only(
left: 16.h,
top: 18.v,
bottom: 25.v,
),
onTap: () => onTapArrowleftone(context),
),
title: Padding(
padding: EdgeInsets.only(left: 12.h),
child: Row(
children: [
AppbarTitleImage(
imagePath: ImageConstant.imgIconMoreHorizontal,
margin: EdgeInsets.only(bottom: 3.v),
),
Padding(
padding: EdgeInsets.only(
left: 12.h,
top: 2.v,
),
child: Column(
children: [
AppbarSubtitle(
text: "Валерий Леонтьев",
),
SizedBox(height: 3.v),
Text("Был в сети вчера", style: theme.textTheme.bodySmall!)
],
),
)
],
),
),
);
}
///Handling route based on bottom click actions
String getCurrentRoute(BottomBarEnum type) {
switch (type) {
case BottomBarEnum.tf:
return AppRoutes.recipeScreen;
default:
return "/";
}
}
///Handling page based on route
Widget getCurrentPage(
BuildContext context,
String currentRoute,
) {
switch (currentRoute) {
case AppRoutes.recipeScreen:
return RecipeScreen.builder(context);
default:
return RecipeScreen();
}
}
_buildBottomBar(BuildContext context) {
return CustomBottomBar(onChanged: (BottomBarEnum type) {});
}
/// Navigates to the previous screen.
onTapArrowleftone(BuildContext context) {
NavigatorService.goBack();
}
}