Bloc flutter 신 문법 on 메서드

문승훈·2023년 11월 17일
0

Bloc 시리즈

목록 보기
1/2

오늘은 bloc 신 문법 on 메서드를 활용하여 코드의 가독성을 높혔다

여기서 일단 android studio 에서 BLoc 라는 플러그인을 다운을 받는다
받으면 이벤트 정의 , 상태 정의 , 함수 정의 가 자연스레 생성이 된다

class SubjectBloc extends Bloc<SubjectEvent, SubjectState> {
  SubjectBloc() : super(SubjectInitial()) {
    on<SubjectEvent>((event, emit) {
      // TODO: implement event handler
    });
  }
}

처음에 이렇게 생성이 되는데 여기서 이제 이거에 맞게 코드를 생성 해주면 된다

먼저 이벤트 정의를 하는데

class DeleteCommentEvent extends CommentEvent {
  final String commentId;
  final String postId;
  DeleteCommentEvent(this.commentId, this.postId);
}

이벤트 정의 해준다 여기까지는 값을 정의 하는거기 때문에 어렵지는 않다

상태 정의

abstract class CommentState {}

class CommentLoadingState extends CommentState {}

class CommentLoadedState extends CommentState {
  final List<Comment> comments;
  CommentLoadedState(this.comments);
}

이렇게 사애 정의 해주고 마지막은 함수 정의 를 해준다 자기가 원하는 상태를 정의 하면 된다

여기서 Bloc 사용하는 예제들을 보면 다양한 방법으로 하는것을 알수 있다

나는 여기서 on메서드를 사용하여 각 이벤트에 대한 로직을 정의 하게 된다

  CommentBloc() : super(CommentLoadingState()) {
    on<FetchCommentsEvent>((event, emit) async {
      // 'FetchCommentsEvent' 이벤트가 들어왔을 때 댓글을 불러오는 로직
      emit(CommentLoadingState()); // 댓글을 불러오는 중 상태로 변경

      try {
        List<Comment> comments = await _fetchCommentsFromFirestore(event.postId);
        emit(CommentLoadedState(comments)); // 댓글을 성공적으로 불러온 상태로 변경
      } catch (e) {
        emit(CommentErrorState('Failed to fetch comments: $e')); // 오류 발생 시 에러 상태로 변경
      }
    });

이제 여기 인자에 들어가 있는걸 보면 event 와 emit이라는게 있다 emit은 State랑 같은 역할을 함으로써
상태를 초기화 시켜주고 변경을 시켜주는 메서드이다

profile
차기 GDE 개발자 문승훈

0개의 댓글