This is not a post to have a solution but to discuss the project structure on Compose.
I'm currently learning Compose and I have difficulties to understand how to use the Snackbar in a project. Most examples I've seen are basic examples to call the Snackbar once with the SnackbarHostState
from the Scaffold.
However, when working on an app that has an MVVM structure, I don't understand how the snackbar can be called from anywhere, except transmitting the state from a composable to another.
However, I would like the snackbar use to not be that restrictive. Is there any scalable way to use the Snackbar yet with Compose?
CodePudding user response:
This might be a good use-case for CompositionLocals - a way to pass dependencies down the tree implicitly. First, make sure each screen-level composable provides a SnackbarHostState
or some kind of snackbar manager, which wraps the SnackbarHostState
(if you'd like to add some logic on top of the standard behaviour). After that at any place in your app use the provided CompositionLocal
to show a snackbar.
CodePudding user response:
Setup;
ExampleTheme {
val snackbarHostState = remember { SnackbarHostState() }
val LocalSnackbarHostState = compositionLocalOf<SnackbarHostState>{
error("No Snackbar Host State")
}
CompositionLocalProvider(
values = arrayOf(
LocalSnackbarHostState provides snackbarHostState
)
) {
Scaffold(
snackbarHost = { SnackbarHost(snackbarHostState) },
) {
//
}
}
}
Call wherever you want;
val snackbarHostState = LocalSnackbarHostState.current
snackbarHostState.showSnackbar()