Skip to content

Commit

Permalink
утилитарный метод для показа диалоговых окон
Browse files Browse the repository at this point in the history
- если возникла аномальная авторизация,
теперь выводится алерт вместо снэкбара
- переименован метод вызова снэкбара
- фикс: слушатель, который вызывает уведомление об
аномальной авторизации перенесен на страницу
дашборда, чтобы избежать дублирования окон
  • Loading branch information
iska9der committed Nov 15, 2023
1 parent 0afb1f8 commit afc38f1
Show file tree
Hide file tree
Showing 16 changed files with 95 additions and 51 deletions.
6 changes: 3 additions & 3 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
"version": "0.2.0",
"configurations": [
{
"name": "flabr",
"name": "debug",
"request": "launch",
"type": "dart"
},
{
"name": "flabr (profile mode)",
"name": "profile",
"request": "launch",
"type": "dart",
"flutterMode": "profile"
},
{
"name": "flabr (release mode)",
"name": "release",
"request": "launch",
"type": "dart",
"flutterMode": "release"
Expand Down
38 changes: 37 additions & 1 deletion lib/common/utils/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class Utils with ImageUtilsMixin {

final AppRouter router;

void showNotification({
void showSnack({
required BuildContext context,
required Widget content,
SnackBarAction? action,
Expand All @@ -24,4 +24,40 @@ class Utils with ImageUtilsMixin {
),
);
}

Future showAlert({
required BuildContext context,
required Widget content,
required List<Widget>? Function(BuildContext context) actions,
bool isDismissible = true,
}) async {
return await showDialog(
context: context,
barrierDismissible: isDismissible,
useSafeArea: true,
useRootNavigator: true,
builder: (context) {
final localActions = actions(context);

return WillPopScope(
onWillPop: () async => isDismissible,
child: AlertDialog.adaptive(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text('Внимание'),
if (isDismissible)
IconButton(
onPressed: () => Navigator.of(context).pop(),
icon: const Icon(Icons.close),
),
],
),
content: content,
actions: localActions,
),
);
},
);
}
}
2 changes: 1 addition & 1 deletion lib/common/widget/article_list_sliver.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class ArticleListSliver extends StatelessWidget {
listenWhen: (p, c) =>
p.page != 1 && c.status == ArticleListStatus.failure,
listener: (c, state) {
getIt.get<Utils>().showNotification(
getIt.get<Utils>().showSnack(
context: context,
content: Text(state.error),
);
Expand Down
22 changes: 0 additions & 22 deletions lib/feature/article/page/article_list_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../common/model/extension/enum_status.dart';
import '../../../common/utils/utils.dart';
import '../../../common/widget/article_list_sliver.dart';
import '../../../component/di/dependencies.dart';
import '../../../config/constants.dart';
Expand Down Expand Up @@ -74,27 +73,6 @@ class ArticleListView extends StatelessWidget {

return MultiBlocListener(
listeners: [
/// Выводим снэкбар об ошибке, если возникла ошибка при получении
/// данных о вошедшем юзере. Ошибка возникает, если при логине
/// пришел некорректный connectSSID и [AuthCubit.fetchMe()]
/// вернул null
BlocListener<AuthCubit, AuthState>(
listenWhen: (p, c) => p.isAuthorized && c.isAnomaly,
listener: (c, state) {
getIt.get<Utils>().showNotification(
context: context,
content: const Text(
'Возникла неизвестная ошибка при авторизации',
),
action: SnackBarAction(
label: 'Выйти',
onPressed: () => context.read<AuthCubit>().logOut(),
),
duration: const Duration(seconds: 5),
);
},
),

/// Если пользователь вошел, надо переполучить статьи
BlocListener<AuthCubit, AuthState>(
listenWhen: (p, c) => p.status.isLoading && c.isAuthorized,
Expand Down
2 changes: 1 addition & 1 deletion lib/feature/article/widget/article_footer_widget.dart
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ class _BookmarkIconButton extends StatelessWidget {
child: BlocConsumer<BookmarkCubit, BookmarkState>(
listenWhen: (p, c) => c.status.isFailure,
listener: (context, state) {
getIt.get<Utils>().showNotification(
getIt.get<Utils>().showSnack(
context: context,
content: Text(state.error),
);
Expand Down
2 changes: 1 addition & 1 deletion lib/feature/auth/cubit/auth_cubit.dart
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class AuthCubit extends Cubit<AuthState> {
emit(state.copyWith(status: AuthStatus.authorized, data: authData));
}

logOut() async {
Future<void> logOut() async {
emit(state.copyWith(status: AuthStatus.loading));

await _tokenRepository.clearAll();
Expand Down
2 changes: 1 addition & 1 deletion lib/feature/auth/widget/login_widget.dart
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ class _WebViewLoginState extends State<_WebViewLogin> {
listenWhen: (_, current) => current.status.isFailure,
listener: (context, state) {
_clearControllerData();
getIt.get<Utils>().showNotification(
getIt.get<Utils>().showSnack(
context: context,
content: Text(state.error),
duration: const Duration(seconds: 5),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class SubscribeButton extends StatelessWidget {
child: BlocListener<SubscriptionCubit, SubscriptionState>(
listenWhen: (p, c) => p.status.isFailure,
listener: (context, state) {
getIt.get<Utils>().showNotification(
getIt.get<Utils>().showSnack(
context: context,
content: Text(state.error),
);
Expand Down
2 changes: 1 addition & 1 deletion lib/feature/company/page/company_list_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ class CompanyListPageView extends StatelessWidget {
listenWhen: (p, c) =>
p.page != 1 && c.status == CompanyListStatus.failure,
listener: (c, state) {
getIt.get<Utils>().showNotification(
getIt.get<Utils>().showSnack(
context: context,
content: Text(state.error),
);
Expand Down
2 changes: 1 addition & 1 deletion lib/feature/hub/page/hub_list_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ class HubListPageView extends StatelessWidget {
listenWhen: (p, c) =>
p.page != 1 && c.status == HubListStatus.failure,
listener: (c, state) {
getIt.get<Utils>().showNotification(
getIt.get<Utils>().showSnack(
context: context,
content: Text(state.error),
);
Expand Down
2 changes: 1 addition & 1 deletion lib/feature/search/page/search_anywhere.dart
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ class SearchAnywhereDelegate extends FlabrSearchDelegate {
bloc: cubit,
listenWhen: (p, c) => p.page != 1 && c.status.isFailure,
listener: (c, state) {
getIt.get<Utils>().showNotification(
getIt.get<Utils>().showSnack(
context: context,
content: Text(state.error),
);
Expand Down
2 changes: 1 addition & 1 deletion lib/feature/user/page/user_detail_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ class UserDetailPageView extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: model.workplace.map((e) {
return TextButton(
onPressed: () => getIt.get<Utils>().showNotification(
onPressed: () => getIt.get<Utils>().showSnack(
context: context,
content: const Text('Здесь так тихо...'),
),
Expand Down
2 changes: 1 addition & 1 deletion lib/feature/user/page/user_list_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class UserListPageView extends StatelessWidget {
listenWhen: (p, c) =>
p.page != 1 && c.status == UserListStatus.failure,
listener: (context, state) {
getIt.get<Utils>().showNotification(
getIt.get<Utils>().showSnack(
context: context,
content: Text(state.error),
);
Expand Down
6 changes: 2 additions & 4 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -121,12 +121,10 @@ class MyApp extends StatelessWidget {
},
child: MaterialApp.router(
title: 'Flabr',
theme: state.isDarkTheme ? darkTheme() : lightTheme(),
routerConfig: router.config(
deepLinkBuilder: (deepLink) {
return const DeepLink.path('/');
},
deepLinkBuilder: (_) => const DeepLink.path('/'),
),
theme: state.isDarkTheme ? darkTheme() : lightTheme(),
),
);
},
Expand Down
52 changes: 42 additions & 10 deletions lib/page/dashboard_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../common/utils/utils.dart';
import '../component/di/dependencies.dart';
import '../component/router/app_router.dart';
import '../config/constants.dart';
import '../feature/auth/cubit/auth_cubit.dart';
import '../feature/settings/cubit/settings_cubit.dart';

@RoutePage(name: DashboardPage.routeName)
Expand Down Expand Up @@ -35,16 +38,45 @@ class _DashboardPageState extends State<DashboardPage> {

@override
Widget build(BuildContext context) {
return BlocListener<SettingsCubit, SettingsState>(
listenWhen: (previous, current) =>
previous.miscConfig.navigationOnScrollVisible !=
current.miscConfig.navigationOnScrollVisible,
listener: (context, state) {
visibleOnScroll = state.miscConfig.navigationOnScrollVisible;
if (visibleOnScroll) {
barHeight.value = themeHeight;
}
},
return MultiBlocListener(
listeners: [
BlocListener<SettingsCubit, SettingsState>(
listenWhen: (previous, current) =>
previous.miscConfig.navigationOnScrollVisible !=
current.miscConfig.navigationOnScrollVisible,
listener: (context, state) {
visibleOnScroll = state.miscConfig.navigationOnScrollVisible;
if (visibleOnScroll) {
barHeight.value = themeHeight;
}
},
),

/// Выводим уведомление об ошибке, если возникла ошибка при получении
/// данных о вошедшем юзере. Ошибка возникает, если при логине
/// пришел некорректный connectSSID и [AuthCubit.fetchMe()]
/// вернул null
BlocListener<AuthCubit, AuthState>(
listenWhen: (p, c) => p.isAuthorized && c.isAnomaly,
listener: (context, state) {
getIt.get<Utils>().showAlert(
context: context,
content: const Text(
'Возникла неизвестная ошибка при авторизации',
),
actions: (context) => [
TextButton(
child: const Text('Выйти из аккаунта'),
onPressed: () {
context.read<AuthCubit>().logOut();
Navigator.of(context).pop();
},
),
],
);
},
),
],
child: NotificationListener<UserScrollNotification>(
onNotification: (notification) {
if (visibleOnScroll) {
Expand Down
2 changes: 1 addition & 1 deletion lib/page/settings_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ class _ConnectSidWidgetState extends State<ConnectSidWidget> {
Clipboard.setData(
ClipboardData(text: controller.text),
);
getIt.get<Utils>().showNotification(
getIt.get<Utils>().showSnack(
context: context,
content: const Text(
'Скопировано в буфер обмена',
Expand Down

0 comments on commit afc38f1

Please sign in to comment.