Jetpack Compose Dropdown — Complete Guide
In this tutorial, you'll learn about Jetpack Compose Dropdown. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your dropdown menu opens in the wrong position, doesn't close after selection, or the items aren't clickable.
Wrong Approach ❌
@Composable
fun BadDropdown() {
var expanded by remember { mutableStateOf(false) }
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
// No anchor — menu floats at (0,0)
DropdownMenuItem(text = { Text("Option 1") }, onClick = { expanded = false })
}
}
// Items not clickable due to modifier conflict
DropdownMenuItem(
text = { Text("Option") },
onClick = { /* handler */ },
modifier = Modifier.fillMaxWidth().padding(0.dp) // Overrides defaults
)
Output: Menu appears at top-left corner. Items may not respond to clicks.
Right Approach ✅
@Composable
fun GoodDropdown() {
var expanded by remember { mutableStateOf(false) }
var selectedOption by remember { mutableStateOf("Select") }
Box {
OutlinedButton(onClick = { expanded = true }) {
Text(selectedOption)
Icon(Icons.Default.ArrowDropDown, "Expand", modifier = Modifier.size(20.dp))
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
modifier = Modifier
.background(MaterialTheme.colorScheme.surface)
.width(IntrinsicSize.Min)
) {
DropdownMenuItem(
text = { Text("Option A") },
onClick = {
selectedOption = "Option A"
expanded = false
},
leadingIcon = { Icon(Icons.Default.Check, "") }
)
DropdownMenuItem(
text = { Text("Option B") },
onClick = {
selectedOption = "Option B"
expanded = false
},
enabled = false // Disabled item
)
Divider()
DropdownMenuItem(
text = { Text("Delete", color = MaterialTheme.colorScheme.error) },
onClick = {
selectedOption = "Delete"
expanded = false
}
)
}
}
}
Output: Properly anchored dropdown with working items.
Prevention
- Always wrap
DropdownMenuand its anchor in aBox. - Always set
expandedstate correctly inonDismissRequestandonClick. - Use
leadingIconandtrailingIconfor visual indicators. - Use
Divider()between grouped items.
Common Mistakes with compose dropdown
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro