40 lines
1.1 KiB
Dart
40 lines
1.1 KiB
Dart
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import 'package:test_app/data/repository/potter_repository.dart';
|
|
import 'package:test_app/domain/home.dart';
|
|
import 'package:test_app/view/home_page/bloc/events.dart';
|
|
import 'package:test_app/view/home_page/bloc/state.dart';
|
|
|
|
class HomeBloc extends Bloc<HomeEvent, HomeState> {
|
|
final PotterRepository repository;
|
|
|
|
HomeBloc(this.repository) : super(const HomeState()) {
|
|
on<HomeLoadDataEvent>(_onLoadData);
|
|
}
|
|
|
|
void _onLoadData(HomeLoadDataEvent event, Emitter<HomeState> emit) async {
|
|
final nextPage = event.nextPage ?? 1;
|
|
|
|
emit(state.copyWith(
|
|
isLoading: true,
|
|
data: nextPage == 1 ? HomeData() : null,
|
|
));
|
|
|
|
String? error;
|
|
|
|
final data = await repository.loadData(
|
|
q: event.search,
|
|
page: nextPage,
|
|
onError: (e) => error = e,
|
|
);
|
|
|
|
final isNextPage = data?.nextPage != null;
|
|
|
|
if (nextPage > 1) {
|
|
data?.data?.insertAll(0, state.data?.data ?? []);
|
|
}
|
|
|
|
emit(state.copyWith(
|
|
isLoading: false, data: isNextPage ? data : null, error: error));
|
|
}
|
|
}
|