BlocListener

BlocListener with automatically retrieved Bloc

@Composable
inline fun <reified BlocA : BlocBase<BlocAState>, BlocAState : Any>
BlocListener(
    blocTag: String? = null,
    noinline listenWhen: (@DisallowComposableCalls (previousState: BlocAState ?, currentState: BlocAState ) -> Boolean) = null,
    crossinline listener: @DisallowComposableCalls suspend (BlocAState) -> Unit
)

BlocListener handles retrieving a Bloc of the specified type from the registered Blocs in the current composable subtree (see BlocProvider) and start listening to the associated stream of Bloc state updates.

the listener function is invoked in response to state changes in the Bloc.

Note that listener is not a Composable function: It is a (potentially) suspendable method, that is invoked with LaunchedEffect.

The listener is guaranteed to be called only once for each state change, unlike the content method in BlocBuilder, that can be triggered because of recomposition.

An optional blocTag parameter can be specified in order to identify a specific bloc instance in the case where there is more than one instance of a bloc of same type registered for the current composable subtree (see BlocProvider).

The blocTag parameter is not present in the original flutter_bloc implementation

An optional listenWhen parameter can be provided for more granular control over when listener is called.

listenWhen takes the previous state and current state and must return a Boolean which determines whether or not the listener function will be invoked.

For the first call to listenWhen the previous state will be initialized to the state of the Bloc when the BlocListener was initialized.

BlocListener for externally provided Bloc

@Composable
inline fun <reified BlocA : BlocBase<BlocAState>, BlocAState : Any>
BlocListener(
    externallyProvidedBlock: BlocA,
    noinline listenWhen: (@DisallowComposableCalls (previousState: BlocAState ?, currentState: BlocAState ) -> Boolean) = null,
    crossinline listener: @DisallowComposableCalls suspend (BlocAState) -> Unit
)

This is the same as the previous method but with an explicitly specified Bloc instance externallyProvidedBlock , not retrieved implicitly from current registered blocs in the current composable subtree.

Use this method if for example you have retrieved the Bloc already with rememberProvidedBlocOf

Last updated