Managing SnackBar in JetPack Compose
We all know that snack bar is very efficient way to show information in app, We have a different way to show SnackBar in Jetpack compose. To create and show snackBar we need SnackBarHost. Let’s understand about SnackBarHost
.
This is use to maintain state of the SnackBarHost, controls the queue and the current SnackBar being shown inside the SnackBarHost. we usually get that from the ScaffoldState
This state usually lives as a part of a ScaffoldState and provided to the SnackBarHost automatically, but can be decoupled from it and live separately when desired.
SnackBarHost Host for SnackBars to be used in Scaffold to properly show, hide and dismiss items based on material specification and the hostState.
This component with default parameters comes build-in with Scaffold,
if we need to show a default SnackBar, use ScaffoldState. SnackBarHostState and call showSnackBar()
val snackBarHostState = remember { SnackbarHostState() }Scaffold(
backgroundColor = MaterialTheme.colors.surface,
snackbarHost = {
SnackbarHost(
hostState = snackBarHostState,
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight(Alignment.Bottom)
}
)
{
Box(contentAlignment= Alignment.Center){
Button(
onClick ={
LaunchedEffect(key1 = activity){
snackBarHostState.showSnackbar(
message = "Saved Successfully",
duration = SnackbarDuration.Indefinite,
actionLabel = "Ok"
) }
}
)
}
}
showSnackBar() Shows or queues to be shown a SnackBar at the bottom of the Scaffold at which this state is attached and suspends until snackBar is disappeared. SnackbarHostState guarantees to show at most one snackBar at a time. If this function is called while another snackBar is already visible, it will be suspended until this snack bar is shown and subsequently addressed. If the caller is cancelled, the snackBar will be removed from display and/or the queue to be displayed.
showSnackBar returns SnackBarResult, We can use this to implement our own logic, when ActionPerformed or Dismissed
when (result) {
SnackbarResult.ActionPerformed -> {
/* action has been performed */
}
SnackbarResult.Dismissed -> {
/* dismissed, no action needed */
}
}