forked from eatvio/eatvio_app
feat(diets) Diets create and edit API connect, TextController management and redirect
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -0,0 +1,21 @@
|
||||
// ignore_for_file: must_be_immutable
|
||||
|
||||
part of 'diet_create_bloc.dart';
|
||||
|
||||
/// Abstract class for all events that can be dispatched from the
|
||||
///DietCreate widget.
|
||||
///
|
||||
/// Events must be immutable and implement the [Equatable] interface.
|
||||
@immutable
|
||||
abstract class DietCreateEvent extends Equatable {}
|
||||
|
||||
/// Event that is dispatched when the DietCreate widget is first created.
|
||||
class DietCreateInitialEvent extends DietCreateEvent {
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
class CreateDiet extends DietCreateEvent {
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// ignore_for_file: must_be_immutable
|
||||
|
||||
part of 'diet_create_bloc.dart';
|
||||
|
||||
/// Represents the state of DietCreate in the application.
|
||||
///
|
||||
|
||||
class DietCreateState extends Equatable {
|
||||
DietCreateState({
|
||||
this.dietModelObj,
|
||||
});
|
||||
|
||||
DietCreateModel? dietModelObj;
|
||||
|
||||
@override
|
||||
List<Object?> get props => [dietModelObj];
|
||||
DietCreateState copyWith({DietCreateModel? dietModelObj}) {
|
||||
return DietCreateState(
|
||||
dietModelObj: dietModelObj ?? this.dietModelObj,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class DietCreateLoadedState extends DietCreateState {
|
||||
DietCreateLoadedState({
|
||||
this.dietModelObj,
|
||||
this.name,
|
||||
this.details,
|
||||
});
|
||||
|
||||
DietCreateModel? dietModelObj;
|
||||
TextEditingController? name;
|
||||
TextEditingController? details;
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
dietModelObj,
|
||||
name,
|
||||
details,
|
||||
];
|
||||
DietCreateLoadedState copyWith({
|
||||
DietCreateModel? dietModelObj,
|
||||
TextEditingController? name,
|
||||
TextEditingController? details,
|
||||
}) {
|
||||
return DietCreateLoadedState(
|
||||
dietModelObj: dietModelObj ?? this.dietModelObj,
|
||||
name: name ?? this.name,
|
||||
details: details ?? this.details,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class DietCreateErrorState extends DietCreateState {
|
||||
final String errorMessage;
|
||||
|
||||
DietCreateErrorState(this.errorMessage);
|
||||
|
||||
@override
|
||||
List<Object> get props => [errorMessage];
|
||||
}
|
||||
|
||||
class DietCreateInitialState extends DietCreateState {
|
||||
DietCreateInitialState({required DietCreateModel dietModelObj})
|
||||
: super(dietModelObj: dietModelObj);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'bloc/diet_create_bloc.dart';
|
||||
import 'models/diet_create_model.dart';
|
||||
import 'package:eatvio_app/core/app_export.dart';
|
||||
import 'package:flutter/material.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 DietCreateScreen extends StatelessWidget {
|
||||
const DietCreateScreen({Key? key}) : super(key: key);
|
||||
static Widget builder(BuildContext context) {
|
||||
final dietID = ModalRoute.of(context)!.settings.arguments;
|
||||
return BlocProvider<DietCreateBloc>(
|
||||
create: (context) => DietCreateBloc(DietCreateState(
|
||||
dietModelObj: DietCreateModel(dietID: dietID.toString())))
|
||||
..add(DietCreateInitialEvent()),
|
||||
child: DietCreateScreen());
|
||||
}
|
||||
|
||||
Widget build(BuildContext context) {
|
||||
return BlocBuilder<DietCreateBloc, DietCreateState>(
|
||||
builder: (context, state) {
|
||||
if (state is DietCreateInitialState) {
|
||||
// Это начальное состояние, данные ещё не загружены.
|
||||
return Container(
|
||||
color: Colors.white,
|
||||
);
|
||||
} else if (state is DietCreateLoadedState) {
|
||||
// Данные загружены, можно строить экран.
|
||||
return _buildDietCreate(context, state);
|
||||
} else if (state is DietCreateErrorState) {
|
||||
// Произошла ошибка при загрузке данных.
|
||||
return Center(child: Text(state.errorMessage));
|
||||
} else {
|
||||
// Другие состояния, если они есть.
|
||||
return Container(); // Пустой контейнер для необработанных состояний.
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
_buildDietCreate(BuildContext context, DietCreateLoadedState 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),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
SizedBox(height: 16.0),
|
||||
TextFormField(
|
||||
controller: state.name,
|
||||
decoration: InputDecoration(labelText: 'Заголовок'),
|
||||
),
|
||||
SizedBox(height: 16.0),
|
||||
TextFormField(
|
||||
controller: state.details,
|
||||
decoration: InputDecoration(labelText: 'Описание'),
|
||||
),
|
||||
SizedBox(height: 16.0),
|
||||
// Здесь нужно добавить виджет для загрузки картинки
|
||||
ElevatedButton(
|
||||
onPressed: () =>
|
||||
context.read<DietCreateBloc>().add(CreateDiet()),
|
||||
child: Text('Создать'),
|
||||
)
|
||||
]),
|
||||
)
|
||||
]),
|
||||
),
|
||||
bottomNavigationBar: _buildBottomBar(context)));
|
||||
}
|
||||
}
|
||||
|
||||
_buildBottomBar(BuildContext context) {
|
||||
return CustomBottomBar(onChanged: (BottomBarEnum type) {});
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// ignore_for_file: must_be_immutable
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
/// This class defines the variables used in the [diet_create_screen],
|
||||
/// and is typically used to hold data that is passed between different parts of the application.
|
||||
|
||||
class DietCreateModel extends Equatable {
|
||||
final String dietID;
|
||||
|
||||
DietCreateModel({required String dietID}) : dietID = dietID;
|
||||
|
||||
DietCreateModel copyWith(String dietID) {
|
||||
return DietCreateModel(dietID: dietID);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [dietID];
|
||||
}
|
||||
117
lib/presentation/diets/diet_edit_screen/bloc/diet_edit_bloc.dart
Normal file
117
lib/presentation/diets/diet_edit_screen/bloc/diet_edit_bloc.dart
Normal file
@@ -0,0 +1,117 @@
|
||||
import 'dart:async';
|
||||
|
||||
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/diets/diet_edit_screen/models/diet_edit_model.dart';
|
||||
part 'diet_edit_event.dart';
|
||||
part 'diet_edit_state.dart';
|
||||
|
||||
/// A bloc that manages the state of a DietEdit according to the event that is dispatched to it.
|
||||
class DietEditBloc extends Bloc<DietEditEvent, DietEditState> {
|
||||
DietEditBloc(DietEditState initialState) : super(initialState) {
|
||||
on<DietEditInitialEvent>(_onInitialize);
|
||||
on<EditDiet>(_editDiet);
|
||||
}
|
||||
|
||||
_onInitialize(
|
||||
DietEditInitialEvent event,
|
||||
Emitter<DietEditState> emit,
|
||||
) async {
|
||||
try {
|
||||
final box = await Hive.openBox('token');
|
||||
final token = box.get('token');
|
||||
if (token == null) {
|
||||
NavigatorService.popAndPushNamed(
|
||||
AppRoutes.authScreen,
|
||||
);
|
||||
}
|
||||
final String? dietID = state.dietModelObj?.dietID;
|
||||
final response = await http.get(
|
||||
Uri.parse(dotenv.env['SERVER_ROOT']! + '/diets/show/$dietID'),
|
||||
headers: {
|
||||
'Authorization': 'Bearer $token',
|
||||
},
|
||||
);
|
||||
if (response.statusCode == 200) {
|
||||
final data = jsonDecode(response.body);
|
||||
if (data is Map<String, dynamic>) {
|
||||
if (state is DietEditLoadedState) {
|
||||
var currentState = state as DietEditLoadedState;
|
||||
emit(currentState.copyWith(
|
||||
dietModelObj: currentState.dietModelObj,
|
||||
diet: currentState.diet,
|
||||
name: currentState.name,
|
||||
duration: currentState.duration,
|
||||
details: currentState.details));
|
||||
} else {
|
||||
emit(DietEditLoadedState(
|
||||
diet: data,
|
||||
name: TextEditingController(text: data['name']),
|
||||
details: TextEditingController(text: data['details']),
|
||||
duration: TextEditingController(text: data['duration'])));
|
||||
}
|
||||
} else {
|
||||
// Один или несколько ключевых полей отсутствуют, обрабатываем ошибку
|
||||
emit(DietEditErrorState('Некоторые необходимые данные отсутствуют.'));
|
||||
}
|
||||
} else {
|
||||
// Статус ответа не равен 200, обрабатываем ошибку
|
||||
emit(DietEditErrorState('Ошибка сервера: ${response.statusCode}'));
|
||||
}
|
||||
} catch (e) {
|
||||
// Ошибка при декодировании JSON или другая ошибка выполнения
|
||||
emit(DietEditErrorState('Ошибка при получении данных о чатах: $e'));
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<void> _editDiet(EditDiet event, Emitter<DietEditState> emit) async {
|
||||
if (state is DietEditLoadedState) {
|
||||
var currentState = state as DietEditLoadedState;
|
||||
int duration = int.parse(currentState.duration!.text) * 7;
|
||||
print(duration);
|
||||
var response = await sendDiet(currentState.diet, currentState.name?.text,
|
||||
currentState.details?.text, duration.toString());
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
NavigatorService.pushNamed(AppRoutes.dietScreen,
|
||||
arguments: currentState.diet?['id'].toString());
|
||||
} else {
|
||||
print(
|
||||
'Failed to edit blog post. Status Code: ${response.statusCode} ${response.body}');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<http.Response> sendDiet(
|
||||
Map<String, dynamic>? diet,
|
||||
String? name,
|
||||
String? details,
|
||||
String? duration,
|
||||
) async {
|
||||
int id = diet?['id'];
|
||||
String url = '${dotenv.env['SERVER_ROOT']!}/diets/update/$id';
|
||||
|
||||
final Map<String, dynamic> credentials = {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'details': details,
|
||||
'duration': '14',
|
||||
};
|
||||
|
||||
var response = await http.post(
|
||||
Uri.parse(url),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: json.encode(credentials),
|
||||
encoding: utf8,
|
||||
);
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// ignore_for_file: must_be_immutable
|
||||
|
||||
part of 'diet_edit_bloc.dart';
|
||||
|
||||
/// Abstract class for all events that can be dispatched from the
|
||||
///DietEdit widget.
|
||||
///
|
||||
/// Events must be immutable and implement the [Equatable] interface.
|
||||
@immutable
|
||||
abstract class DietEditEvent extends Equatable {}
|
||||
|
||||
/// Event that is dispatched when the DietEdit widget is first created.
|
||||
class DietEditInitialEvent extends DietEditEvent {
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
class EditDiet extends DietEditEvent {
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// ignore_for_file: must_be_immutable
|
||||
|
||||
part of 'diet_edit_bloc.dart';
|
||||
|
||||
/// Represents the state of DietEdit in the application.
|
||||
///
|
||||
|
||||
class DietEditState extends Equatable {
|
||||
DietEditState({
|
||||
this.dietModelObj,
|
||||
});
|
||||
|
||||
DietEditModel? dietModelObj;
|
||||
|
||||
@override
|
||||
List<Object?> get props => [dietModelObj];
|
||||
DietEditState copyWith({DietEditModel? dietModelObj}) {
|
||||
return DietEditState(
|
||||
dietModelObj: dietModelObj ?? this.dietModelObj,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class DietEditLoadedState extends DietEditState {
|
||||
DietEditLoadedState(
|
||||
{this.dietModelObj, this.diet, this.name, this.details, this.duration});
|
||||
|
||||
DietEditModel? dietModelObj;
|
||||
Map<String, dynamic>? diet;
|
||||
TextEditingController? name;
|
||||
TextEditingController? details;
|
||||
TextEditingController? duration;
|
||||
@override
|
||||
List<Object?> get props => [dietModelObj, diet, name, details, duration];
|
||||
DietEditLoadedState copyWith({
|
||||
DietEditModel? dietModelObj,
|
||||
Map<String, dynamic>? diet,
|
||||
TextEditingController? name,
|
||||
TextEditingController? details,
|
||||
TextEditingController? duration,
|
||||
}) {
|
||||
return DietEditLoadedState(
|
||||
dietModelObj: dietModelObj ?? this.dietModelObj,
|
||||
diet: diet ?? this.diet,
|
||||
name: name ?? this.name,
|
||||
details: details ?? this.details,
|
||||
duration: duration ?? this.duration,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class DietEditErrorState extends DietEditState {
|
||||
final String errorMessage;
|
||||
|
||||
DietEditErrorState(this.errorMessage);
|
||||
|
||||
@override
|
||||
List<Object> get props => [errorMessage];
|
||||
}
|
||||
|
||||
class DietEditInitialState extends DietEditState {
|
||||
DietEditInitialState({required DietEditModel dietModelObj})
|
||||
: super(dietModelObj: dietModelObj);
|
||||
}
|
||||
114
lib/presentation/diets/diet_edit_screen/diet_edit_screen.dart
Normal file
114
lib/presentation/diets/diet_edit_screen/diet_edit_screen.dart
Normal file
@@ -0,0 +1,114 @@
|
||||
import 'bloc/diet_edit_bloc.dart';
|
||||
import 'models/diet_edit_model.dart';
|
||||
import 'package:eatvio_app/core/app_export.dart';
|
||||
import 'package:flutter/material.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 DietEditScreen extends StatelessWidget {
|
||||
const DietEditScreen({Key? key}) : super(key: key);
|
||||
static Widget builder(BuildContext context) {
|
||||
final dietID = ModalRoute.of(context)!.settings.arguments;
|
||||
return BlocProvider<DietEditBloc>(
|
||||
create: (context) => DietEditBloc(DietEditState(
|
||||
dietModelObj: DietEditModel(dietID: dietID.toString())))
|
||||
..add(DietEditInitialEvent()),
|
||||
child: DietEditScreen());
|
||||
}
|
||||
|
||||
Widget build(BuildContext context) {
|
||||
return BlocBuilder<DietEditBloc, DietEditState>(
|
||||
builder: (context, state) {
|
||||
if (state is DietEditInitialState) {
|
||||
// Это начальное состояние, данные ещё не загружены.
|
||||
return Container(
|
||||
color: Colors.white,
|
||||
);
|
||||
} else if (state is DietEditLoadedState) {
|
||||
// Данные загружены, можно строить экран.
|
||||
return _buildDietEdit(context, state);
|
||||
} else if (state is DietEditErrorState) {
|
||||
// Произошла ошибка при загрузке данных.
|
||||
return Center(child: Text(state.errorMessage));
|
||||
} else {
|
||||
// Другие состояния, если они есть.
|
||||
return Container(); // Пустой контейнер для необработанных состояний.
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
_buildDietEdit(BuildContext context, DietEditLoadedState 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),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
CachedNetworkImage(
|
||||
imageUrl: dotenv.env['STORAGE_URL']! +
|
||||
(state.diet?['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.name,
|
||||
decoration: InputDecoration(labelText: 'Заголовок'),
|
||||
),
|
||||
SizedBox(height: 16.0),
|
||||
TextFormField(
|
||||
controller: state.details,
|
||||
decoration: InputDecoration(labelText: 'Описание'),
|
||||
),
|
||||
SizedBox(height: 16.0),
|
||||
// Здесь нужно добавить виджет для загрузки картинки
|
||||
ElevatedButton(
|
||||
onPressed: () =>
|
||||
context.read<DietEditBloc>().add(EditDiet()),
|
||||
child: Text('Сохранить'),
|
||||
)
|
||||
]),
|
||||
)
|
||||
]),
|
||||
),
|
||||
bottomNavigationBar: _buildBottomBar(context)));
|
||||
}
|
||||
}
|
||||
|
||||
_buildBottomBar(BuildContext context) {
|
||||
return CustomBottomBar(onChanged: (BottomBarEnum type) {});
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// ignore_for_file: must_be_immutable
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
/// This class defines the variables used in the [diet_edit_screen],
|
||||
/// and is typically used to hold data that is passed between different parts of the application.
|
||||
|
||||
class DietEditModel extends Equatable {
|
||||
final String dietID;
|
||||
|
||||
DietEditModel({required String dietID}) : dietID = dietID;
|
||||
|
||||
DietEditModel copyWith(String dietID) {
|
||||
return DietEditModel(dietID: dietID);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [dietID];
|
||||
}
|
||||
@@ -40,7 +40,6 @@ class DietSelectScreen extends StatelessWidget {
|
||||
|
||||
_buildSetingsScreen(BuildContext context, DietSelectLoadedState state) {
|
||||
mediaQueryData = MediaQuery.of(context);
|
||||
print(state.posts);
|
||||
return SafeArea(
|
||||
child: Scaffold(
|
||||
backgroundColor: Colors.grey[200],
|
||||
@@ -86,6 +85,16 @@ class DietSelectScreen extends StatelessWidget {
|
||||
margin: EdgeInsets.only(
|
||||
left: 80.h, top: 12.v, bottom: 9.v),
|
||||
),
|
||||
Spacer(),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 20.0),
|
||||
child: GestureDetector(
|
||||
onTap: () => Navigator.pushNamed(
|
||||
context,
|
||||
AppRoutes.dietCreateScreen,
|
||||
),
|
||||
child: Icon(Icons.create_outlined)),
|
||||
)
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -140,6 +149,13 @@ class DietSelectScreen extends StatelessWidget {
|
||||
AppRoutes.dietScreen,
|
||||
arguments: post?['id'].toString(),
|
||||
),
|
||||
trailing: GestureDetector(
|
||||
onTap: () => Navigator.pushNamed(
|
||||
context,
|
||||
AppRoutes.dietEditScreen,
|
||||
arguments: post?['id'].toString(),
|
||||
),
|
||||
child: Icon(Icons.edit)),
|
||||
));
|
||||
},
|
||||
),
|
||||
|
||||
@@ -102,9 +102,11 @@ class DietScreen extends StatelessWidget {
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
children: [
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
// Действие для редактирования
|
||||
},
|
||||
onPressed: () => Navigator.pushNamed(
|
||||
context,
|
||||
AppRoutes.dietEditScreen,
|
||||
arguments: state.diet?['id'].toString(),
|
||||
),
|
||||
child: Text('Редактировать'),
|
||||
),
|
||||
ElevatedButton(
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import 'dart:async';
|
||||
|
||||
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/feed/blog_post_create_screen/models/blog_post_create_model.dart';
|
||||
part 'blog_post_create_event.dart';
|
||||
part 'blog_post_create_state.dart';
|
||||
|
||||
/// A bloc that manages the state of a BlogPostCreate according to the event that is dispatched to it.
|
||||
class BlogPostCreateBloc
|
||||
extends Bloc<BlogPostCreateEvent, BlogPostCreateState> {
|
||||
BlogPostCreateBloc(BlogPostCreateState initialState) : super(initialState) {
|
||||
on<BlogPostCreateInitialEvent>(_onInitialize);
|
||||
on<CreateBlogPost>(_createBlogPost);
|
||||
}
|
||||
|
||||
_onInitialize(
|
||||
BlogPostCreateInitialEvent event,
|
||||
Emitter<BlogPostCreateState> emit,
|
||||
) async {
|
||||
final box = await Hive.openBox('token');
|
||||
final token = box.get('token');
|
||||
if (token == null) {
|
||||
NavigatorService.popAndPushNamed(
|
||||
AppRoutes.authScreen,
|
||||
);
|
||||
}
|
||||
if (state is BlogPostCreateLoadedState) {
|
||||
var currentState = state as BlogPostCreateLoadedState;
|
||||
emit(currentState.copyWith(
|
||||
blog_postModelObj: currentState.blog_postModelObj,
|
||||
title: currentState.title,
|
||||
description: currentState.description,
|
||||
youtube_url: currentState.youtube_url));
|
||||
} else {
|
||||
emit(BlogPostCreateLoadedState(
|
||||
title: TextEditingController(),
|
||||
description: TextEditingController(),
|
||||
youtube_url: TextEditingController()));
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<void> _createBlogPost(
|
||||
CreateBlogPost event, Emitter<BlogPostCreateState> emit) async {
|
||||
if (state is BlogPostCreateLoadedState) {
|
||||
var currentState = state as BlogPostCreateLoadedState;
|
||||
|
||||
var response = await sendBlogPost(
|
||||
currentState.title?.text,
|
||||
currentState.youtube_url?.text,
|
||||
currentState.description?.text,
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
NavigatorService.pushNamed(AppRoutes.feedScreen);
|
||||
} else {
|
||||
print(
|
||||
'Failed to create blog post. Status Code: ${response.statusCode} ${response.body}');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<http.Response> sendBlogPost(
|
||||
String? title,
|
||||
String? youtube_url,
|
||||
String? description,
|
||||
) async {
|
||||
String url = '${dotenv.env['SERVER_ROOT']!}/feed/create';
|
||||
|
||||
final Map<String, dynamic> credentials = {
|
||||
'title': title,
|
||||
'description': description,
|
||||
'youtube_url': youtube_url,
|
||||
'status': 'active',
|
||||
};
|
||||
|
||||
var response = await http.post(
|
||||
Uri.parse(url),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: json.encode(credentials),
|
||||
encoding: utf8,
|
||||
);
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// ignore_for_file: must_be_immutable
|
||||
|
||||
part of 'blog_post_create_bloc.dart';
|
||||
|
||||
/// Abstract class for all events that can be dispatched from the
|
||||
///BlogPostCreate widget.
|
||||
///
|
||||
/// Events must be immutable and implement the [Equatable] interface.
|
||||
@immutable
|
||||
abstract class BlogPostCreateEvent extends Equatable {}
|
||||
|
||||
/// Event that is dispatched when the BlogPostCreate widget is first created.
|
||||
class BlogPostCreateInitialEvent extends BlogPostCreateEvent {
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
class CreateBlogPost extends BlogPostCreateEvent {
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// ignore_for_file: must_be_immutable
|
||||
|
||||
part of 'blog_post_create_bloc.dart';
|
||||
|
||||
/// Represents the state of BlogPostCreate in the application.
|
||||
///
|
||||
|
||||
class BlogPostCreateState extends Equatable {
|
||||
BlogPostCreateState({
|
||||
this.blog_postModelObj,
|
||||
});
|
||||
|
||||
BlogPostCreateModel? blog_postModelObj;
|
||||
|
||||
@override
|
||||
List<Object?> get props => [blog_postModelObj];
|
||||
BlogPostCreateState copyWith({BlogPostCreateModel? blog_postModelObj}) {
|
||||
return BlogPostCreateState(
|
||||
blog_postModelObj: blog_postModelObj ?? this.blog_postModelObj,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class BlogPostCreateLoadedState extends BlogPostCreateState {
|
||||
BlogPostCreateLoadedState(
|
||||
{this.blog_postModelObj, this.title, this.description, this.youtube_url});
|
||||
|
||||
BlogPostCreateModel? blog_postModelObj;
|
||||
TextEditingController? title;
|
||||
TextEditingController? description;
|
||||
TextEditingController? youtube_url;
|
||||
@override
|
||||
List<Object?> get props =>
|
||||
[blog_postModelObj, title, description, youtube_url];
|
||||
BlogPostCreateLoadedState copyWith({
|
||||
BlogPostCreateModel? blog_postModelObj,
|
||||
TextEditingController? title,
|
||||
TextEditingController? description,
|
||||
TextEditingController? youtube_url,
|
||||
}) {
|
||||
return BlogPostCreateLoadedState(
|
||||
blog_postModelObj: blog_postModelObj ?? this.blog_postModelObj,
|
||||
title: title ?? this.title,
|
||||
description: description ?? this.description,
|
||||
youtube_url: youtube_url ?? this.youtube_url,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class BlogPostCreateErrorState extends BlogPostCreateState {
|
||||
final String errorMessage;
|
||||
|
||||
BlogPostCreateErrorState(this.errorMessage);
|
||||
|
||||
@override
|
||||
List<Object> get props => [errorMessage];
|
||||
}
|
||||
|
||||
class BlogPostCreateInitialState extends BlogPostCreateState {
|
||||
BlogPostCreateInitialState({required BlogPostCreateModel blog_postModelObj})
|
||||
: super(blog_postModelObj: blog_postModelObj);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import 'bloc/blog_post_create_bloc.dart';
|
||||
import 'models/blog_post_create_model.dart';
|
||||
import 'package:eatvio_app/core/app_export.dart';
|
||||
import 'package:flutter/material.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 BlogPostCreateScreen extends StatelessWidget {
|
||||
const BlogPostCreateScreen({Key? key}) : super(key: key);
|
||||
static Widget builder(BuildContext context) {
|
||||
final blog_postID = ModalRoute.of(context)!.settings.arguments;
|
||||
return BlocProvider<BlogPostCreateBloc>(
|
||||
create: (context) => BlogPostCreateBloc(BlogPostCreateState(
|
||||
blog_postModelObj:
|
||||
BlogPostCreateModel(blog_postID: blog_postID.toString())))
|
||||
..add(BlogPostCreateInitialEvent()),
|
||||
child: BlogPostCreateScreen());
|
||||
}
|
||||
|
||||
Widget build(BuildContext context) {
|
||||
return BlocBuilder<BlogPostCreateBloc, BlogPostCreateState>(
|
||||
builder: (context, state) {
|
||||
if (state is BlogPostCreateInitialState) {
|
||||
// Это начальное состояние, данные ещё не загружены.
|
||||
return Container(
|
||||
color: Colors.white,
|
||||
);
|
||||
} else if (state is BlogPostCreateLoadedState) {
|
||||
// Данные загружены, можно строить экран.
|
||||
return _buildBlogPostCreate(context, state);
|
||||
} else if (state is BlogPostCreateErrorState) {
|
||||
// Произошла ошибка при загрузке данных.
|
||||
return Center(child: Text(state.errorMessage));
|
||||
} else {
|
||||
// Другие состояния, если они есть.
|
||||
return Container(); // Пустой контейнер для необработанных состояний.
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
_buildBlogPostCreate(BuildContext context, BlogPostCreateLoadedState 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),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
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.youtube_url,
|
||||
decoration: InputDecoration(labelText: 'Ссылка'),
|
||||
),
|
||||
SizedBox(height: 16.0),
|
||||
// Здесь нужно добавить виджет для загрузки картинки
|
||||
ElevatedButton(
|
||||
onPressed: () => context
|
||||
.read<BlogPostCreateBloc>()
|
||||
.add(CreateBlogPost()),
|
||||
child: Text('Создать'),
|
||||
)
|
||||
]),
|
||||
)
|
||||
]),
|
||||
),
|
||||
bottomNavigationBar: _buildBottomBar(context)));
|
||||
}
|
||||
}
|
||||
|
||||
_buildBottomBar(BuildContext context) {
|
||||
return CustomBottomBar(onChanged: (BottomBarEnum type) {});
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// ignore_for_file: must_be_immutable
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
/// This class defines the variables used in the [blog_post_create_screen],
|
||||
/// and is typically used to hold data that is passed between different parts of the application.
|
||||
|
||||
class BlogPostCreateModel extends Equatable {
|
||||
final String blog_postID;
|
||||
|
||||
BlogPostCreateModel({required String blog_postID})
|
||||
: blog_postID = blog_postID;
|
||||
|
||||
BlogPostCreateModel copyWith(String blog_postID) {
|
||||
return BlogPostCreateModel(blog_postID: blog_postID);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [blog_postID];
|
||||
}
|
||||
@@ -39,7 +39,6 @@ class FeedScreen extends StatelessWidget {
|
||||
|
||||
_buildSetingsScreen(BuildContext context, FeedLoadedState state) {
|
||||
mediaQueryData = MediaQuery.of(context);
|
||||
print(state.posts);
|
||||
return SafeArea(
|
||||
child: Scaffold(
|
||||
backgroundColor: Colors.grey[200],
|
||||
@@ -85,6 +84,16 @@ class FeedScreen extends StatelessWidget {
|
||||
margin: EdgeInsets.only(
|
||||
left: 80.h, top: 12.v, bottom: 9.v),
|
||||
),
|
||||
Spacer(),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 20.0),
|
||||
child: GestureDetector(
|
||||
onTap: () => Navigator.pushNamed(
|
||||
context,
|
||||
AppRoutes.blogPostCreateScreen,
|
||||
),
|
||||
child: Icon(Icons.create_outlined)),
|
||||
)
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -27,10 +27,13 @@ import 'package:eatvio_app/presentation/feed/feed_screen/feed_screen.dart';
|
||||
import 'package:eatvio_app/presentation/recipe/recipe_select_screen/recipe_select_screen.dart';
|
||||
import 'package:eatvio_app/presentation/plans/plan_select_screen/plan_select_screen.dart';
|
||||
import 'package:eatvio_app/presentation/diets/diet_show_screen/diet_show_screen.dart';
|
||||
import 'package:eatvio_app/presentation/diets/diet_edit_screen/diet_edit_screen.dart';
|
||||
import 'package:eatvio_app/presentation/diets/diet_create_screen/diet_create_screen.dart';
|
||||
import 'package:eatvio_app/presentation/plans/plan_show_screen/plan_show_screen.dart';
|
||||
import 'package:eatvio_app/presentation/recipe/recipe_show_screen/recipe_show_screen.dart';
|
||||
import 'package:eatvio_app/presentation/feed/blog_post_screen/blog_post_screen.dart';
|
||||
import 'package:eatvio_app/presentation/feed/blog_post_edit_screen/blog_post_edit_screen.dart';
|
||||
import 'package:eatvio_app/presentation/feed/blog_post_create_screen/blog_post_create_screen.dart';
|
||||
|
||||
class AppRoutes {
|
||||
// REGISTRATION
|
||||
@@ -93,6 +96,8 @@ class AppRoutes {
|
||||
|
||||
static const String blogPostEditScreen = '/blogPostEdit';
|
||||
|
||||
static const String blogPostCreateScreen = '/blogPostCreate';
|
||||
|
||||
static const String recipeSelectScreen = '/recipeSelect';
|
||||
|
||||
static const String recipeScreen = '/recipe';
|
||||
@@ -101,6 +106,10 @@ class AppRoutes {
|
||||
|
||||
static const String dietScreen = '/diet';
|
||||
|
||||
static const String dietEditScreen = 'dietEdit';
|
||||
|
||||
static const String dietCreateScreen = '/dietCreate';
|
||||
|
||||
static const String planSelectScreen = '/planSelect';
|
||||
|
||||
static const String planScreen = '/plan';
|
||||
@@ -139,5 +148,8 @@ class AppRoutes {
|
||||
planScreen: PlanScreen.builder,
|
||||
blogPostScreen: BlogPostScreen.builder,
|
||||
blogPostEditScreen: BlogPostEditScreen.builder,
|
||||
blogPostCreateScreen: BlogPostCreateScreen.builder,
|
||||
dietEditScreen: DietEditScreen.builder,
|
||||
dietCreateScreen: DietCreateScreen.builder,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user