Home > front end >  Why use "remember" keyword in AlertDialog? (Jetpack compose)
Why use "remember" keyword in AlertDialog? (Jetpack compose)

Time:09-16

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 ?

CodePudding user response:

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/

CodePudding user response:

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.

  • Related