Jetpack Compose - 检测 LazyColumn 的滚动位置何时位于第一个索引

Jetpack Compose - Detect when LazyColumn's scroll position is at the first index

我想为我的LazyColumn设置一个滚动回到顶部按钮。我成功地使按钮工作。但如果我已经在 LazyColumn 的顶部,我希望它不可见。我怎样才能做到这一点?

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        startActivity(intent)

        setContent {
            val scrollState = rememberLazyListState()
            val coroutineScope = rememberCoroutineScope()

            Column(modifier = Modifier.fillMaxSize()) {
                if (scrollState.firstVisibleItemIndex > 0) {
                    Button(onClick = {
                        coroutineScope.launch {
                            scrollState.scrollToItem(0)
                        }
                    }, enabled = scrollState.firstVisibleItemIndex > 0) {
                        Text("Scroll to top")
                    }
                }

                LazyColumn(modifier = Modifier.fillMaxSize(), state = scrollState) {
                    items(MutableList(100) { it }) { i ->
                        Text(i.toString())
                    }
                }
            }
        }
    }
}

LazyColumnstate 属性,如果您传递自定义值而不是默认值,您可以对状态变化做出反应。

为了防止冗余重组,在这种情况下应该使用derivedStateOf:它只会在基于其他状态变量的生成结果发生变化时触发重组:

Box {
    val state = rememberLazyListState()
    LazyColumn(state = state) {
        // ...
    }
    val firstItemVisible by remember {
        derivedStateOf {
            state.firstVisibleItemIndex == 0
        }
    }
    if (!firstItemVisible) {
        Button(onClick = { /*TODO*/ }) {

        }
    }
}