PostBloc constructor Null safety

PostBloc(
  1. {required PostRepository repository,
  2. String? subreddit}
)

Create a new PostBloc.

Implementation

PostBloc({
  required this.repository,
  this.subreddit
}) : super(const PostState()) {
  on<PostFetchRequestedEvent>((event, emit) async {
    if (state.hasReachedMax || _fetching) {
      return;
    }
    try {
      _fetching = true;
      List<Post> posts = await repository.getPosts(
        subreddit: subreddit,
        sortBy: state.sortBy,
        since: state.sortSince,
        after: state.posts.isNotEmpty
          ? state.posts.last.id
          : null
      );
      emit(state.copyWith(
        posts: List.of(state.posts)..addAll(posts),
        status: PostStatus.success,
        hasReachedMax: posts.isEmpty
      ));
    } catch(e) {
      print(e);
      emit(state.copyWith(status: PostStatus.failure));
    }
    finally {
      _fetching = false;
    }
  });
  on<PostSortChangedEvent>((event, emit) async {
    emit(PostState(
      sortBy: event.sortBy,
      sortSince: event.sortSince
    ));
    add(PostFetchRequestedEvent());
  });
}