52 lines
1.3 KiB
Dart
52 lines
1.3 KiB
Dart
import 'dart:async';
|
|
|
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import 'package:pmu/data/repositories/api_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 ApiRepository repository;
|
|
|
|
HomeBloc(this.repository) : super(const HomeState()) {
|
|
on<HomeLoadDataEvent>(_onLoadData);
|
|
}
|
|
|
|
Future<void> _onLoadData(
|
|
HomeLoadDataEvent event, Emitter<HomeState> emit) async {
|
|
|
|
if (event.pageNumber == event.lastPageNumber && event.pageNumber != null) {
|
|
emit(state.copyWith(
|
|
isLoading: false,
|
|
isPaginationLoading: false,
|
|
));
|
|
return;
|
|
}
|
|
|
|
if (event.nextPageNumber == null) {
|
|
emit(state.copyWith(isLoading: true));
|
|
} else {
|
|
emit(state.copyWith(isPaginationLoading: true));
|
|
}
|
|
|
|
String? error;
|
|
|
|
final data = await repository.loadData(
|
|
q: event.search,
|
|
pageNumber: event.nextPageNumber ?? 0,
|
|
onError: (e) => error = e,
|
|
);
|
|
|
|
if (event.nextPageNumber != null) {
|
|
data?.data?.insertAll(0, state.data?.data ?? []);
|
|
}
|
|
|
|
emit(state.copyWith(
|
|
isLoading: false,
|
|
isPaginationLoading: false,
|
|
data: data,
|
|
error: error,
|
|
));
|
|
}
|
|
}
|