Jetpack Compose Desktop 1.8.0中onDragStart的startTransfer迁移方法
Jetpack Compose Desktop 1.8.0 文件拖拽源适配方案
在Compose Desktop 1.8.0中,1.7.3版本可用的startTransfer API已被移除,导致旧代码出现Unresolved reference 'startTransfer'错误。以下是适配后的完整实现代码:
/** * 允许将组件拖拽到其他应用,实现文件的复制/移动/链接操作 * * 注意:在macOS Finder中常规鼠标拖拽默认会执行移动文件操作 * * @param onTransferCompleted 拖拽完成回调,拖拽中止时参数为null * @param drawDragDecoration 拖拽时的视觉装饰绘制逻辑,示例可参考默认实现 */ @OptIn(ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class) fun Modifier.fileDragSource( path: Path, onTransferCompleted: ((userAction: DragAndDropTransferAction?) -> Unit)? = null, drawDragDecoration: (DrawScope.() -> Unit)? = debugDrawDragDecoration() ): Modifier = dragAndDropSource( drawDragDecoration = { drawDragDecoration?.invoke(this) }, ) { detectDragGestures( onDragStart = { offset -> // 启动拖拽操作,替代原startTransfer val result = startDragAndDrop( supportedActions = setOf( DragAndDropTransferAction.Copy, DragAndDropTransferAction.Move, DragAndDropTransferAction.Link, ), dragDecorationOffset = offset ) { // 构建拖拽传输数据 DragAndDropRequest( transferables = listOf( DragAndDropTransferable(PathTransferable(path)) ) ) } // 处理拖拽完成结果 launch { val action = result.firstOrNull() onTransferCompleted?.invoke(action) } }, onDrag = { _, _ -> }, ) }
关键API变更说明
- 移除
startTransfer,改用startDragAndDrop函数启动拖拽流程 - 原
DragAndDropTransferData替换为DragAndDropRequest,通过transferables字段传入传输数据 - 支持的拖拽操作(supportedActions)从原传输数据参数移至
startDragAndDrop的直接参数 - 拖拽完成回调不再通过构造参数传入,而是通过
startDragAndDrop返回的Flow<DragAndDropTransferAction?>获取结果,需用协程收集
内容的提问来源于stack exchange,提问作者Dima
相关产品推荐
相关产品推荐

