forked from eatvio/eatvio_app
feat: implement offline-first architecture with local database synchronization and diary caching
This commit is contained in:
@@ -3,6 +3,8 @@ import 'dart:io';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/image_compressing/image_compress_utility.dart';
|
||||
import 'package:eatvio_app/core/internet_connection_cubit/internet_connection_cubit.dart';
|
||||
import 'package:eatvio_app/core/local_db/diary_local_data_source.dart';
|
||||
import 'package:eatvio_app/core/utils/date_time_utils.dart';
|
||||
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
|
||||
import 'package:eatvio_app/features/consultations/models/consultation_model.dart';
|
||||
@@ -30,7 +32,13 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
final DietRepository dietRepository;
|
||||
final ChatRepository chatRepository;
|
||||
final SettingsRepository settingsRepository;
|
||||
final DiaryLocalDataSource localDataSource;
|
||||
final InternetConnectionCubit connectionCubit;
|
||||
int? diaryId;
|
||||
|
||||
// Трек офлайн-режима
|
||||
bool _lastFetchWasOffline = false;
|
||||
|
||||
DiaryCubit({
|
||||
required this.chatRepository,
|
||||
required this.diaryRepository,
|
||||
@@ -38,6 +46,8 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
required this.profileRepository,
|
||||
required this.dietRepository,
|
||||
required this.settingsRepository,
|
||||
required this.localDataSource,
|
||||
required this.connectionCubit,
|
||||
}) : super(const DiaryState.loading()) {
|
||||
today = DateTime.now();
|
||||
selectedDay = today;
|
||||
@@ -86,7 +96,11 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
|
||||
final diaryDay = await getDiary();
|
||||
if (diaryDay == null) {
|
||||
emit(const DiaryState.error(errorMessage: 'Diary not found'));
|
||||
// Офлайн и нет кэша — показываем понятное сообщение
|
||||
final msg = connectionCubit.state.isInternetAvailable
|
||||
? 'Дневник не найден'
|
||||
: 'Нет интернета. Откройте дневник онлайн хотя бы один раз, чтобы он был доступен офлайн.';
|
||||
emit(DiaryState.error(errorMessage: msg));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -110,7 +124,9 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
|
||||
Future<void> updateCurrentDiary() async {
|
||||
try {
|
||||
final diaryDay = await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
final diaryDay = await diaryRepository.getDiaryDayV2(
|
||||
day: selectedDay.toISO8601WithTimeZoneOffset(),
|
||||
);
|
||||
final diaryEntity = diaryDay.toEntity();
|
||||
if (diaryEntity != null) {
|
||||
setDiary(diaryDay: diaryEntity, diaryId: diaryId);
|
||||
@@ -121,19 +137,39 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
}
|
||||
|
||||
Future<DiaryDayModel?> getDiary() async {
|
||||
_lastFetchWasOffline = false;
|
||||
|
||||
// Офлайн: СРАЗУ в кэш, не трогаем сеть
|
||||
if (!connectionCubit.state.isInternetAvailable) {
|
||||
_lastFetchWasOffline = true;
|
||||
try {
|
||||
return await diaryRepository.getDiaryDayV2(
|
||||
day: selectedDay.toISO8601WithTimeZoneOffset(),
|
||||
);
|
||||
} catch (_) {
|
||||
return null; // Нет кэша — вернём null, UI покажет offline-заглушку
|
||||
}
|
||||
}
|
||||
|
||||
// Онлайн: создаём день + грузим с сервера
|
||||
try {
|
||||
await diaryRepository.createDiaryDay(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
final diaryDay = await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
return diaryDay;
|
||||
return await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
} catch (e, st) {
|
||||
log(e.toString(), stackTrace: st);
|
||||
if (e is DioException) {
|
||||
if (e.response?.statusCode == 422) {
|
||||
final diaryDay = await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
return diaryDay;
|
||||
}
|
||||
if (e is DioException && e.response?.statusCode == 422) {
|
||||
// День уже существует — просто загружаем
|
||||
try {
|
||||
return await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
} catch (_) {}
|
||||
}
|
||||
// Другая сетевая ошибка → пробуем кэш
|
||||
_lastFetchWasOffline = true;
|
||||
try {
|
||||
return await diaryRepository.getDiaryDayV2(day: selectedDay.toISO8601WithTimeZoneOffset());
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,35 +268,54 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
try {
|
||||
bool isMoodEnabled = false;
|
||||
bool isWakeUpAndRetireTimeEnabled = false;
|
||||
if (diaryId != null) {
|
||||
} else {
|
||||
final profileSettings = await settingsRepository.getProfileSettings();
|
||||
isMoodEnabled = profileSettings.isMoodFillable;
|
||||
isWakeUpAndRetireTimeEnabled = profileSettings.isBedtimeFillable;
|
||||
if (diaryId == null) {
|
||||
try {
|
||||
final profileSettings = await settingsRepository.getProfileSettings();
|
||||
isMoodEnabled = profileSettings.isMoodFillable;
|
||||
isWakeUpAndRetireTimeEnabled = profileSettings.isBedtimeFillable;
|
||||
} catch (_) {
|
||||
// Офлайн — используем значения по умолчанию
|
||||
}
|
||||
}
|
||||
|
||||
ConsultantReviewModel? consultantReview;
|
||||
int? planDuration;
|
||||
int? currentPlanDay;
|
||||
String? planName;
|
||||
if (diaryDay.chosenPlanId != null) {
|
||||
final chosenPlanModel = await chatRepository.getChosenPlan(id: diaryDay.chosenPlanId!);
|
||||
if (!isConsultantView &&
|
||||
(diaryDay.typeOfDiary.diaryState == DiaryStateEnum.lastDayCommented || diaryDay.typeOfDiary.diaryState == DiaryStateEnum.commented)) {
|
||||
await diaryRepository.viewCommentOfDiaryDayByConsultant(diaryId: diaryDay.id);
|
||||
try {
|
||||
final chosenPlanModel = await chatRepository.getChosenPlan(id: diaryDay.chosenPlanId!);
|
||||
if (!isConsultantView &&
|
||||
(diaryDay.typeOfDiary.diaryState == DiaryStateEnum.lastDayCommented ||
|
||||
diaryDay.typeOfDiary.diaryState == DiaryStateEnum.commented)) {
|
||||
await diaryRepository.viewCommentOfDiaryDayByConsultant(diaryId: diaryDay.id);
|
||||
}
|
||||
consultantReview = await diaryRepository.getDiaryComments(
|
||||
planId: diaryDay.chosenPlanId!,
|
||||
diaryId: diaryDay.id,
|
||||
);
|
||||
planDuration = chosenPlanModel.plan.duration;
|
||||
planName = chosenPlanModel.plan.name;
|
||||
currentPlanDay = consultantReview.currentPlanDay;
|
||||
} catch (_) {
|
||||
// Офлайн — данные плана недоступны
|
||||
}
|
||||
consultantReview = await diaryRepository.getDiaryComments(planId: diaryDay.chosenPlanId!, diaryId: diaryDay.id);
|
||||
planDuration = chosenPlanModel.plan.duration;
|
||||
planName = chosenPlanModel.plan.name;
|
||||
currentPlanDay = consultantReview.currentPlanDay;
|
||||
}
|
||||
|
||||
final nutrition = await getNutrition(diaryDay.id);
|
||||
|
||||
final isDiaryFinished = diaryDay.typeOfDiary.diaryState == DiaryStateEnum.finished || diaryDay.typeOfDiary.diaryState == DiaryStateEnum.lastDayFinished;
|
||||
final isDiaryFinished =
|
||||
diaryDay.typeOfDiary.diaryState == DiaryStateEnum.finished ||
|
||||
diaryDay.typeOfDiary.diaryState == DiaryStateEnum.lastDayFinished;
|
||||
|
||||
final isDiaryCommented =
|
||||
diaryDay.typeOfDiary.diaryState == DiaryStateEnum.commented ||
|
||||
diaryDay.typeOfDiary.diaryState == DiaryStateEnum.lastDayCommented ||
|
||||
diaryDay.typeOfDiary.diaryState == DiaryStateEnum.reviewedByUser;
|
||||
|
||||
// Offline-first: получаем кол-во операций в очереди
|
||||
final pendingCount = await localDataSource.getPendingCount();
|
||||
|
||||
emit(
|
||||
DiaryState.loaded(
|
||||
diary: diaryDay,
|
||||
@@ -276,6 +331,8 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
chosenPlanName: planName,
|
||||
isMoodEnabled: isMoodEnabled,
|
||||
isWakeUpAndRetireEnabled: isWakeUpAndRetireTimeEnabled,
|
||||
pendingOpsCount: pendingCount,
|
||||
isOfflineMode: _lastFetchWasOffline,
|
||||
),
|
||||
);
|
||||
} catch (e, st) {
|
||||
@@ -295,8 +352,13 @@ class DiaryCubit extends Cubit<DiaryState> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<NutritionDataModel> getNutrition(int index) async {
|
||||
return (await diaryRepository.getNutritionData(index));
|
||||
Future<NutritionDataModel?> getNutrition(int index) async {
|
||||
try {
|
||||
return await diaryRepository.getNutritionData(index);
|
||||
} catch (e) {
|
||||
log('getNutrition offline fallback: $e');
|
||||
return null; // Офлайн — нет данных по калориям, не критично
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> addProductToMeal({
|
||||
|
||||
@@ -16,7 +16,7 @@ abstract class DiaryState with _$DiaryState {
|
||||
|
||||
const factory DiaryState.loaded({
|
||||
required DiaryDayEntity diary,
|
||||
required NutritionDataModel nutrition,
|
||||
NutritionDataModel? nutrition,
|
||||
required DateTime selectedDay,
|
||||
required int selectedMeal,
|
||||
int? chosenPlanCurrentDay,
|
||||
@@ -29,6 +29,10 @@ abstract class DiaryState with _$DiaryState {
|
||||
@Default(false) bool isWakeUpAndRetireEnabled,
|
||||
@Default(false) bool isMoodEnabled,
|
||||
@Default(false) bool isLoadingAddingProductInMeal,
|
||||
// Offline-first: кол-во операций в очереди на синхронизацию
|
||||
@Default(0) int pendingOpsCount,
|
||||
// Offline-first: true если данные получены из локального кэша
|
||||
@Default(false) bool isOfflineMode,
|
||||
}) = DiaryStateLoaded;
|
||||
|
||||
const factory DiaryState.loadedTomorrowWithDiet({required DiaryFutureDietDayEntity diary, required DateTime selectedDay, required int selectedMeal}) =
|
||||
|
||||
@@ -19,6 +19,7 @@ import 'package:eatvio_app/features/diary/presentation/widgets/comment_for_consu
|
||||
import 'package:eatvio_app/features/diary/presentation/widgets/day_comment_widget.dart';
|
||||
import 'package:eatvio_app/features/diary/presentation/widgets/finish_day_button_widget.dart';
|
||||
import 'package:eatvio_app/features/diary/presentation/widgets/meal_widget.dart';
|
||||
import 'package:eatvio_app/features/diary/presentation/widgets/offline_banner_widget.dart';
|
||||
import 'package:eatvio_app/features/diary/presentation/widgets/wakeup_and_retire_widget.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
@@ -89,99 +90,107 @@ class _DiaryScreenContentState extends State<DiaryScreenContent> {
|
||||
),
|
||||
centerTitle: true,
|
||||
),
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.only(bottom: 16, top: 8),
|
||||
physics: const BouncingScrollPhysics(),
|
||||
child: Column(
|
||||
children: [
|
||||
if (widget.diaryId == null) CalendarWidget(date: widget.date),
|
||||
if (state is DiaryStateLoading) ...[const SizedBox(height: 60), const Loader()],
|
||||
if (state is DiaryStateLoaded)
|
||||
WakeupAndRetireWidget(
|
||||
isEnabled: state.diary.typeOfDiary.hasChosenPlan || state.isConsultantView || state.isWakeUpAndRetireEnabled,
|
||||
disable: state.isConsultantView || state.isDiaryFinished || state.isDiaryCommented,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (state is DiaryStateLoaded)
|
||||
MealWidget(
|
||||
showMood: state.diary.typeOfDiary.hasChosenPlan || state.isConsultantView || state.isMoodEnabled,
|
||||
showAddButton: !state.isConsultantView && !state.isDiaryFinished && !state.isDiaryCommented,
|
||||
),
|
||||
if (state is DiaryStateLoadedTomorrowWithDiet) const MealWidget(showMood: false, showAddButton: false),
|
||||
if (state is DiaryStateLoaded) const CaloriesChartWidget(),
|
||||
const SizedBox(height: 12),
|
||||
Builder(
|
||||
builder: (context) {
|
||||
if (state is DiaryStateLoaded && state.diary.typeOfDiary.hasChosenPlan) {
|
||||
if (state.diary.comment.isNotEmpty) {
|
||||
return CommentForConsultantWidget(comment: state.diary.comment);
|
||||
}
|
||||
if (state.isDiaryCommented || state.isDiaryFinished) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return const CommentForConsultantWidget();
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
if (state is DiaryStateLoaded && !state.isConsultantView && !state.isDiaryFinished && !state.isDiaryCommented)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 12),
|
||||
child: _isDiaryFinishing
|
||||
? const Center(child: Loader())
|
||||
: FinishDayButtonWidget(
|
||||
hasProducts: state.diary.hasProducts,
|
||||
onPressed: () async {
|
||||
setState(() {
|
||||
_isDiaryFinishing = true;
|
||||
});
|
||||
final isFinished = await context.read<DiaryCubit>().finishDiaryDay(
|
||||
diaryId: state.diary.id,
|
||||
wakeUp: state.diary.wakeup.toString(),
|
||||
retire: state.diary.retire.toString(),
|
||||
);
|
||||
if (!isFinished && context.mounted) {
|
||||
showErrorDialog(context);
|
||||
}
|
||||
setState(() {
|
||||
_isDiaryFinishing = false;
|
||||
});
|
||||
},
|
||||
),
|
||||
),
|
||||
if (state is DiaryStateLoaded && state.isConsultantView && !state.isDiaryCommented) ...[
|
||||
const SizedBox(height: 16),
|
||||
const MainBackgroundBouble(padding: EdgeInsets.all(16), child: DayCommentWidget()),
|
||||
],
|
||||
if (state is DiaryStateLoaded && state.consultantReview?.consultantComments.dayComment != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
MainBackgroundBouble(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(s.dayComment, style: TextStyles.textLSemibold.copyWith(color: appTheme.black)),
|
||||
const SizedBox(height: 12),
|
||||
CommentContainer(comment: state.consultantReview?.consultantComments.dayComment ?? ''),
|
||||
body: Column(
|
||||
children: [
|
||||
// Офлайн-баннер (скользит сверху при потере сети)
|
||||
const OfflineBannerWidget(),
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.only(bottom: 16, top: 8),
|
||||
physics: const BouncingScrollPhysics(),
|
||||
child: Column(
|
||||
children: [
|
||||
if (widget.diaryId == null) CalendarWidget(date: widget.date),
|
||||
if (state is DiaryStateLoading) ...[const SizedBox(height: 60), const Loader()],
|
||||
if (state is DiaryStateLoaded)
|
||||
WakeupAndRetireWidget(
|
||||
isEnabled: state.diary.typeOfDiary.hasChosenPlan || state.isConsultantView || state.isWakeUpAndRetireEnabled,
|
||||
disable: state.isConsultantView || state.isDiaryFinished || state.isDiaryCommented,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (state is DiaryStateLoaded)
|
||||
MealWidget(
|
||||
showMood: state.diary.typeOfDiary.hasChosenPlan || state.isConsultantView || state.isMoodEnabled,
|
||||
showAddButton: !state.isConsultantView && !state.isDiaryFinished && !state.isDiaryCommented,
|
||||
),
|
||||
if (state is DiaryStateLoadedTomorrowWithDiet) const MealWidget(showMood: false, showAddButton: false),
|
||||
if (state is DiaryStateLoaded) const CaloriesChartWidget(),
|
||||
const SizedBox(height: 12),
|
||||
Builder(
|
||||
builder: (context) {
|
||||
if (state is DiaryStateLoaded && state.diary.typeOfDiary.hasChosenPlan) {
|
||||
if (state.diary.comment.isNotEmpty) {
|
||||
return CommentForConsultantWidget(comment: state.diary.comment);
|
||||
}
|
||||
if (state.isDiaryCommented || state.isDiaryFinished) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return const CommentForConsultantWidget();
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
if (state is DiaryStateLoaded && !state.isConsultantView && !state.isDiaryFinished && !state.isDiaryCommented)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 12),
|
||||
child: _isDiaryFinishing
|
||||
? const Center(child: Loader())
|
||||
: FinishDayButtonWidget(
|
||||
hasProducts: state.diary.hasProducts,
|
||||
onPressed: () async {
|
||||
setState(() {
|
||||
_isDiaryFinishing = true;
|
||||
});
|
||||
final isFinished = await context.read<DiaryCubit>().finishDiaryDay(
|
||||
diaryId: state.diary.id,
|
||||
wakeUp: state.diary.wakeup.toString(),
|
||||
retire: state.diary.retire.toString(),
|
||||
);
|
||||
if (!isFinished && context.mounted) {
|
||||
showErrorDialog(context);
|
||||
}
|
||||
setState(() {
|
||||
_isDiaryFinishing = false;
|
||||
});
|
||||
},
|
||||
),
|
||||
),
|
||||
if (state is DiaryStateLoaded && state.isConsultantView && !state.isDiaryCommented) ...[
|
||||
const SizedBox(height: 16),
|
||||
const MainBackgroundBouble(padding: EdgeInsets.all(16), child: DayCommentWidget()),
|
||||
],
|
||||
),
|
||||
if (state is DiaryStateLoaded && state.consultantReview?.consultantComments.dayComment != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
MainBackgroundBouble(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(s.dayComment, style: TextStyles.textLSemibold.copyWith(color: appTheme.black)),
|
||||
const SizedBox(height: 12),
|
||||
CommentContainer(comment: state.consultantReview?.consultantComments.dayComment ?? ''),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
],
|
||||
if (state is DiaryStateLoaded && state.isConsultantView && state.isDiaryFinished && !state.isDiaryCommented) ...[
|
||||
const SizedBox(height: 16),
|
||||
CustomOutlinedButton(
|
||||
text: s.send,
|
||||
height: 52,
|
||||
buttonTextStyle: TextStyles.textMSemibold.copyWith(color: appTheme.whiteA700),
|
||||
buttonStyle: ButtonStyle(side: const WidgetStatePropertyAll(BorderSide.none), backgroundColor: WidgetStatePropertyAll(appTheme.blueA400)),
|
||||
onPressed: () async {
|
||||
await context.read<ConsultantCommentsCubit>().submitComments(state.diary.id);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
],
|
||||
if (state is DiaryStateLoaded && state.isConsultantView && state.isDiaryFinished && !state.isDiaryCommented) ...[
|
||||
const SizedBox(height: 16),
|
||||
CustomOutlinedButton(
|
||||
text: s.send,
|
||||
height: 52,
|
||||
buttonTextStyle: TextStyles.textMSemibold.copyWith(color: appTheme.whiteA700),
|
||||
buttonStyle: ButtonStyle(side: const WidgetStatePropertyAll(BorderSide.none), backgroundColor: WidgetStatePropertyAll(appTheme.blueA400)),
|
||||
onPressed: () async {
|
||||
await context.read<ConsultantCommentsCubit>().submitComments(state.diary.id);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
@@ -13,6 +13,10 @@ class CaloriesChartWidget extends StatelessWidget {
|
||||
return BlocBuilder<DiaryCubit, DiaryState>(
|
||||
builder: (BuildContext context, DiaryState state) {
|
||||
if (state is DiaryStateLoaded) {
|
||||
// В офлайн-режиме данные о питании недоступны — скрываем блок
|
||||
final nutrition = state.nutrition;
|
||||
if (nutrition == null) return const SizedBox.shrink();
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(top: 12),
|
||||
padding: const EdgeInsets.all(16),
|
||||
@@ -72,9 +76,9 @@ class CaloriesChartWidget extends StatelessWidget {
|
||||
cornerStyle: CornerStyle.bothCurve,
|
||||
),
|
||||
RangePointer(
|
||||
value: (state.nutrition.dailyNutritionIntake.carbohydrates / state.nutrition.dailyNutritionRecommendation.carbohydrates) * 100,
|
||||
value: (nutrition.dailyNutritionIntake.carbohydrates / nutrition.dailyNutritionRecommendation.carbohydrates) * 100,
|
||||
width: 0.16,
|
||||
color: state.nutrition.dailyNutritionIntake.carbohydrates < state.nutrition.dailyNutritionRecommendation.carbohydrates
|
||||
color: nutrition.dailyNutritionIntake.carbohydrates < nutrition.dailyNutritionRecommendation.carbohydrates
|
||||
? appTheme.blueA400
|
||||
: Colors.red,
|
||||
sizeUnit: GaugeSizeUnit.factor,
|
||||
@@ -92,9 +96,9 @@ class CaloriesChartWidget extends StatelessWidget {
|
||||
pointerOffset: -0.18,
|
||||
),
|
||||
RangePointer(
|
||||
value: (state.nutrition.dailyNutritionIntake.fats / state.nutrition.dailyNutritionRecommendation.fats) * 100,
|
||||
value: (nutrition.dailyNutritionIntake.fats / nutrition.dailyNutritionRecommendation.fats) * 100,
|
||||
width: 0.16,
|
||||
color: state.nutrition.dailyNutritionIntake.fats < state.nutrition.dailyNutritionRecommendation.fats
|
||||
color: nutrition.dailyNutritionIntake.fats < nutrition.dailyNutritionRecommendation.fats
|
||||
? appTheme.blueA400
|
||||
: Colors.red,
|
||||
sizeUnit: GaugeSizeUnit.factor,
|
||||
@@ -113,9 +117,9 @@ class CaloriesChartWidget extends StatelessWidget {
|
||||
pointerOffset: -0.36,
|
||||
),
|
||||
RangePointer(
|
||||
value: (state.nutrition.dailyNutritionIntake.proteins / state.nutrition.dailyNutritionRecommendation.proteins) * 100,
|
||||
value: (nutrition.dailyNutritionIntake.proteins / nutrition.dailyNutritionRecommendation.proteins) * 100,
|
||||
width: 0.16,
|
||||
color: state.nutrition.dailyNutritionIntake.proteins < state.nutrition.dailyNutritionRecommendation.proteins
|
||||
color: nutrition.dailyNutritionIntake.proteins < nutrition.dailyNutritionRecommendation.proteins
|
||||
? appTheme.blueA400
|
||||
: Colors.red,
|
||||
sizeUnit: GaugeSizeUnit.factor,
|
||||
@@ -134,9 +138,9 @@ class CaloriesChartWidget extends StatelessWidget {
|
||||
pointerOffset: -0.54,
|
||||
),
|
||||
RangePointer(
|
||||
value: (state.nutrition.dailyNutritionIntake.energy / state.nutrition.dailyNutritionRecommendation.energy) * 100,
|
||||
value: (nutrition.dailyNutritionIntake.energy / nutrition.dailyNutritionRecommendation.energy) * 100,
|
||||
width: 0.16,
|
||||
color: state.nutrition.dailyNutritionIntake.energy < state.nutrition.dailyNutritionRecommendation.energy
|
||||
color: nutrition.dailyNutritionIntake.energy < nutrition.dailyNutritionRecommendation.energy
|
||||
? appTheme.blueA400
|
||||
: Colors.red,
|
||||
sizeUnit: GaugeSizeUnit.factor,
|
||||
@@ -210,24 +214,22 @@ class CaloriesChartWidget extends StatelessWidget {
|
||||
children: [
|
||||
_chartData(
|
||||
'Калории',
|
||||
'${state.nutrition.dailyNutritionIntake.energy.toStringAsFixed(0)} из ${state.nutrition.dailyNutritionRecommendation.energy.toStringAsFixed(0)} ккал',
|
||||
'${nutrition.dailyNutritionIntake.energy.toStringAsFixed(0)} из ${nutrition.dailyNutritionRecommendation.energy.toStringAsFixed(0)} ккал',
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
_chartData(
|
||||
'Белки',
|
||||
'${state.nutrition.dailyNutritionIntake.proteins.toStringAsFixed(0)} из ${state.nutrition.dailyNutritionRecommendation.proteins.toStringAsFixed(
|
||||
0,
|
||||
)} грамм',
|
||||
'${nutrition.dailyNutritionIntake.proteins.toStringAsFixed(0)} из ${nutrition.dailyNutritionRecommendation.proteins.toStringAsFixed(0)} грамм',
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
_chartData(
|
||||
'Жиры',
|
||||
'${state.nutrition.dailyNutritionIntake.fats.toStringAsFixed(0)} из ${state.nutrition.dailyNutritionRecommendation.fats.toStringAsFixed(0)} грамм',
|
||||
'${nutrition.dailyNutritionIntake.fats.toStringAsFixed(0)} из ${nutrition.dailyNutritionRecommendation.fats.toStringAsFixed(0)} грамм',
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
_chartData(
|
||||
'Углеводы',
|
||||
'${state.nutrition.dailyNutritionIntake.carbohydrates.toStringAsFixed(0)} из ${state.nutrition.dailyNutritionRecommendation.carbohydrates.toStringAsFixed(0)} грамм',
|
||||
'${nutrition.dailyNutritionIntake.carbohydrates.toStringAsFixed(0)} из ${nutrition.dailyNutritionRecommendation.carbohydrates.toStringAsFixed(0)} грамм',
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -238,6 +240,7 @@ class CaloriesChartWidget extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart';
|
||||
import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.dart';
|
||||
|
||||
/// Тонкий баннер вверху экрана дневника, указывающий на офлайн-режим
|
||||
/// и количество операций, ожидающих синхронизацию.
|
||||
///
|
||||
/// Показывается только когда нет интернета или есть pending операции.
|
||||
/// Автоматически скрывается при восстановлении соединения и пустой очереди.
|
||||
class OfflineBannerWidget extends StatelessWidget {
|
||||
const OfflineBannerWidget({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocBuilder<DiaryCubit, DiaryState>(
|
||||
buildWhen: (prev, curr) {
|
||||
if (prev is DiaryStateLoaded && curr is DiaryStateLoaded) {
|
||||
return prev.pendingOpsCount != curr.pendingOpsCount ||
|
||||
prev.isOfflineMode != curr.isOfflineMode;
|
||||
}
|
||||
return prev.runtimeType != curr.runtimeType;
|
||||
},
|
||||
builder: (context, state) {
|
||||
if (state is! DiaryStateLoaded) return const SizedBox.shrink();
|
||||
|
||||
final isOffline = state.isOfflineMode;
|
||||
final pending = state.pendingOpsCount;
|
||||
|
||||
// Не показываем если онлайн и очердь пуста
|
||||
if (!isOffline && pending == 0) return const SizedBox.shrink();
|
||||
|
||||
return _OfflineBanner(isOffline: isOffline, pendingCount: pending);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _OfflineBanner extends StatefulWidget {
|
||||
final bool isOffline;
|
||||
final int pendingCount;
|
||||
|
||||
const _OfflineBanner({required this.isOffline, required this.pendingCount});
|
||||
|
||||
@override
|
||||
State<_OfflineBanner> createState() => _OfflineBannerState();
|
||||
}
|
||||
|
||||
class _OfflineBannerState extends State<_OfflineBanner>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late final AnimationController _controller;
|
||||
late final Animation<double> _slideAnim;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
);
|
||||
_slideAnim = Tween<double>(begin: -1.0, end: 0.0).animate(
|
||||
CurvedAnimation(parent: _controller, curve: Curves.easeOutCubic),
|
||||
);
|
||||
_controller.forward();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final (color, icon, text) = _resolveStyle();
|
||||
|
||||
return AnimatedBuilder(
|
||||
animation: _slideAnim,
|
||||
builder: (context, child) => Transform.translate(
|
||||
offset: Offset(0, _slideAnim.value * 40),
|
||||
child: child,
|
||||
),
|
||||
child: Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 9),
|
||||
decoration: BoxDecoration(
|
||||
color: color,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: color.withValues(alpha: 0.35),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(icon, color: Colors.white, size: 16),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
text,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
letterSpacing: 0.2,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (widget.isOffline)
|
||||
const _PulsingDot(),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
(Color, IconData, String) _resolveStyle() {
|
||||
if (widget.isOffline && widget.pendingCount > 0) {
|
||||
return (
|
||||
const Color(0xFFE85D04),
|
||||
Icons.cloud_off_rounded,
|
||||
'Офлайн · ${widget.pendingCount} ${_inflect(widget.pendingCount)} в очереди',
|
||||
);
|
||||
} else if (widget.isOffline) {
|
||||
return (
|
||||
const Color(0xFF6B7280),
|
||||
Icons.cloud_off_rounded,
|
||||
'Офлайн · данные из кэша',
|
||||
);
|
||||
} else {
|
||||
// Онлайн, но есть pending операции (только что восстановилось соединение)
|
||||
return (
|
||||
const Color(0xFF059669),
|
||||
Icons.sync_rounded,
|
||||
'Синхронизация: ${widget.pendingCount} ${_inflect(widget.pendingCount)}…',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _inflect(int n) {
|
||||
if (n % 100 >= 11 && n % 100 <= 19) return 'изменений';
|
||||
switch (n % 10) {
|
||||
case 1:
|
||||
return 'изменение';
|
||||
case 2:
|
||||
case 3:
|
||||
case 4:
|
||||
return 'изменения';
|
||||
default:
|
||||
return 'изменений';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Мигающая точка — визуальный индикатор офлайн-статуса.
|
||||
class _PulsingDot extends StatefulWidget {
|
||||
const _PulsingDot();
|
||||
|
||||
@override
|
||||
State<_PulsingDot> createState() => _PulsingDotState();
|
||||
}
|
||||
|
||||
class _PulsingDotState extends State<_PulsingDot>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late final AnimationController _ctrl;
|
||||
late final Animation<double> _anim;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_ctrl = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 800),
|
||||
)..repeat(reverse: true);
|
||||
_anim = Tween<double>(begin: 0.3, end: 1.0).animate(_ctrl);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_ctrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FadeTransition(
|
||||
opacity: _anim,
|
||||
child: Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: const BoxDecoration(
|
||||
color: Colors.white,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user