Created
October 3, 2024 18:35
-
-
Save ProArun/c667739465cde835eaa04ac3eae15cd1 to your computer and use it in GitHub Desktop.
Save and Restore the Scroll Position of a LazyColumn Persistently
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@OptIn(FlowPreview::class) | |
@Composable | |
fun LazyColumnPosition(modifier: Modifier = Modifier) { | |
val context = LocalContext.current | |
val pref by lazy { | |
context.getSharedPreferences("prefs", MODE_PRIVATE) | |
} | |
val scrollPosition = pref.getInt("scroll_position", 0) | |
val lazyListState = rememberLazyListState( | |
initialFirstVisibleItemIndex = scrollPosition | |
) | |
LaunchedEffect(key1 = lazyListState) { | |
// it is use to convert compose state to flow | |
snapshotFlow { | |
lazyListState.firstVisibleItemIndex | |
} | |
.debounce(500L) | |
.collectLatest { index -> | |
pref.edit() | |
.putInt("scroll_position", index) | |
.apply() | |
} | |
} | |
LazyColumn( | |
state = lazyListState, | |
modifier = Modifier.fillMaxSize(), | |
contentPadding = PaddingValues(16.dp) | |
) { | |
items(100) { | |
ElevatedCard(it) | |
} | |
} | |
} | |
@Composable | |
fun ElevatedCard(index: Int) { | |
ElevatedCard( | |
elevation = CardDefaults.cardElevation( | |
defaultElevation = 6.dp | |
), | |
modifier = Modifier | |
.fillMaxWidth() | |
.height(150.dp) | |
.padding(10.dp) | |
) { | |
Row( | |
modifier = Modifier.fillMaxSize().padding(20.dp), | |
horizontalArrangement = Arrangement.SpaceBetween | |
) { | |
Column( | |
verticalArrangement = Arrangement.SpaceBetween, | |
modifier = Modifier.fillMaxHeight() | |
) { | |
Text( | |
text = "Title", | |
style = TextStyle(fontSize = 32.sp, fontWeight = FontWeight.Bold), | |
textAlign = TextAlign.Center, | |
) | |
Text( | |
text = "Description", | |
style = TextStyle(fontSize = 24.sp), | |
textAlign = TextAlign.Center, | |
) | |
} | |
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxHeight()) { | |
Text( | |
text = "$index", | |
style = TextStyle(fontSize = 42.sp), | |
textAlign = TextAlign.Center, | |
) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment