Pick the fix
The whole screen recomposes on every scroll event, but the button only needs to know if the index is above 0. Best fix?
@Composable
fun Feed(listState: LazyListState) {
val show = listState.firstVisibleItemIndex > 0
if (show) { Button(onClick = {}) { Text("Top") } }
}Hint 1 of 1
How often does the Boolean change compared with the index?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A val show by remember { derivedStateOf { listState.firstVisibleItemIndex > 0 } }
Correct. Readers are notified only when the Boolean flips.
Why not the others?
- B
val show = remember { listState.firstVisibleItemIndex > 0 }. That computes once and never updates. - C
val show = listState.firstVisibleItemIndex > 0inside a LaunchedEffect. Effects don't return values to the composition. - D Move the check into the onClick lambda. Then the button can't be shown or hidden.