I’m new to Flutter Bloc, I’m handling customer related bloc where there can be following states CustomerLoaded, CustomerLoading, CustomerAddLoader and CustomerInvalidForm
CustomerLoaded – this state holds customer list
CustomerLoading – this state is emitted when fetching customers from backend (API Call)
CustomerAddLoader – this state is emitted when adding customer
CustomerInvalidForm – this state is emitted if there is validation related error in customer adding form
the problem is that if I emit CustomerInvalidForm state (due to form validation), this state is shown across all screen where I’m displaying customer list, I wouldn’t want to show such validation related state on customer list screen
basically when I emit CustomerInvalidForm state, CustomerLoaded state is no longer available on Customer List screen where I’m displaying all customers
how to handle such scenario?
Customer State Class
abstract class CustomerState {}
class CustomerInitialState extends CustomerState {}
class CustomerAddLoader extends CustomerState {}
class CustomerLoading extends CustomerState{}
class CustomerLoaded extends CustomerState {
final List<CustomerModel> customerList;
CustomerLoaded({required this.customerList});
}
class CustomerError extends CustomerState {
final String error;
CustomerError({required this.error});
}
class CustomerInvalidForm extends CustomerState {
String error;
CustomerInvalidForm({required this.error});
}
Customer Bloc
class CustomerBloc extends Bloc<CustomerEvent, CustomerState> {
final List<CustomerModel> _customerList = [];
CustomerBloc() : super(CustomerInitialState()) {
on<CustomerInitialEvent>((event, emit) {
emit(CustomerLoaded(customerList: _customerList));
});
on<AddCustomerEvent>((event, emit) async {
CustomerModel customerModel = event.customerModel;
if (customerModel.customerName.isEmpty) {
emit(CustomerInvalidForm(error: 'Customer name is required')); // CustomerLoaded state is no longer available on customer list screen
} else {
emit(CustomerAddLoader());
await Future.delayed(const Duration(seconds: 2));
_customerList.add(customerModel);
emit(CustomerLoaded(customerList: _customerList));
}
});
}
}