Skip to content

Instantly share code, notes, and snippets.

@Humayung
Last active August 25, 2024 17:21
Show Gist options
  • Save Humayung/37476391614afb599b806adcb76c83a1 to your computer and use it in GitHub Desktop.
Save Humayung/37476391614afb599b806adcb76c83a1 to your computer and use it in GitHub Desktop.
// this is our snackbar provider. It acts as a "portal" to our snackbar state
val LocalSnackbarProvider = staticCompositionLocalOf<SnackbarHostState> {
error("No local provider for snackbar")
}
// wrap your root composable with this
@Composable
fun SnackbarProvider(content: @Composable (SnackbarHostState) -> Unit) {
val snackbarHostState = remember {
SnackbarHostState()
}
// this is the where we inject our Snackbar state
CompositionLocalProvider(
LocalSnackbarProvider provides snackbarHostState,
) {
content(snackbarHostState)
}
}
// This is your root composable
@Composable
fun MainScreen(modifier: Modifier = Modifier) {
// wrap the parent composable with our SnackbarProvider
// wrap it once, and you are good to go
MaterialTheme {
SnackbarProvider { snackbar ->
Scaffold(
modifier = modifier,
snackbarHost = {
SnackbarHost(hostState = snackbar)
}
) { contentPadding ->
YourAppPage(
modifier = Modifier
.padding(contentPadding)
.fillMaxSize()
)
}
}
}
}
@Composable
fun YourAppPage(modifier: Modifier = Modifier) {
// here where the power of composition local provider comes into play
// you can access the provider across all composables within our
// Snackbar wrapped composable tree
val localSnackBar = LocalSnackbarProvider.current
val scope = rememberCoroutineScope()
Box(
modifier = modifier, contentAlignment = Alignment.Center
) {
Button(onClick = {
scope.launch {
// just use the snackbar state like you used to do
localSnackBar.showSnackbar(
message = "Snackbar anywhere",
)
}
}) {
Text(text = "Show Snackbar")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment