feat(marketing): added marketing bottom sheet

This commit is contained in:
misha
2025-10-23 17:25:12 +03:00
parent ce0099c385
commit 41313f09af
19 changed files with 309 additions and 19 deletions

View File

@@ -1,4 +1,5 @@
import 'package:eatvio_app/core/app_initializer.dart';
import 'package:eatvio_app/core/cubit/marketing/marketing_cubit.dart';
import 'package:eatvio_app/core/env_config.dart';
import 'package:eatvio_app/core/internet_connection_cubit/internet_connection_cubit.dart';
import 'package:eatvio_app/core/locator_service.dart';
@@ -40,6 +41,7 @@ class AppConfig {
BlocProvider<ChatsCubit>(create: (context) => sl<ChatsCubit>()..getChatRoomsWithLoading()),
BlocProvider<ViewsCubit>(create: (context) => sl<ViewsCubit>()),
BlocProvider<InternetConnectionCubit>(lazy: false, create: (context) => sl<InternetConnectionCubit>()),
BlocProvider<MarketingCubit>(create: (context) => sl<MarketingCubit>()),
];
/// Делегаты локализации

View File

@@ -0,0 +1,29 @@
import 'package:eatvio_app/core/cubit/marketing/marketing_cubit_state.dart';
import 'package:eatvio_app/core/prefs.dart';
import 'package:eatvio_app/core/prefs_keys.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class MarketingCubit extends Cubit<MarketingCubitState> {
final Prefs prefs;
MarketingCubit(this.prefs) : super(const MarketingCubitState());
Future<bool> checkRegistrationDate() async {
try {
final milliseconds = prefs.getInt(PrefsKeys.registrationDate);
final marketingBottomSheetHasBeenShown = prefs.getBool(PrefsKeys.marketingBottomSheetHasBeenShown);
if (milliseconds == null || marketingBottomSheetHasBeenShown == true) {
return false;
}
final date = DateTime.fromMillisecondsSinceEpoch(milliseconds);
final today = DateTime.now();
final daysCount = today.difference(date).inDays;
final needToShowMarketingBottomSheet = daysCount >= 14;
if (needToShowMarketingBottomSheet) {
await prefs.setBool(PrefsKeys.marketingBottomSheetHasBeenShown, true);
}
return needToShowMarketingBottomSheet;
} catch (e) {
rethrow;
}
}
}

View File

@@ -0,0 +1,3 @@
class MarketingCubitState {
const MarketingCubitState();
}

View File

@@ -1,3 +1,4 @@
import 'package:eatvio_app/core/cubit/marketing/marketing_cubit.dart';
import 'package:eatvio_app/core/internet_connection_cubit/internet_connection_cubit.dart';
import 'package:eatvio_app/core/views/cubit/views_cubit.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart';
@@ -74,10 +75,10 @@ class CubitRegistrations {
static void _registerFactoryCubits() {
// Auth related cubits
sl.registerFactory<AuthCubit>(() => AuthCubit(authRepository: sl()));
sl.registerFactory<RegistrationCubit>(() => RegistrationCubit(registrationRepository: sl()));
sl.registerFactory<RegistrationCubit>(() => RegistrationCubit(registrationRepository: sl(), prefs: sl()));
sl.registerFactory<ResetPasswordCubit>(() => ResetPasswordCubit(resetPasswordRepository: sl()));
sl.registerFactory<VerifyEmailCubit>(() => VerifyEmailCubit(profileRepository: sl()));
sl.registerFactory<OAuthCubit>(() => OAuthCubit(authRepository: sl()));
sl.registerFactory<OAuthCubit>(() => OAuthCubit(authRepository: sl(), prefs: sl()));
// Feed related cubits
sl.registerFactory<FeedCubit>(() => FeedCubit(feedRepository: sl()));
sl.registerFactory<RecipesCubit>(() => RecipesCubit(feedRepository: sl(), recipeRepository: sl(), aboutRecipeRepository: sl()));
@@ -143,5 +144,6 @@ class CubitRegistrations {
sl.registerFactory<ViewsCubit>(() => ViewsCubit(viewsRepository: sl()));
sl.registerFactory<UserDetailsCubit>(() => UserDetailsCubit(profileRepository: sl()));
sl.registerFactory<MenuCubit>(() => MenuCubit(sl()));
sl.registerFactory<MarketingCubit>(() => MarketingCubit(sl()));
}
}

View File

@@ -0,0 +1,11 @@
import 'package:eatvio_app/core/prefs.dart';
import 'package:eatvio_app/core/prefs_keys.dart';
mixin RegistrationDateCacheMixin {
late final Prefs prefs;
Future<void> cacheRegistrationDate(DateTime date) async {
await prefs.setInt(PrefsKeys.registrationDate, date.millisecondsSinceEpoch);
}
}

View File

@@ -1 +1 @@
enum PrefsKeys { hasAnonymousTokenBeenSent, welcomeScreenWasShowed }
enum PrefsKeys { hasAnonymousTokenBeenSent, welcomeScreenWasShowed, registrationDate, marketingBottomSheetHasBeenShown }

View File

@@ -249,4 +249,10 @@ abstract class TextStyles {
fontWeight: FontWeight.w500,
height: 1.255,
);
static const textFS24FW700 = TextStyle(
fontSize: 24,
fontWeight: FontWeight.w700,
height: 1.255,
);
}

View File

@@ -141,6 +141,8 @@ class PrimaryColors {
Color get gray60003 => const Color(0XFF707070);
Color get gray60005 => const Color(0xFF6C7C93);
// Green
Color get greenA700 => const Color(0XFF019A3E);

View File

@@ -0,0 +1,124 @@
import 'package:eatvio_app/core/theme/custom_text_style.dart';
import 'package:eatvio_app/core/theme/theme_helper.dart';
import 'package:eatvio_app/core/widgets/custom_outlined_button.dart';
import 'package:eatvio_app/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:share_plus/share_plus.dart';
void showMarketingBottomSheet(BuildContext context) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => Container(
margin: EdgeInsets.only(left: 8, right: 8, bottom: MediaQuery.of(context).viewInsets.bottom + MediaQuery.of(context).padding.bottom + 20),
decoration: BoxDecoration(borderRadius: BorderRadius.circular(12), color: appTheme.whiteA700),
child: const MarketingBottomSheet(),
),
);
}
class MarketingBottomSheet extends StatelessWidget {
const MarketingBottomSheet({super.key});
@override
Widget build(BuildContext context) {
final s = S.of(context);
return Padding(
padding: const EdgeInsetsGeometry.all(4),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Container(
height: 180,
width: double.infinity,
decoration: const BoxDecoration(
image: DecorationImage(image: AssetImage('assets/images/logo_bg.png'), fit: BoxFit.cover),
),
child: Center(child: SvgPicture.asset('assets/icons/logo_2.svg', height: 90)),
),
),
const SizedBox(height: 16),
Text(s.congratulations, style: TextStyles.textFS24FW700.copyWith(color: appTheme.blueA400)),
const SizedBox(height: 12),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Container(
decoration: BoxDecoration(color: appTheme.lightGray0, borderRadius: BorderRadius.circular(20)),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 20),
child: Row(
children: [
const Spacer(),
Container(
decoration: BoxDecoration(shape: BoxShape.circle, color: appTheme.blueA400),
padding: const EdgeInsets.all(8),
child: Text('14', style: TextStyles.textFS24FW700.copyWith(color: appTheme.whiteA700)),
),
const SizedBox(width: 12),
RichText(
text: TextSpan(
text: s.youWithUs,
style: TextStyles.textSMedium.copyWith(color: appTheme.gray60005),
children: [
TextSpan(
text: s.fourteenDays,
style: TextStyles.textLMedium.copyWith(color: appTheme.black),
),
],
),
),
const Spacer(),
],
),
),
),
),
const SizedBox(height: 12),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Text(
s.weAreLookingFor,
textAlign: TextAlign.center,
style: TextStyles.textMMediumAuto.copyWith(color: appTheme.black),
),
),
Text(
s.letsInvite,
textAlign: TextAlign.center,
style: TextStyles.textMMediumAuto.copyWith(color: appTheme.black),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 4),
child: CustomOutlinedButton(
text: s.invite,
height: 52,
buttonTextStyle: TextStyles.textMSemibold.copyWith(color: appTheme.whiteA700),
leftIcon: Padding(
padding: const EdgeInsets.only(right: 12),
child: Transform.rotate(
angle: 3.14,
child: SvgPicture.asset('assets/icons/share.svg', width: 14, height: 14, colorFilter: ColorFilter.mode(appTheme.whiteA700, BlendMode.srcIn)),
),
),
buttonStyle: ButtonStyle(side: const WidgetStatePropertyAll(BorderSide.none), backgroundColor: WidgetStatePropertyAll(appTheme.blueA400)),
onPressed: () async {
SharePlus.instance.share(ShareParams(uri: Uri.parse('https://promo.eatvio.ru/')));
},
),
),
Text(
s.eatvioIsAHelthyHabbit,
textAlign: TextAlign.center,
style: TextStyles.textSMedium.copyWith(color: appTheme.blueA400),
),
const SizedBox(height: 16),
],
),
);
}
}

