Jetpack Compose 使用 CoroutineScope 滚动 LazyColumn 结果错误 此 CoroutineContext 中不可用 MonotonicFrameClock

Jetpack Compose scrolling LazyColumn with CoroutineScope results error A MonotonicFrameClock is not available in this CoroutineContext

检查 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)

它returns

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

这是什么意思,是 rememberCoroutineScope() 为该函数提供 coroutineScope 的唯一方法吗?

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

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.