Home > Software engineering >  Flashing list while swiping using HorizontalPager
Flashing list while swiping using HorizontalPager

Time:12-02

I use TabRow and HorizontalPager to display two item list.

When I swipe from one tab to second I see in second tab list from first tab for a second. Then UI updates and second list items display correctly in the second tab.

Also when I'm swiping from one tab to second and I stop swipe between tabs using my finger I can see list from first tab in second tab. When I release my finger from screen and it swipe to second tab, after almost second list updates and display items for second tab.

Why is that?

in ViewModel: (I also tried with mutableStateOf())

val screen = MutableStateFlow<ScreenState>(ScreenState.Loading)
val discountList = MutableStateFlow<List<DiscountOffer>?>(null)
val couponList = MutableStateFlow<List<CouponOffer>?>(null)

in @Composable:

val screenState by viewModel.state.screen.collectAsState()
val discountList by viewModel.state.discountList.collectAsState()
val couponList by viewModel.state.couponList.collectAsState()

when (screenState) {
    ScreenState.Ok -> {
        Box(modifier = Modifier.fillMaxSize()) {
            val pagerState = rememberPagerState(initialPage = 0)
            val scope = rememberCoroutineScope()
            Column {
                TabItems(
                    tabIndex = pagerState.currentPage,
                    selectedTab = { tab -> scope.launch { pagerState.animateScrollToPage(tab.ordinal) } }
                )
                HorizontalPager(count = tabItems.size, state = pagerState) {
                    when (tabItems[pagerState.currentPage]) {
                        PROMOTIONS ->
                            ItemsSection(items = discountList) {
                                DiscountItem()
                            }
                        COUPONS ->
                            ItemsSection(items = couponList) {
                                CouponItem()
                            }
                    }
                }
            }
        }
    }
}  

CodePudding user response:

For HorizontalPager correct work you should return the view depending on the page requested by HorizontalPager: during scrolling while multiple views are on the screen, content lambda will be called multiple times for each of them.

HorizontalPager(count = tabItems.size, state = pagerState) { page ->
    when (tabItems[page]) {
        PROMOTIONS ->
            ItemsSection(items = discountList) {
                DiscountItem()
            }
        COUPONS ->
            ItemsSection(items = couponList) {
                CouponItem()
            }
    }
}
  • Related