android - Jetpack Compose 滚动 LazyColumn with CoroutineScope 结果错误 A MonotonicFrameClock 在此 CoroutineContext 中不可用

标签 android kotlin-coroutines android-jetpack-compose

退房this example使用状态和协程作为列表滚动

@Composable
fun ScrollingList() {
    val listSize = 100
    // We save the scrolling position with this state
    val scrollState = rememberLazyListState()
    // We save the coroutine scope where our animated scroll will be executed
    val coroutineScope = rememberCoroutineScope()

    Column {
        Row {
            Button(onClick = {
                coroutineScope.launch {
                    // 0 is the first item index
                    scrollState.animateScrollToItem(0)
                }
            }) {
                Text("Scroll to the top")
            }

            Button(onClick = {
                coroutineScope.launch {
                    // listSize - 1 is the last index of the list
                    scrollState.animateScrollToItem(listSize - 1)
                }
            }) {
                Text("Scroll to the end")
            }
        }

        LazyColumn(state = scrollState) {
            items(listSize) {
                ImageListItem(it)
            }
        }
    }
}
哪个适用于暂停功能
suspend fun animateScrollToItem(
    /*@IntRange(from = 0)*/
    index: Int,
    /*@IntRange(from = 0)*/
    scrollOffset: Int = 0
) {
    doSmoothScrollToItem(index, scrollOffset)
}
如果我将协程范围更改为
val coroutineScope = CoroutineScope(Dispatchers.Main)
它返回

java.lang.IllegalStateException: A MonotonicFrameClock is not available in this CoroutineContext. Callers should supply an appropriate MonotonicFrameClock using withContext.


这是什么意思,是rememberCoroutineScope()提供的唯一途径协程范围 到这个功能?

最佳答案

由于 animateScrollToItem 是可组合函数,因此需要在组合范围内调用它。
As documentation states

rememberCoroutineScope is a composable function that returns a CoroutineScope bound to the point of the Composition where it's called. The scope will be cancelled when the call leaves the Composition.

关于android - Jetpack Compose 滚动 LazyColumn with CoroutineScope 结果错误 A MonotonicFrameClock 在此 CoroutineContext 中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68398064/

相关文章:

android - Picasso库异常崩溃

Android Handler.post,到底发生了什么

kotlin - 从多个来源收集数据的惯用方式是什么?

androidx.compose.ui.tooling.preview.PreviewActivity 不是 Activity 子类或别名

android - 如何在 Androidx Compose Material 中删除 TextField 的指示线?

android - OnBackpressed 在 tablayout 上获得空 View

android - 是否可以在Android上控制png编码的图像质量?

android - 何时使用 Kotlin 协程来优化代码性能

android - 如何在使用 API 时处理 Flow Coroutines 异步行为

android - 如何在jetpack compose中将文本定义为h1?