Material3 ‐ AlertDialog - devrath/Material-3-Design-Kit GitHub Wiki

Contents
Observation
Demo representation
Code

Observation

  • Here one point to note is we cannot update the mutable state directly in the composable function that we have called, Instead we need to pass the boolean value back via the callback as shown in the function.

Demo representation

Light Theme Dark Theme

Code

Alert dialog with icon, text, description, and two action buttons

@Composable
fun ScreenContent(modifier: Modifier = Modifier) {
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {

        var dialogDisplayState by remember { mutableStateOf(false) }

        if (dialogDisplayState) {
            normalDialog(dialogDisplayState) { newValue ->
                // Here we re-assign the boolean value and update the state
                dialogDisplayState = newValue
            }
        }


        Button(onClick = {
            dialogDisplayState = true
        }) {
            Text(text = "Display Dialog")
        }
    }
}

@Composable
private fun normalDialog(
    dialogDisplayState: Boolean,
    onDismiss: (Boolean) -> Unit
) {
    val contextForToast = LocalContext.current.applicationContext

    if (dialogDisplayState) {
        AlertDialog(
            onDismissRequest = {
                // Update the dialogDisplayState via Lambda when user clicks outside the dialog
                onDismiss(false)
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        // Update the dialogDisplayState via Lambda on click of action button
                        onDismiss(false)
                        Toast.makeText(contextForToast, "Yes", Toast.LENGTH_SHORT).show()
                    }
                ) {
                    Text(text = "Yes")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        // Update the dialogDisplayState via Lambda on click of action button
                        onDismiss(false)
                        Toast.makeText(contextForToast, "No", Toast.LENGTH_SHORT).show()
                    }
                ) {
                    Text(text = "No")
                }
            },
            title = { Text(text = "Are you sure?") },
            text = { Text(text = "Are you sure you want to perform a action") },
            icon = {
                Icon(
                    imageVector = Icons.Default.Android,
                    contentDescription = "Action to be performed"
                )
            }
        )
    }
}
⚠️ **GitHub.com Fallback** ⚠️