Where and when should I store values in BLoC itself or its state
Asked Answered
D

1

8

Context

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.

Use case

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);
}

Problem

Because of the way I implemented the pattern, I need to pass the category every time I change the state.

Solution?

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.

Decameter answered 11/8, 2020 at 13:44 Comment(1)
hi, do you found the workaround about this?Blackmon
E
1

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.

Edgeways answered 11/8, 2020 at 15:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.