Reputation: 2962
I have in my ViewModel
class, a State
object with the default value of false
.
var menuState = mutableStateOf(false)
Now I want to display the IconButton
according to the value of menuState
:
setContent {
Scaffold(
topBar = {
TopAppBar (
title = {
Text(
text = "MyApp",
fontSize = 18.sp
)
if (viewModel.menuState.value) { //Condition
IconButton(
onClick = {
//Do stuff
}
) {
Icon(
imageVector = Icons.Outlined.MoreVert,
contentDescription = null,
)
}
}
}
)
}
)
}
This code works fine, when the app starts, since I want the IconButton
to be hidden. Now the problem comes when I want to change the visibility from another composable on button click:
Button(
onClick = {
viewModel.menuState.value = true
}
) {
Text(
text = "Sign out",
fontSize = 18.sp
)
}
Nothing happens. The IconButton
remains hidden. How to solve this?
Upvotes: 2
Views: 3258
Reputation: 602
Try out this way:
Create Composable method for TopBar and pass boolean parameter
@Composable
fun TopBar(isVisible: Boolean) {
TopAppBar (
title = {
Text(
text = "MyApp",
fontSize = 18.sp
)
if (isVisible) { //Condition
IconButton(
onClick = {
//Do stuff
}
) {
Icon(
imageVector = Icons.Outlined.MoreVert,
contentDescription = null,
)
}
}
}
)
}
After that call this method:
setContent {
Scaffold(
topBar = TopBar(viewModel.menuState.value) }
)
}
Upvotes: 1