2024-12-04 13:22:22 +04:00

47 lines
1.2 KiB
Dart

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pmu/data/repositories/cats_repository.dart';
import 'package:pmu/presentation/home_page/bloc/events.dart';
import 'package:pmu/presentation/home_page/bloc/state.dart';
class HomeBloc extends Bloc<HomeEvent, HomeState> {
final CatsRepository repo;
HomeBloc(this.repo) : super(const HomeState()) {
on<HomeLoadDataEvent>(_onLoadData);
}
Future<void> _onLoadData(HomeLoadDataEvent event, Emitter<HomeState> emit) async {
if (event.offset == 0) {
emit(state.copyWith(isLoading: true));
} else {
emit(state.copyWith(isPaginationLoading: true));
}
String? error;
final data = await repo.loadData(
q: event.search,
onError: (e) => error = e,
offset: event.offset,
);
if (data != null) {
final updatedData = (event.offset == 0
? data.data
: [...state.data?.data ?? [], ...data.data ?? []]);
emit(state.copyWith(
isLoading: false,
isPaginationLoading: false,
data: HomeData(data: updatedData),
error: error,
));
} else {
emit(state.copyWith(
isLoading: false,
isPaginationLoading: false,
error: error,
));
}
}
}