47 lines
1.4 KiB
Dart
47 lines
1.4 KiB
Dart
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import 'package:flutter_project/data/repositories/anime_repository.dart';
|
|
import 'package:flutter_project/views/home_page/bloc/events.dart';
|
|
import 'package:flutter_project/views/home_page/bloc/state.dart';
|
|
|
|
class HomeBloc extends Bloc<HomeEvent, HomeState> {
|
|
final AnimeRepository repo;
|
|
|
|
HomeBloc(this.repo) : super(const HomeState()) {
|
|
on<HomeLoadDataEvent>(_onLoadData);
|
|
on<HomeShowButtonToTopEvent>(_onShowButton);
|
|
}
|
|
|
|
void _onShowButton(HomeShowButtonToTopEvent event, Emitter<HomeState> emit) {
|
|
if (event.isShown != null) {
|
|
if (event.isShown == true) {
|
|
emit(state.copyWith(isButtonToTopShown: true));
|
|
} else {
|
|
emit(state.copyWith(isButtonToTopShown: false));
|
|
}
|
|
}
|
|
}
|
|
|
|
Future<void> _onLoadData(HomeLoadDataEvent event, Emitter<HomeState> emit) async {
|
|
if (event.hasError != null && event.hasError == true) {
|
|
emit(state.copyWith(error: null));
|
|
}
|
|
|
|
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);
|
|
|
|
if (event.nextPage != null) {
|
|
data?.data?.insertAll(0, state.data?.data ?? []);
|
|
}
|
|
|
|
emit(state.copyWith(data: data, isLoading: false, isPaginationLoading: false, error: error));
|
|
}
|
|
}
|