You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose报错:@Composable函数需在可组合上下文中调用

解决Jetpack Compose TextField的@Composable调用错误

问题原因

你使用的Material3 TextField组件没有名为icon的参数,传入的Icon Composable被错误绑定到了非Composable类型的参数上,导致Composable函数在非法上下文调用,连带label内的Text和TextField本身都触发了报错。

解决方案

  1. 修正参数名:将icon改为Material3 TextField支持的leadingIcon(左侧图标)或trailingIcon(右侧图标)。
  2. 确认导入包:确保导入的是Material3相关类:
    • androidx.compose.material3.TextField
    • androidx.compose.material3.TextFieldDefaults

修正后的代码

@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)) },
        // 根据需求选择leadingIcon或trailingIcon
        leadingIcon = { Icon(painter = painterResource(id = icon), contentDescription = null) },
        keyboardOptions = keyboardOptions,
        onValueChange = onValueChange,
        singleLine = true,
        modifier = modifier,
        colors = TextFieldDefaults.textFieldColors(
            containerColor = Color(0xFFBDFCC9)
        )
    )
}

内容的提问来源于stack exchange,提问作者user25472147

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 12:12:10