forked from eatvio/eatvio_app
feat(diary): Data load and screen update on scroll TODO: Fix an error on product remove
This commit is contained in:
@@ -33,8 +33,9 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
|
||||
on<ProductInput>(
|
||||
_inputProduct); //пользователь нажимает "Добавить комментарий"
|
||||
on<FinishDay>(_finishDay); //пользователь нажимает "Добавить комментарий"
|
||||
on<SendModeration>(
|
||||
_sendModeration); //пользователь нажимает "Добавить комментарий"
|
||||
on<SendModeration>(_sendModeration);
|
||||
on<RefreshEvent>(
|
||||
reloadScreen); //пользователь нажимает "Добавить комментарий"
|
||||
}
|
||||
|
||||
Future<void> _onInitialize(
|
||||
@@ -65,7 +66,7 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
|
||||
},
|
||||
);
|
||||
final diary = jsonDecode(response.body)['diary'];
|
||||
print(diary);
|
||||
print("Screen load success");
|
||||
if (diary is Map<String, dynamic>) {
|
||||
final String diaryDate =
|
||||
diary['date'] ?? DateTime.now().toString();
|
||||
@@ -146,6 +147,84 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
|
||||
}
|
||||
}
|
||||
|
||||
reloadScreen(DiaryEditEvent event, Emitter<DiaryEditState> emit) async {
|
||||
print("Reloading...");
|
||||
try {
|
||||
final token =
|
||||
"laravel_sanctum_1lPFtd9tpGmHYS243C4K7YF8BrVhxxgXm8cTmjuZda1da694";
|
||||
|
||||
final response = await http.get(
|
||||
Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/index'),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer $token',
|
||||
},
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = jsonDecode(response.body);
|
||||
if (data is Map<String, dynamic> && data.containsKey('id')) {
|
||||
final int diaryId = data['id'];
|
||||
|
||||
final diaryResponse = await http.get(
|
||||
Uri.parse(dotenv.env['SERVER_ROOT']! + '/diary/show/$diaryId'),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer $token',
|
||||
},
|
||||
);
|
||||
|
||||
final diary = jsonDecode(diaryResponse.body)['diary'];
|
||||
|
||||
if (diary is Map<String, dynamic>) {
|
||||
final String diaryDate = diary['date'] ?? DateTime.now().toString();
|
||||
// Продолжайте обработку данных дневника
|
||||
// Если текущее состояние - начальное, создаем новое загруженное состояние
|
||||
try {
|
||||
await Future(() => emit(DiaryEditLoadedState(
|
||||
currentMeal: SelectionPopupModel(
|
||||
id: 1, title: "Прием пищи 1", isSelected: true),
|
||||
wakeupExpanded: true,
|
||||
moodExpanded: true,
|
||||
moderationExpanded: false,
|
||||
token: token,
|
||||
meals: diary['meals'],
|
||||
portions: diary['meals'][0]['portions'],
|
||||
wakeupController: toTime(diary['wakeup'] ?? "09:00"),
|
||||
retireController: toTime(diary['retire'] ?? "23:00"),
|
||||
mealTimeController:
|
||||
toTime(diary['meals'][0]['time'] ?? "10:00"),
|
||||
selectedSatiety: diary['meals'][0]['satiety'],
|
||||
selectedMood: diary['meals'][0]['mood'],
|
||||
commentController:
|
||||
TextEditingController(text: diary['comment']),
|
||||
productNameController: TextEditingController(),
|
||||
productQuantityController: TextEditingController(),
|
||||
diaryId: diaryId,
|
||||
diaryDate: diaryDate,
|
||||
autocompleteList: [],
|
||||
diaryEditModelObj: state.diaryEditModelObj
|
||||
?.copyWith(mealList: fillMealList()))));
|
||||
print("Updated");
|
||||
} catch (e) {
|
||||
print("Ошибка при создании нового состояния $e");
|
||||
}
|
||||
} else {
|
||||
emit(DiaryEditErrorState(
|
||||
'Ошибка при декодировании данных дневника'));
|
||||
}
|
||||
} else {
|
||||
emit(
|
||||
DiaryEditErrorState('Некоторые необходимые данные отсутствуют.'));
|
||||
}
|
||||
} else {
|
||||
emit(DiaryEditErrorState('Ошибка сервера: ${response.statusCode}'));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(DiaryEditErrorState('Ошибка при получении данных дневника: $e'));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _changeSatiety(
|
||||
ChangeSatiety event, Emitter<DiaryEditState> emit) async {
|
||||
if (state is DiaryEditLoadedState) {
|
||||
@@ -401,6 +480,8 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
|
||||
currentState.diaryId,
|
||||
);
|
||||
|
||||
print(currentState.portions);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
dynamic newPortion = jsonDecode(response.body)['portion'];
|
||||
|
||||
@@ -409,7 +490,13 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
|
||||
|
||||
final updatedState = currentState.copyWith(portions: updatedPortions);
|
||||
|
||||
print(updatedState.portions);
|
||||
|
||||
emit(updatedState); // Emit the updated state
|
||||
} else {
|
||||
// Handling error when response status code is not 200
|
||||
print(
|
||||
'Failed to add portion. Status Code: ${response.statusCode} ${response.body}');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -467,8 +554,8 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
|
||||
.map((product) => product['name'])
|
||||
.toList(),
|
||||
);
|
||||
|
||||
if (event.input.length > 2) {
|
||||
print(event.input.length);
|
||||
if (event.input.length > 3) {
|
||||
updatedState = updatedState.copyWith(moderationExpanded: true);
|
||||
} else {
|
||||
updatedState = updatedState.copyWith(moderationExpanded: false);
|
||||
@@ -494,16 +581,8 @@ class DiaryEditBloc extends Bloc<DiaryEditEvent, DiaryEditState> {
|
||||
currentState.diaryId,
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final updatedPortions = currentState.portions
|
||||
?.where((portion) => portion['id'] != event.portionId)
|
||||
.toList();
|
||||
|
||||
final updatedState = currentState.copyWith(portions: updatedPortions);
|
||||
|
||||
await _onInitialize(
|
||||
DiaryEditInitialEvent(), emit); // Emit the updated state
|
||||
emit(updatedState);
|
||||
if (response.statusCode == 204) {
|
||||
reloadScreen(event, emit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,6 +121,13 @@ class FinishDay extends DiaryEditEvent {
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
class RefreshEvent extends DiaryEditEvent {
|
||||
RefreshEvent();
|
||||
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
class SendModeration extends DiaryEditEvent {
|
||||
SendModeration(
|
||||
{required this.name,
|
||||
|
||||
@@ -55,7 +55,7 @@ class DiaryEditScreen extends StatelessWidget {
|
||||
BuildContext context, DiaryEditLoadedState state) {
|
||||
mediaQueryData = MediaQuery.of(context);
|
||||
return RefreshIndicator(
|
||||
onRefresh: () async {},
|
||||
onRefresh: refreshPage(context),
|
||||
child: FormBuilder(
|
||||
child: SafeArea(
|
||||
child: Scaffold(
|
||||
@@ -95,6 +95,12 @@ class DiaryEditScreen extends StatelessWidget {
|
||||
)));
|
||||
}
|
||||
|
||||
refreshPage(BuildContext context) {
|
||||
return () async {
|
||||
context.read<DiaryEditBloc>().add(RefreshEvent());
|
||||
};
|
||||
}
|
||||
|
||||
/// Section Widget
|
||||
_buildHeaderRow(BuildContext context, DiaryEditLoadedState state) {
|
||||
final day = state.diaryId;
|
||||
|
||||
@@ -33,7 +33,9 @@ void main() {
|
||||
MaterialApp(
|
||||
home: BlocProvider<DiaryEditBloc>.value(
|
||||
value: diaryEditBloc,
|
||||
child: DiaryEditScreen(),
|
||||
child: DiaryEditScreen(
|
||||
onInitialize: () {},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user