androidkotlinandroid-studioandroid-jetpack-composewordpress-jetpack

how to fix this error with OutlinedTextField and DropdownMenu?


I have the code below. I want to create an OutlinedTextField it fill in using the drop-down menu

var expanded by remember { mutableStateOf(false) }
val suggestions = listOf("Item1","Item2","Item3")
var selectedText by remember { mutableStateOf("") }

var textfieldSize by remember { mutableStateOf(Size.Zero)}

val icon = if (expanded)
    Icons.Filled.KeyboardArrowUp //it requires androidx.compose.material:material-icons-extended
else
    Icons.Filled.KeyboardArrowDown


Box() {
    OutlinedTextField(
        value = selectedText,
        onValueChange = { selectedText = it },
        modifier = Modifier
            .fillMaxWidth()
            .onGloballyPositioned { coordinates ->
                //This value is used to assign to the DropDown the same width
                textfieldSize = coordinates.size.toSize()
            },
        label = {Text("Label")},
        trailingIcon = {
            Icon(icon,"contentDescription",
                Modifier.clickable { expanded = !expanded })
        }
    )
    DropdownMenu(
        expanded = expanded,
        onDismissRequest = { expanded = false },
        modifier = Modifier
            .width(with(LocalDensity.current){textfieldSize.width.toDp()})
    ) {
        suggestions.forEach { label ->
            DropdownMenuItem(onClick = {
                selectedText = label
            }) {
                Text(text = label)
            }
        }
    }


}

But I have this problem Text Error

I couldn't find the solution

can you help me??


Solution

  • try this,

    suggestions.forEach { label ->
                DropdownMenuItem(onClick = {
                    selectedText = label
                } , text = {   Text(text = label)})
            }