import 'package:flutter_android_app/presentation/home_page/bloc/events.dart'; import 'package:flutter_android_app/presentation/home_page/bloc/state.dart'; import 'package:flutter_android_app/repositories/api_interface.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class HomeBloc extends Bloc { final ApiInterface repo; HomeBloc(this.repo) : super(const HomeState()) { on(_onLoadData); on(_onLoadFavouritesData); } Future _onLoadData(HomeLoadDataEvent event, Emitter emit) async { const int pageSize = 20; if (event.nextPage == null) { emit(state.copyWith( isLoading: true, error: 'NO_ERROR', )); } else { emit(state.copyWith(isPaginationLoading: true)); } String? error; final data = await repo.loadData( search: event.search, page: event.nextPage ?? 1, pageSize: pageSize, onError: (e) => error = e, locale: event.locale, currencyId: event.currencyId, ); bool isLastPage = false; if (data?.data != null && data!.data!.length < pageSize) { isLastPage = true; } if (event.nextPage != null) { data?.data?.insertAll(0, state.data?.data ?? []); } emit(state.copyWith( isLoading: false, isPaginationLoading: false, data: data, error: error, isAllPagesLoaded: isLastPage, )); } Future _onLoadFavouritesData(HomeLoadFavouritesDataEvent event, Emitter emit) async { const int pageSize = 10; if (event.nextPage == null) { emit(state.copyWith( isLoading: true, error: 'NO_ERROR', )); } else { emit(state.copyWith(isPaginationLoading: true)); } String? error; final data = await repo.loadDataWithIds( ids: event.ids ?? [], page: event.nextPage ?? 1, pageSize: pageSize, onError: (e) => error = e, locale: event.locale, currencyId: event.currencyId, ); bool isLastPage = false; if (data?.data != null && data!.data!.length < pageSize) { isLastPage = true; } if (event.nextPage != null) { data?.data?.insertAll(0, state.data?.data ?? []); } emit(state.copyWith( isLoading: false, isPaginationLoading: false, data: data, error: error, isAllPagesLoaded: isLastPage, )); } }