Dialogs and Bottom Sheets
Deleting a plant in Sprout should ask "Are you sure?" first. And choosing a watering schedule would be neater in a panel that slides up from the bottom. Both are overlays, and in Compose both follow the same rule, which surprises people coming from older Android code: there is no show() call.
The rule
A dialog is on screen while its state is true; dismiss means set it false.
Hold a boolean in state and wrap the dialog in an if:
var showDelete by remember { mutableStateOf(false) }
IconButton(onClick = { showDelete = true }) {
Icon(Icons.Filled.Delete, contentDescription = "Delete plant")
}
if (showDelete) {
AlertDialog(
onDismissRequest = { showDelete = false },
title = { Text("Delete Monstera?") },
text = { Text("Its watering history will be lost.") },
confirmButton = {
TextButton(onClick = { onDelete(); showDelete = false }) { Text("Delete") }
},
dismissButton = {
TextButton(onClick = { showDelete = false }) { Text("Cancel") }
}
)
}onDismissRequest is called when the user taps outside or presses Back. It is only a request: the dialog closes because you set the state to false. Leave it empty and the dialog cannot be dismissed that way.
A ModalBottomSheet works the same way: show it inside if (showSheet) and set the flag false in its onDismissRequest. Choose by purpose:
- AlertDialog — a short decision that interrupts: confirm, discard, allow.
- Bottom sheet — extra content or a list of options tied to the current screen, such as picking a watering schedule.
The shortcut
For any overlay, answer three blanks: which flag shows it, who sets it true, who sets it false.
Which flag
showDelete, remembered, startingfalse.
Drills
Answer fast — trust the rule.
How do you show an AlertDialog in Compose?
When is onDismissRequest called?
A dialog's onDismissRequest = { } is empty. What happens when the user taps outside?
Which overlay fits "choose one of five watering schedules" best?
Remember
- A dialog is on screen while its state is true; dismiss means set it false.
- Answer the three blanks: which flag, who sets true, who sets false.
- Dialogs for short decisions; bottom sheets for options and extra content.
