出现报错:
Suspend function 'scrollToItem' should be called only from a coroutine or another suspend function
源代码:
val scrollState = rememberLazyListState()
Column {
Row {
Button(modifier = Modifier.weight(1f), onClick = {
scrollState.scrollToItem(0)
}) {
Text(text = "Scroll to the top")
}
Button(modifier = Modifier.weight(1f), onClick = {
scrollState.scrollToItem(99)
}) {
Text(text = "Scroll to the end")
}
}
LazyColumn(state = scrollState) {
items(100) {
ImageListItem(index = it)
}
}
}
但是scrollState.scrollToItem(0)
这个位置爆红,问人工智能也没有,最后度娘之后找到:
scrollToItem() 和 animateScrollToItem() 都是挂起函数,这意味着我们需要在协同例程中调用它们
将代码改为下面的内容即可:
val scrollState = rememberLazyListState()
val coroutineScope = rememberCoroutineScope()
Column {
Row {
Button(modifier = Modifier.weight(1f), onClick = {
coroutineScope.launch {
scrollState.scrollToItem(0)
}
}) {
Text(text = "Scroll to the top")
}
Button(modifier = Modifier.weight(1f), onClick = {
coroutineScope.launch {
scrollState.scrollToItem(99)
}
}) {
Text(text = "Scroll to the end")
}
}
LazyColumn(state = scrollState) {
items(100) {
ImageListItem(index = it)
}
}
}