import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:laba1/presentation/home_page/bloc/state.dart'; import '../../../data/repositories/potter_repository.dart'; import 'events.dart'; class HomeBloc extends Bloc { final PotterRepository repo; HomeBloc(this.repo) : super(const HomeState()) { on(_onLoadData); } Future _onLoadData( HomeLoadDataEvent event, Emitter emit) async { if (event.nextPage == null) { emit(state.copyWith(isLoading: true)); } else { emit(state.copyWith(isPaginationLoading: true)); } String? error; final data = await repo.loadData( q: event.search, page: event.nextPage ?? 1, onError: (e) => error = e, ); data?.nextPage = data?.nextPage ?? (event.nextPage ?? 1); if (event.nextPage != null) { // Добавляем новые данные, пропуская дубликаты if (state.data != null) { for (var entity in data?.data ?? []) { if (!(state.data!.existingIds.contains(entity.id))) { state.data?.data?.add(entity); state.data?.existingIds.add(entity.id); } } } state.data?.nextPage = data?.nextPage; emit(state.copyWith( isLoading: false, isPaginationLoading: false, data: state.data, error: error, )); } else { emit(state.copyWith( isLoading: false, isPaginationLoading: false, data: data, error: error, )); } } }