Reputation: 909
code reference : https://foso.github.io/Jetpack-Compose-Playground/material/alertdialog/
@Composable
fun AlertDialogSample() {
MaterialTheme {
Column {
val openDialog = remember { mutableStateOf(false) }
Button(onClick = {
openDialog.value = true
}) {
Text("Click me")
}
if (openDialog.value) {
AlertDialog(
onDismissRequest = {
// Dismiss the dialog when the user clicks outside the dialog or on the back
// button. If you want to disable that functionality, simply use an empty
// onCloseRequest.
openDialog.value = false
},
title = {
Text(text = "Dialog Title")
},
text = {
Text("Here is a text ")
},
confirmButton = {
Button(
onClick = {
openDialog.value = false
}) {
Text("This is the Confirm Button")
}
},
dismissButton = {
Button(
onClick = {
openDialog.value = false
}) {
Text("This is the dismiss Button")
}
}
)
}
}
}
}
I have learned about remember and mutableStateOf keyword. but in this code I think "remember" keyword is not necessary.
If button is clicked, variable openDialog comes true and if onDismissRequest, variable openDialog comes false
all the functions are controlled passively by code writer.. (not automatically managed by remember keyword) Then, why use "remember" in this code case ?
Upvotes: -1
Views: 1715
Reputation: 1525
remember
is used to store the state of the dialog - whether it is open or not. It helps us to update the UI at run time.
Look at this article on state management in Jetpack Compose.
Upvotes: 0
Reputation: 7271
Consider a situation when the value of openDialog
is true
and the parent of AlertDialogSample
get recomposed for any reason which will trigger a recomposition of AlertDialogSample
as well. If you do not use remember
, the value openDialog
will be set to false
.
Upvotes: 2
Reputation: 886
By using remember
the composable stores the previous composition value else it will overwrite it every time. Thanks thracian.
ref: https://www.jetpackcompose.app/donut-hole-skipping/
Upvotes: 3