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

Kotlin中传递navController.navigate时出现‘表达式未使用’错误

解决Compose中SearchBar的“The expression is unused”错误

你的问题出在SearchBar可组合项的keyboardActions配置里:

keyboardActions = KeyboardActions(onSearch = { onNavigateToSearch })

这里你只是引用了onNavigateToSearch函数,但没有调用它。编译器识别到这个表达式没有产生任何实际执行效果,所以抛出“The expression is unused”错误。

修正代码

只需要给onNavigateToSearch加上括号,触发函数调用即可:

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchBar(
    searchState: MutableState<TextFieldValue> = remember { mutableStateOf(TextFieldValue()) },
    onNavigateToSearch: () -> Unit,
) {
    TextField(
        value = searchState.value,
        onValueChange = { searchState.value = it},
        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
        // 修正:添加()执行导航函数
        keyboardActions = KeyboardActions(onSearch = { onNavigateToSearch() }),
    )
}

原因说明

KeyboardActions的onSearch参数接受一个无参无返回值的lambda,需要在其中编写具体的执行逻辑。你之前的写法只是把函数本身作为表达式返回,没有触发导航操作;加上()后,才会真正调用navController.navigate("search"),完成页面跳转。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:40:23