admin管理员组

文章数量:1297069

Suppose i have a composable that wraps a TextField into a DropdownMenu. that composable accepts a type T that is used to provide the dropdown menu options and in an onSelect callback. Like this:

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun <T> AutocompleteTextField(
    modifier: Modifier = Modifier,
    initialValue: String? = null,
    enabled: Boolean = true,
    label: String,
    keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
    suggestions: List<T>,
    onSelect: (T) -> Unit
) {
    var expanded by remember { mutableStateOf(false) }
    val textFieldState = rememberTextFieldState(initialValue ?: "")

    ExposedDropdownMenuBox(
        modifier = modifier,
        expanded = expanded,
        onExpandedChange = { expanded = !expanded }
    ) {
        TextField(
            modifier = Modifier
                .menuAnchor(MenuAnchorType.PrimaryEditable)
                .fillMaxWidth(),
            value = textFieldState.text.toString(),
            onValueChange = {
                textFieldState.setTextAndPlaceCursorAtEnd(it.uppercase(Locale.getDefault()))
            },
            singleLine = true,
            enabled = enabled,
            label = { Text(label) },
            keyboardOptions = keyboardOptions,
            colors = ExposedDropdownMenuDefaults.textFieldColors(),
            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) }
        )

        ExposedDropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false }
        ) {
            suggestions
                .filter { it.toString().startsWith(textFieldState.text) }
                .forEach { suggestion ->
                    DropdownMenuItem(
                        text = {
                            Text(
                                text = suggestion.toString(),
                                style = MaterialTheme.typography.titleMedium
                            )
                        },
                        onClick = {
                            textFieldState.setTextAndPlaceCursorAtEnd(suggestion.toString())
                            onSelect(suggestion)
                            expanded = false
                        }
                    )
                }
        }
    }
}

This has worked nicely so far, but now I need to add a dropdown option that allows the user to add a new item of the type T to be used as a suggestion, with T being any simple data class

when I tried accessing the type using T::class, I got some errors about inlining the composable, and after following the IDE's suggestions I ended up inlining the composable and also crossilining the onSelect callback, then I was able to access T::class.

Since I know next to nothing about inline functions, I would like some guidance about whether this is acceptable to do in a composable and, if not, what is the alternative to solving my problem

本文标签: