feat: customer page
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
import 'package:dartz/dartz.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:injectable/injectable.dart';
|
||||
|
||||
import '../../../domain/customer/customer.dart';
|
||||
|
||||
part 'customer_loader_event.dart';
|
||||
part 'customer_loader_state.dart';
|
||||
part 'customer_loader_bloc.freezed.dart';
|
||||
|
||||
@injectable
|
||||
class CustomerLoaderBloc
|
||||
extends Bloc<CustomerLoaderEvent, CustomerLoaderState> {
|
||||
final ICustomerRepository _repository;
|
||||
CustomerLoaderBloc(this._repository) : super(CustomerLoaderState.initial()) {
|
||||
on<CustomerLoaderEvent>(_onCustomerLoaderEvent);
|
||||
}
|
||||
|
||||
Future<void> _onCustomerLoaderEvent(
|
||||
CustomerLoaderEvent event,
|
||||
Emitter<CustomerLoaderState> emit,
|
||||
) {
|
||||
return event.map(
|
||||
searchChanged: (e) async {
|
||||
emit(state.copyWith(search: e.search));
|
||||
},
|
||||
fetched: (e) async {
|
||||
var newState = state;
|
||||
|
||||
if (e.isRefresh) {
|
||||
newState = state.copyWith(isFetching: true);
|
||||
|
||||
emit(newState);
|
||||
}
|
||||
|
||||
newState = await _mapFetchedToState(state, isRefresh: e.isRefresh);
|
||||
|
||||
emit(newState);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<CustomerLoaderState> _mapFetchedToState(
|
||||
CustomerLoaderState state, {
|
||||
bool isRefresh = false,
|
||||
}) async {
|
||||
state = state.copyWith(isFetching: false);
|
||||
|
||||
if (state.hasReachedMax && state.customers.isNotEmpty && !isRefresh) {
|
||||
return state;
|
||||
}
|
||||
|
||||
if (isRefresh) {
|
||||
state = state.copyWith(
|
||||
page: 1,
|
||||
failureOptionCustomer: none(),
|
||||
hasReachedMax: false,
|
||||
customers: [],
|
||||
);
|
||||
}
|
||||
|
||||
final failureOrCustomer = await _repository.get(
|
||||
page: state.page,
|
||||
search: state.search,
|
||||
);
|
||||
|
||||
state = failureOrCustomer.fold(
|
||||
(f) {
|
||||
if (state.customers.isNotEmpty) {
|
||||
return state.copyWith(hasReachedMax: true);
|
||||
}
|
||||
return state.copyWith(failureOptionCustomer: optionOf(f));
|
||||
},
|
||||
(customers) {
|
||||
return state.copyWith(
|
||||
customers: List.from(state.customers)..addAll(customers),
|
||||
failureOptionCustomer: none(),
|
||||
page: state.page + 1,
|
||||
hasReachedMax: customers.length < 10,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return state;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user