Reputation: 13139
It seems like when I navigate + show a snackbar from a destination, it flickers for a second and then disappears, instead, if I'm inside a screen without navigating the snackbar shows correctly.
This is my code:
From composable A I send an event to the snackbar host to show a message like so:
@Composable
fun ComposableA(showSnackBarMessage: (message: String, isError: Boolean) -> Unit) {
...
if((uiState.value as ProfileState.ProfileUiState).profileScreenUiState.accountDeleted) {
viewModel.resetVariables()
onNavigateBackToLogin.invoke()
showSnackBarMessage("Account deleted", false)
}
}
Now in MainActivity I receive this event and show a snackbar (meanwhile the navigation happens)
override fun onCreate(...) {
setContent {
val scaffoldState: ScaffoldState = rememberScaffoldState()
var snackBarMessage: String? by remember { mutableStateOf(null) }
var isError by remember { mutableStateOf(false) }
var localState by rememberSaveable { mutableStateOf(false) }
MyTheme {
if (localState) {
LaunchedEffect(key1 = scaffoldState.snackbarHostState) {
if (snackBarMessage != null) {
scaffoldState.snackbarHostState.showSnackbar(
message = snackBarMessage ?: ""
)
snackBarMessage = null
}
}
localState = false
}
Scaffold(
scaffoldState = scaffoldState,
snackbarHost = {
SnackbarHost(hostState = it) { data ->
Snackbar(
snackbarData = data,
backgroundColor = if (!isError) GreenProfit else Color.Red,
contentColor = Color.White
)
}
},
backgroundColor = Color.Black
) {
NavigationGraph(
modifier = Modifier.padding(bottom = it.calculateBottomPadding()),
navController = navController,
showSnackBarMessage = { message, showError ->
isError = showError
snackBarMessage = message
localState = true
}
)
}
I'm using a localState to trigger the snackbar whenever an event occurs, then I check if the snackBarMessage is not null (since we could send the same message twice and I need it to show again, that's why inside the LaunchedEffect I validate it), then I set the message as null and the state as false so it will not re-launch or re-compose.
Now, the issue is that navigating from my profile screen to the login screen will trigger maybe 3 or more compositions since the frames are being rendered, and seems like it goes through really quick and I cannot see the default duration of the snackbar, instead this happens.
Upvotes: 3
Views: 668
Reputation: 1
Try to look in how you manage the screen states, I had the same issue and I noticed that I was changing the UIState after showing the SnackBar causing the same behavior.
Upvotes: 0