在detectDragGestures中调用Text报错:@Composable仅能在@Composable上下文调用
解决Jetpack Compose中detectDragGestures回调内调用Composable组件的错误
错误原因
detectDragGestures的onDragStart是普通挂起函数,不具备@Composable上下文,而Text是带有@Composable注解的组件,只能在@Composable函数的上下文中调用,因此直接在回调内调用会触发如下错误:
error: @Composable invocations can only happen from the context of a @Composable function
解决方案
通过状态变量控制UI渲染逻辑,将Composable组件的显示放在@Composable层级内,手势回调仅负责更新状态:
@Composable fun DragGestureDemo() { // 定义状态变量,控制文本的显示状态与内容 var showDragIndicator by remember { mutableStateOf(false) } var dragStartInfo by remember { mutableStateOf("") } Box(modifier = Modifier.fillMaxSize()) { Canvas( modifier = Modifier .fillMaxSize() .pointerInput(Unit) { detectDragGestures( onDragStart = { touchPoint -> // 仅在回调中更新状态 showDragIndicator = true dragStartInfo = "拖拽起始点: ${touchPoint.x}, ${touchPoint.y}" }, onDragEnd = { // 拖拽结束后隐藏文本 showDragIndicator = false } ) } ) { // 此处添加Canvas自定义绘制逻辑 } // 根据状态在Composable上下文内渲染Text if (showDragIndicator) { Text( text = dragStartInfo, modifier = Modifier.padding(16.dp), color = Color.Black, fontSize = 16.sp ) } } }
核心逻辑说明
- 使用
remember和mutableStateOf创建可观察状态,状态变更时Compose会自动触发UI重组 - 手势回调仅处理状态更新,UI渲染严格遵循Compose的状态驱动设计原则,始终在
@Composable上下文中执行
内容的提问来源于stack exchange,提问作者Artier
相关产品推荐
相关产品推荐

