错误:必须在可组合上下文中调用可组合函数

问题描述 投票:0回答:1

@Composable 调用只能在 @Composable 函数的上下文中发生

我是 jetpack compose 的新手,在文本字段中添加图标和标签时不断收到此错误“@Composable 调用只能在 @Composable 函数的上下文中发生”。

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EditNumberField(
    value: String,
    @StringRes label: Int,
    @DrawableRes icon: Int,
    keyboardOptions: KeyboardOptions,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier
){
    TextField(
        value = value,
        label = { Text(stringResource(label)) },
        icon = {  Icon(painter = painterResource(id = icon), contentDescription = null) },
        keyboardOptions = keyboardOptions,
        onValueChange = onValueChange,
        singleLine = true,
        modifier = modifier,
        colors = TextFieldDefaults.textFieldColors(
            containerColor = Color(0xFFBDFCC9))
    )
}

“TextField(), label = {Text()}, icon = {Icon()}”这些行带有红色下划线,显示上述错误。

android android-studio android-jetpack-compose
1个回答
0
投票

对于 TextField 可组合项,没有名为

icon
的参数。相反,您可以根据需要使用 leadingIcontrailingIcon,然后就可以解决显示的错误。

这是来自

material 3
文档的 TextField 可组合项:

fun TextField(
    value: TextFieldValue,
    onValueChange: (TextFieldValue) -> Unit,
    label: @Composable (() -> Unit)? = null,
    leadingIcon: @Composable (() -> Unit)? = null,
    trailingIcon: @Composable (() -> Unit)? = null,
    //... other paramteres
) {  } //... content of the composable
© www.soinside.com 2019 - 2024. All rights reserved.