import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:pmd_labs/data/repositories/album_repository.dart'; import 'package:pmd_labs/home_page/bloc/state.dart'; import '../home_page.dart'; import 'events.dart'; class HomeBloc extends Bloc { final AlbumRepository 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)); } try { final data = await repo.loadData(albumName: event.search, page: event.nextPage ?? 1); HomeData? updatedData; Set existingIds; if (event.nextPage != null && state.data != null) { final existingData = state.data!.data ?? []; final newDataList = data; existingIds = existingData.map((item) => item.id).toSet(); final newData = newDataList?.where((newItem) => !existingIds.contains(newItem.id)).toList(); updatedData = HomeData(data: [...existingData, ...?newData], nextPage: (event.nextPage ?? 1) + 1); } else { updatedData = HomeData(data: data, nextPage: (event.nextPage ?? 1) + 1); } emit(state.copyWith(data: updatedData, isLoading: false, isPaginationLoading: false)); } catch (e) { emit(state.copyWith(isLoading: false, isPaginationLoading: false)); print("Error loading data: $e"); } } }