I tried below code and I observe snackbar is not displayed at bottom of screen. My task is to display snackbar on click of button. I wrote code related to display button in a column in function DisplaySnackBarOnClik() The code to display snackbar is written in MySnackBar(). Can anyone help me to display snackbar in the bottom of the screen by observing the below code:
@Composable
fun DisplaySnackBarOnClik() {
var canShowSnackBar by remember {
mutableStateOf(false)
}
Column(
modifier = Modifier
.verticalScroll(rememberScrollState())
.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(5.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Button(
onClick = { canShowSnackBar = ! canShowSnackBar },
modifier = modifier,
enabled = isEnabled,
elevation = ButtonDefaults.elevation(
defaultElevation = 10.dp,
pressedElevation = 15.dp,
disabledElevation = 0.dp
),
colors = ButtonDefaults.buttonColors(
backgroundColor = colorResource(R.color.cgux_primary_700),
contentColor = colorResource(R.color.white)
)
) {
Text(text = "Show Snack Bar")
}
if (canShowSnackBar) {
MySnackbar("Hello, Snackbar!", "Dismiss")
}
}
@Composable fun MySnackbar(
message: String, actionLabel: String, duration: SnackbarDuration = SnackbarDuration.Short
) {
val snackbarHostState = remember { SnackbarHostState() }
LaunchedEffect(snackbarHostState) {
snackbarHostState.showSnackbar(message, actionLabel, duration = duration)
}
Box(
Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter
) {
SnackbarHost(
hostState = snackbarHostState
)
}
}
You have to wrap your contents inside Box like this. its basic structure to follow
and most important you can remove the box from your the
MySnackbar
composable.Detail Answer