View File

@@ -1,14 +1,18 @@
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:eatvio_app/core/mixins/registration_date_cache_mixin.dart';
import 'package:eatvio_app/core/prefs.dart';
import 'package:eatvio_app/core/token_storage.dart';
import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_state.dart';
import 'package:eatvio_app/features/auth/repositories/auth_repository.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class OAuthCubit extends Cubit<OAuthState> {
class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
final AuthRepository authRepository;
OAuthCubit({required this.authRepository}) : super(const OAuthState());
OAuthCubit({required this.authRepository, required Prefs prefs}) : super(const OAuthState()) {
this.prefs = prefs;
}
Future<void> signInViaSocialMedia({required String provider, required String accessToken, required String refreshToken, required String clientId}) async {
try {
@@ -63,6 +67,7 @@ class OAuthCubit extends Cubit<OAuthState> {
clientId: clientId,
);
TokenStorage.saveTokenInStorage(token);
cacheRegistrationDate(DateTime.now());
emit(OAuthState.loaded(token: token));
} on DioException catch (e) {
emit(OAuthState.error(errorMessage: e.toString()));

View File

@@ -1,9 +1,11 @@
import 'package:easy_debounce/easy_debounce.dart';
import 'package:eatvio_app/app_keys.dart';
import 'package:eatvio_app/core/const.dart';
import 'package:eatvio_app/core/cubit/marketing/marketing_cubit.dart';
import 'package:eatvio_app/core/views/cubit/views_cubit.dart';
import 'package:eatvio_app/core/widgets/add_item_button.dart';
import 'package:eatvio_app/core/widgets/custom_search_bar.dart';
import 'package:eatvio_app/core/widgets/marketing_bottom_sheet.dart';
import 'package:eatvio_app/features/create_diet/presentation/create_diet_screen.dart';
import 'package:eatvio_app/features/create_plan/presentation/create_plan_screen.dart';
import 'package:eatvio_app/features/feed/presentation/bloc/consultants_cubit/consultants_cubit.dart';
@@ -71,6 +73,7 @@ class _FeedScreenContentState extends State<FeedScreenContent> {
void initState() {
chipsLabelList = hidePlans ? ['Все', 'Рецепты', 'Диеты', 'Консультанты'] : ['Все', 'Рецепты', 'Диеты', 'Планы питания', 'Консультанты'];
consultantsScrollController.addListener(_onScrollConsultants);
_checkRegistrationDate(context);
super.initState();
}
@@ -78,6 +81,15 @@ class _FeedScreenContentState extends State<FeedScreenContent> {
if (consultantsScrollController.offset >= consultantsScrollController.position.maxScrollExtent && !consultantsScrollController.position.outOfRange) {}
}
void _checkRegistrationDate(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback((_) async {
final needToShowMarketingBottomSheet = await context.read<MarketingCubit>().checkRegistrationDate();
if (needToShowMarketingBottomSheet && context.mounted) {
showMarketingBottomSheet(context);
}
});
}
@override
void dispose() {
blogPostsScrollController.dispose();

View File

@@ -3,6 +3,8 @@ import 'dart:developer';
import 'package:eatvio_app/core/app_router.dart';
import 'package:eatvio_app/core/firebase_api.dart';
import 'package:eatvio_app/core/locator_service.dart';
import 'package:eatvio_app/core/mixins/registration_date_cache_mixin.dart';
import 'package:eatvio_app/core/prefs.dart';
import 'package:eatvio_app/core/token_storage.dart';
import 'package:eatvio_app/features/registration/models/user_registration_model.dart';
@@ -12,10 +14,9 @@ import 'package:eatvio_app/features/registration/services/registration_analytics
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
class RegistrationCubit extends Cubit<RegistrationState> {
class RegistrationCubit extends Cubit<RegistrationState> with RegistrationDateCacheMixin {
final RegistrationRepository registrationRepository;
RegistrationCubit({required this.registrationRepository})
RegistrationCubit({required this.registrationRepository, required Prefs prefs})
: super(
const RegistrationState(
sheet: UserRegistrationSheet(
@@ -47,7 +48,9 @@ class RegistrationCubit extends Cubit<RegistrationState> {
phone: '',
),
),
);
) {
this.prefs = prefs;
}
void updateSheet(UserRegistrationSheet sheet) => emit(RegistrationState(sheet: sheet));
@@ -59,6 +62,7 @@ class RegistrationCubit extends Cubit<RegistrationState> {
await TokenStorage.saveTokenInStorage(token);
await sl<FirebaseApi>().registerPushToken();
RegistrationAnalyticsService.reportRegistrationComplete();
cacheRegistrationDate(DateTime.now());
AppRouter.navigatorKey.currentContext?.replaceNamed('verifyEmailScreen');
} catch (e, st) {
log(e.toString(), stackTrace: st);

View File

@@ -199,6 +199,7 @@ class MessageLookup extends MessageLookupByLibrary {
"congratsYouHaveFinishedPlan": MessageLookupByLibrary.simpleMessage(
"Поздравляем, Вы закончили план",
),
"congratulations": MessageLookupByLibrary.simpleMessage("Поздравляем!"),
"consultantLeftComment": m0,
"consultations_count": MessageLookupByLibrary.simpleMessage(
"Кол-во проведенных консулдьтаций",
@@ -305,6 +306,9 @@ class MessageLookup extends MessageLookupByLibrary {
"eating_behavior_type_desc": MessageLookupByLibrary.simpleMessage(
"Формирование здорового пищевого поведения — это процесс, который включает в себя изменение привычек и отношения к еде. Он направлен на то, чтобы помочь людям научиться правильно питаться и поддерживать здоровый образ жизни.Основные принципы формирования здорового пищевого поведения: \n● Разнообразие продуктов; \n● Сбалансированный рацион; \n● Питьевой режим; \n● Ограничение вредных продуктов; \n● Регулярные приёмы пищи; \n● Умеренность;Осознанное питание; \n● Физическая активность;",
),
"eatvioIsAHelthyHabbit": MessageLookupByLibrary.simpleMessage(
"Итвио — это полезная привычка",
),
"economy": MessageLookupByLibrary.simpleMessage("Эконом"),
"edit": MessageLookupByLibrary.simpleMessage("Редактировать"),
"email": MessageLookupByLibrary.simpleMessage("Электронная почта"),
@@ -378,6 +382,7 @@ class MessageLookup extends MessageLookupByLibrary {
"for_whole_period_of_time": MessageLookupByLibrary.simpleMessage(
"За всё время",
),
"fourteenDays": MessageLookupByLibrary.simpleMessage("14 дней"),
"fraud": MessageLookupByLibrary.simpleMessage("Мошенничество"),
"fraud_description": MessageLookupByLibrary.simpleMessage(
"Мошенничество с целью наживы. Если вас обманули, пожалуйста, сообщите об этом в правоохранительные органы.",
@@ -418,6 +423,7 @@ class MessageLookup extends MessageLookupByLibrary {
"initial_measurements": MessageLookupByLibrary.simpleMessage(
"Первичные замеры",
),
"invite": MessageLookupByLibrary.simpleMessage("Пригласить"),
"invited_people_count": MessageLookupByLibrary.simpleMessage(
"Количество приглашенных",
),
@@ -440,6 +446,9 @@ class MessageLookup extends MessageLookupByLibrary {
"leaveComplainRequest": MessageLookupByLibrary.simpleMessage(
"Подать жалобу",
),
"letsInvite": MessageLookupByLibrary.simpleMessage(
"Давайте пригласим близких в итвио",
),
"light_type": MessageLookupByLibrary.simpleMessage("Легкая"),
"light_type_desc": MessageLookupByLibrary.simpleMessage(
"С некоторыми видами диет можно употреблять алкоголь в умеренных количествах. Рекомендуется совмещать вместе с низкокалорийными закусками.",
@@ -773,6 +782,9 @@ class MessageLookup extends MessageLookupByLibrary {
"want_to_see_tomorrow": MessageLookupByLibrary.simpleMessage(
"Хотите заглянуть в будущее?",
),
"weAreLookingFor": MessageLookupByLibrary.simpleMessage(
"Мы собираем самое большое сообщество людей, желающих вести здоровый образ жизни!",
),
"weapon": MessageLookupByLibrary.simpleMessage("Оружие"),
"weight": MessageLookupByLibrary.simpleMessage("Вес"),
"weight_chart": MessageLookupByLibrary.simpleMessage("График веса"),
@@ -801,6 +813,7 @@ class MessageLookup extends MessageLookupByLibrary {
"youShureYouWantToDeleteAccount": MessageLookupByLibrary.simpleMessage(
"Вы уверены, что хотите удалить аккаунт?",
),
"youWithUs": MessageLookupByLibrary.simpleMessage("Вы с итвио уже\n"),
"you_can_not_open_this_day": MessageLookupByLibrary.simpleMessage(
"Вы не можете перейти в этот день",
),

View File

@@ -28,10 +28,9 @@ class S {
static const AppLocalizationDelegate delegate = AppLocalizationDelegate();
static Future<S> load(Locale locale) {
final name =
(locale.countryCode?.isEmpty ?? false)
? locale.languageCode
: locale.toString();
final name = (locale.countryCode?.isEmpty ?? false)
? locale.languageCode
: locale.toString();
final localeName = Intl.canonicalizedLocale(name);
return initializeMessages(localeName).then((_) {
Intl.defaultLocale = localeName;
@@ -3499,6 +3498,66 @@ class S {
args: [],
);
}
/// `Поздравляем!`
String get congratulations {
return Intl.message(
'Поздравляем!',
name: 'congratulations',
desc: '',
args: [],
);
}
/// `Вы с итвио уже\n`
String get youWithUs {
return Intl.message(
'Вы с итвио уже\n',
name: 'youWithUs',
desc: '',
args: [],
);
}
/// `14 дней`
String get fourteenDays {
return Intl.message('14 дней', name: 'fourteenDays', desc: '', args: []);
}
/// `Мы собираем самое большое сообщество людей, желающих вести здоровый образ жизни!`
String get weAreLookingFor {
return Intl.message(
'Мы собираем самое большое сообщество людей, желающих вести здоровый образ жизни!',
name: 'weAreLookingFor',
desc: '',
args: [],
);
}
/// `Давайте пригласим близких в итвио`
String get letsInvite {
return Intl.message(
'Давайте пригласим близких в итвио',
name: 'letsInvite',
desc: '',
args: [],
);
}
/// `Итвио — это полезная привычка`
String get eatvioIsAHelthyHabbit {
return Intl.message(
'Итвио — это полезная привычка',
name: 'eatvioIsAHelthyHabbit',
desc: '',
args: [],
);
}
/// `Пригласить`
String get invite {
return Intl.message('Пригласить', name: 'invite', desc: '', args: []);
}
}
class AppLocalizationDelegate extends LocalizationsDelegate<S> {

View File

@@ -414,6 +414,13 @@
"delete": "Удалить",
"cannotDeleteAccount": "Не получилось удалить ваш аккаунт",
"resend": "Отправить повторно",
"notifications": "Уведомления"
"notifications": "Уведомления",
"congratulations": "Поздравляем!",
"youWithUs": "Вы с итвио уже\n",
"fourteenDays": "14 дней",
"weAreLookingFor": "Мы собираем самое большое сообщество людей, желающих вести здоровый образ жизни!",
"letsInvite": "Давайте пригласим близких в итвио",
"eatvioIsAHelthyHabbit": "Итвио — это полезная привычка",
"invite": "Пригласить"
}