79109794

Date: 2024-10-21 11:24:21
Score: 0.5
Natty:
Report link

Google has added a sample how to show your data in @Preview

One important moment - you should use exactly MutableStateFlow() and not builders like flowOf() (in this case it's not necessary use sourceLoadStates)

@Sampled
@Preview
@Composable
fun PagingPreview() {
    /**
     * The composable that displays data from LazyPagingItems.
     *
     * This composable is inlined only for the purposes of this sample. In production code, this
     * function should be its own top-level function.
     */
    @Composable
    fun DisplayPaging(flow: Flow<PagingData<String>>) {
        // Flow of real data i.e. flow from a ViewModel, or flow of fake data i.e. from a Preview.
        val lazyPagingItems = flow.collectAsLazyPagingItems()
        LazyColumn(modifier = Modifier.fillMaxSize().background(Color.Red)) {
            items(count = lazyPagingItems.itemCount) { index ->
                val item = lazyPagingItems[index]
                Text(text = "$item", fontSize = 35.sp, color = Color.Black)
            }
        }
    }

    /**
     * The preview function should be responsible for creating the fake data and passing it to the
     * function that displays it.
     */
    // create list of fake data for preview
    val fakeData = List(10) { "preview item $it" }
    // create pagingData from a list of fake data
    val pagingData = PagingData.from(fakeData)
    // pass pagingData containing fake data to a MutableStateFlow
    val fakeDataFlow = MutableStateFlow(pagingData)
    // pass flow to composable
    DisplayPaging(flow = fakeDataFlow)
}
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Preview
  • Low reputation (1):
Posted by: nowiwr01p