Kiryl Tkach
Kiryl Tkach

Reputation: 3644

Proper way to store tab states in Compose Multiplatform

What is the proper way to store tab content state in Compose Multiplatform? "Remember" keeps state only during recompositions, not when one view replaces another. On Android ViewModel should be used, but in Compose Multiplatform there is no ViewModel class.

Upvotes: 1

Views: 688

Answers (1)

write custom code

@Composable
 fun HorizontalChipTabs(modifier: Modifier = Modifier,selectedIndex:Int=0,items: List<String> = emptyList(),onChipSelectedIndex: (Int) -> Unit = { _ ->},center:Boolean=false) {

val allItems: List<String> by remember { mutableStateOf(items) }

var activePosition by remember { mutableStateOf(selectedIndex) }

LazyRow(
    modifier = modifier.fillMaxWidth(),
    contentPadding = PaddingValues(2.dp),
    verticalAlignment = Alignment.CenterVertically,
    horizontalArrangement = if (!center) Arrangement.Start else Arrangement.Center,
    flingBehavior = ScrollableDefaults.flingBehavior(),
    reverseLayout = false,
    content = {

        itemsIndexed(allItems) { index, item ->

            if (activePosition == index) {
                PrimaryChip(item) {
                    onChipSelectedIndex(index)
                    activePosition = index
                }
            } else {
                SecondaryChip(item) {
                    onChipSelectedIndex(index)
                    activePosition = index
                }
            }
        }
    }
)}

usage

 var selectedTabIndex by rememberSaveable { mutableStateOf(0) }


HorizontalChipTabs(
            selectedIndex = selectedTabIndex,
            items = tabs,
            onChipSelectedIndex = { index ->
                selectedTabIndex = index
                viewModel.clearData()
            }
        )

Upvotes: 0

Related Questions