I am new in Jetpack Compose. I just implemented an AlertDialog in Jetpack Compose. I'am not clear about Dialog show and dismiss process. Here is sample code:
@Composable
fun CreateAlertDialog() {
Column {
val openDialog = remember { mutableStateOf(false) }
Button(
onClick = {
openDialog.value = true
},
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
) {
Text(text = "Open Dialog")
}
if (openDialog.value){
AlertDialog(
onDismissRequest = {
openDialog.value = false
},
title = {
Text(text = "Dialog Title")
},
text = {
Text(text = "Text content")
},
confirmButton = {
Button(
onClick = {
openDialog.value = false
}
) {
Text(text = "Ok")
}
},
dismissButton = {
Button(
onClick = {
openDialog.value = false
}
) {
Text(text = "Cancel")
}
},
modifier = Modifier.padding(start = 32.dp, end = 32.dp)
)
}
}
}
This works fine, but i am not clear how dialog is dismissed here. Dialog is showing based on MutableState
It shows dialog when openDialog.value this is true.
What happen after a Button click ? When a Button is clicked openDialog.value becomes false and dialog is dismissed.
Where is dialog dismiss code executed?
How this state is handled ?
Can any one can explain this would be helpful to me.Thanks in advance.
Where is dialog dismiss code executed? --> As soon as you click the button and the value of
openDialogis changed. Recomposition will triggered for your Composable function and UI will be redrawn and accordingly your dialog visibility will be changed. So when the value ofopenDialogis false the dialog code will be skipped. Please check this -> https://developer.android.com/jetpack/compose/mental-model#recompositionHow this state is handled ? --> State is usually handled with
rememberandmutableState.rememberallows you to keep the value of the object in memory incase of the recomposition. andmutableStatestores the value and can trigger recomposition when value is changed.Taking your function as an example. Button clicked and value of
openDialogis true. This will cause recomposition. Now, whenCreateAlertDialog()is again invoke by recomposition the value ofopenDialogwill remain true as it is wrapped inremember{}. Now the dialog will be visible.