카테고리 없음

BlocBuilder, BlocListener, BlocConsumer의 차이

잼민코더 2021. 7. 24. 01:00

위젯을 만들때

알림기능이나 snackBar, dialog 등 팝업이나 토스트..등등을 띄울 일이 많습니다

그럴때마다 특정조건을 걸어 함수를 실행하게하고 그함수에서 알림창을 return 할수도있지만..

그런 기능이 많이 붙을수록 코드가 지저분해지고 가독성이 떨어집니다

 

Bloc을 사용하고있다면 블록빌더나 블록리스너, 블록컨슈머를 적재적소에 쓰면 효과적일 수 있습니다

 

블록빌더는 상태에 대해 여러번 위젯을 rebuild 해줄수있습니다

buildWhen함수를 써서 언제 빌드할지 정해줄수도있습니다. '여러번'리빌드가 될수있습니다.

 

blocListener는 상태가 바뀔때 1회성으로 위젯을 빌드하기 위해 사용합니다.

라우팅할때 사용하기도 합니다. 1번 호출되는게 포인트입니다. Bloc은 초기상태가 필요하지만

BlocListener는 초기상태가 없어도 특정상태로 작동될시 1번 수행이 가능합니다.

 

MultiBlocListener를 사용해서 중첩해서 여러상태를 리슨할수도있습니다.

 

MultiBlocListener(

listeners: [

BlocListener<BlocA, BlocAState>(

listener: (context, state) {}, ),

BlocListener<BlocB, BlocBState>( listener: (context, state) {}, ),

BlocListener<BlocC, BlocCState>( listener: (context, state) {}, ), ],

child: ChildA(), )

 

 

BlocConsumer는 Listener와 Builder의 조합이라고 생각하시면 됩니다.

listenWhen 과 buildWhen 함수로 빌드를 제어할 수 있습니다.

 

 

 

BlocConsumer<BlocA, BlocAState>( listenWhen: (previous, current) { // return true/false to determine whether or not // to invoke listener with state }, listener: (context, state) { // do stuff here based on BlocA's state }, buildWhen: (previous, current) { // return true/false to determine whether or not // to rebuild the widget with state }, builder: (context, state) { // return widget here based on BlocA's state } )

 

 

참조

flutter_bloc | Flutter Package (pub.dev)

 

flutter_bloc | Flutter Package

Flutter Widgets that make it easy to implement the BLoC (Business Logic Component) design pattern. Built to be used with the bloc state management package.

pub.dev