61 lines
2.0 KiB
Dart
61 lines
2.0 KiB
Dart
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import 'dart:developer' as dev;
|
|
import '../../domain/usecase/get_notifications_usecase.dart';
|
|
import '../event/notifications_event.dart';
|
|
import '../state/notifications_state.dart';
|
|
|
|
class NotificationsBloc extends Bloc<NotificationsEvent, NotificationsState> {
|
|
final GetNotificationsUsecase _getNotificationsUsecase;
|
|
|
|
NotificationsBloc(this._getNotificationsUsecase) : super(const NotificationsState()) {
|
|
on<NotificationsFetchRequested>(_onFetchRequested);
|
|
on<NotificationsLoadMoreRequested>(_onLoadMoreRequested);
|
|
}
|
|
|
|
Future<void> _onFetchRequested(
|
|
NotificationsFetchRequested event,
|
|
Emitter<NotificationsState> emit,
|
|
) async {
|
|
if (event.page == 1) {
|
|
emit(state.copyWith(status: NotificationsStatus.loading));
|
|
}
|
|
|
|
try {
|
|
final result = await _getNotificationsUsecase(
|
|
page: event.page,
|
|
pageSize: 100,
|
|
);
|
|
|
|
final newNotifications = event.page == 1
|
|
? result.notifications
|
|
: [...state.notifications, ...result.notifications];
|
|
|
|
emit(state.copyWith(
|
|
status: NotificationsStatus.success,
|
|
notifications: newNotifications,
|
|
currentPage: result.pagination.currentPage,
|
|
totalPages: result.pagination.lastPage,
|
|
hasMore: result.pagination.currentPage < result.pagination.lastPage,
|
|
isLoadingMore: false,
|
|
));
|
|
} catch (e) {
|
|
dev.log('NotificationsBloc: Ошибка загрузки: $e');
|
|
emit(state.copyWith(
|
|
status: event.page == 1 ? NotificationsStatus.failure : NotificationsStatus.success,
|
|
errorMessage: event.page == 1 ? e.toString() : null,
|
|
isLoadingMore: false,
|
|
));
|
|
}
|
|
}
|
|
|
|
Future<void> _onLoadMoreRequested(
|
|
NotificationsLoadMoreRequested event,
|
|
Emitter<NotificationsState> emit,
|
|
) async {
|
|
if (!state.hasMore || state.isLoadingMore) return;
|
|
|
|
emit(state.copyWith(isLoadingMore: true));
|
|
final nextPage = state.currentPage + 1;
|
|
add(NotificationsFetchRequested(page: nextPage));
|
|
}
|
|
} |