there are a way to "clear" a rememberLazyListState...
# compose
c
there are a way to "clear" a rememberLazyListState(). I want clear the state only when i perform an action, the rest of the time i want to hold the state.
val state = rememberLazyListState() Column Pager (when i change of page i want invalidate the state) Tabs (if i change of tab i want hold the state) List(state)
b
If you look at the implementation of
rememberLazyListState
, it’s just a one liner that calls rememberSaveable() and creates an instance of LazyListState. You could probably create your own implementation that also has a key that would trigger invalidation of the
remember
… You could update the key when the Pager changes … something like:
Copy code
val myLazyListState = rememberSaveable(
    saver = LazyListState.Saver, 
    key=pager.currentPage) {
  LazyListState( ... )
}
c
thanks! My mind insisted on using what the library already provides, but creating a custom Remember is the solution without a doubt.
I wonder if the toolkit shouldn’t provide this possibility.
b
Maybe, I think for the most part, the reason why the library has
rememberXXX()
methods at all is just to provide defaults for components that need them. In this case, they provide a
LazyColumn
composable, and one of the things it needs is a list state:
Copy code
@Composable
fun LazyColumn(
    ...
    listState: LazyListState
    ...
) {
For common/basic use cases, they don’t want the developer to have to manually keep track of and provide a list state EVERY time they use it. So, they make the listState property optional and provide a default value. But the default value needs to be remembered, so that’s a lot of code to put into the LazyColumn function definition. So, the final solution is to extract that default value out into a short one liner function they can call:
Copy code
fun rememberLazyListState(index, offset) = rememberSavable() { .... }

@Composable
fun LazyColumn(
    ...
    listState: LazyListState = rememberLazyListSate()
    ...
) {
That’s also convenient for the use case where a developer wants to hoist the state, but doesn’t need any special functionality (so, make the remember function public instead of internal). In the end, the purpose of all of the
rememberxxx()
methods isn’t necessarily to provide the developer with a one line function for building a remembered state of XXX that is flexible and can handle many situations … the purpose is to provide a simple default, and if the developer wants/needs to hoist the state to a higher level, they can write their own one liner. All of the above is just IMO.
d
you can also use
Copy code
val state = key(page) {
    rememberLazyListState()
}
which will create a new state whenever the key change
👍 2
c
Thanks Bradley Corn for share your thoughts, i like the way that you reason about it.
I’ve never used
Key
before, but it seems very useful
284 Views