0

That's my code for PostsBloc:

class PostsBloc extends Bloc<PostsEvent, PostsState> {
  final _dataService = DataService();

  // Constructor
  PostsBloc() : super(LoadingPostsState()) {
    on<LoadPostsEvent>((event, emit) async {
      emit(LoadingPostsState());

      try {
        final posts = await _dataService.getPosts();
        emit(LoadedPostsState(posts: posts));
      } catch (e) {
        emit(FailedToLoadPostsState(error: e));
      }
    });
  }
}

So, I want to use the same method with new event, just without emitting LoadingPostsState() like this:

 PostsBloc() : super(LoadingPostsState()) {
    on<LoadPostsEvent || PullToRefreshEvent>((event, emit) async {
      if(event == LoadPostsEvent){
        emit(LoadingPostsState());
      }

      try {
        final posts = await _dataService.getPosts();
        emit(LoadedPostsState(posts: posts));
      } catch (e) {
        emit(FailedToLoadPostsState(error: e));
      }
    });
  }
rebix
  • 78
  • 5

1 Answers1

1

What you want is the is operator:

if (event is LoadPostsEvent)

However you run into another problem:

on<LoadPostsEvent || PullToRefreshEvent>

this is not a thing. I believe you have two options:

Either make a new event X and have LoadPostsEvent and PullToRefreshEvent extend it, like this:

class LoadEvent extends PostsEvent { ... }

class LoadPostsEvent extends LoadEvent { ... }
class PullToRefreshEvent extends LoadEvent { ... }
on<LoadEvent>((event, emit) {
  if (event is LoadPostsEvent)
});

or, in order to minimize code repetition, declare this event handler as a function

on<LoadPostsEvent>(_loadEvent);
on<PullToRefreshEvent>(_loadEvent);

...

void _loadEvent(PostsEvent event, Emitter<PostsState> emit) {

...

}
h8moss
  • 4,626
  • 2
  • 9
  • 25