Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Auto-dismissing Snackbar for Jetpack Compose
class SnackbarState {
var show by mutableStateOf(false)
}
@Composable
fun TransientSnackbar(
modifier: Modifier = Modifier,
snackbarState: SnackbarState,
text: String,
actionLabel: String,
onAction: () -> Unit,
shape: Shape = MaterialTheme.shapes.small,
autoDismiss: Boolean = true,
timeout: Long = 4_000,
onDismiss: (SnackbarState) -> Unit
) {
if(snackbarState.show) {
Snackbar(
modifier = modifier,
text = { Text(text = text) },
shape = shape,
action = {
ClickableText(
text = AnnotatedString(text = actionLabel),
modifier = Modifier.padding(16.dp),
style = TextStyle(
fontWeight = FontWeight.Bold,
color = MaterialTheme.colors.secondary
),
onClick = {
onAction()
snackbarState.show = false
}
)
}
)
}
if (autoDismiss && snackbarState.show) {
launchInComposition {
delay(timeout)
snackbarState.show = false
onDismiss(snackbarState)
}
}
}
@gtf35

This comment has been minimized.

Copy link

@gtf35 gtf35 commented Feb 1, 2021

Looks cool, but how to add dynamically?🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment