I come from Redux and I am learning the BLoC pattern for global state management. I am having troubles defining where should I store values as properties inside the BLoC class, and when I should store values inside States.
I have a home page where I show some Ads, depending on its category (category should never be null). I implemented an AdsBloc like this:
class AdsBloc extends Bloc<AdsEvent, AdsState> {
  final AdsRepository repository;
  AdsBloc({@required this.repository})
      : super(AdsInitial(category: Category.DOGS));
  @override
  Stream<AdsState> mapEventToState(
    AdsEvent event,
  ) async* {
    // my code
  }
}
And these are my AdsState:
abstract class AdsState {
  final Category category;
  AdsState({this.category});
}
class AdsInitial extends AdsState {
  AdsInitial({category}) : super(category: category);
}
class AdsSuccess extends AdsState {
  final PaginatedAds paginatedAds;
  AdsSuccess({this.paginatedAds, category}) : super(category: category);
}
class AdsFailure extends AdsState {
  AdsFailure({category}) : super(category: category);
}
Because of the way I implemented the pattern, I need to pass the category every time I change the state.
So I was thinking if I can consider the category property to be of AdsBloc and remove it from state, this way I can get a better control of this property.
Implement "category" as a parameter for the event that is triggering ad loading process. This way, for example, you will tell BLoC to "LoadAds" with "category: Category.DOGS".
class LoadAds extends AdsEvent {
  final Category category;
  
  LoadAds({
    @required this.category,
  });
  @override
  List<Object> get props => [category];
}
This way you will be able to use single bloc instance to load different ad types when needed. Load DOGS first, 2 minutes later load CATS instead of dogs.
If you do not need this ability - then defining category inside bloc itself is perfectly fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With