在 Compose Multiplatform 中存储选项卡状态的正确方法

问题描述 投票:0回答:1

在 Compose Multiplatform 中存储选项卡内容状态的正确方法是什么? “记住”仅在重组期间保留状态,而不是在一个视图替换另一个视图时保留状态。在 Android 上应该使用 ViewModel,但在 Compose Multiplatform 中没有 ViewModel 类。

kotlin compose-desktop compose-multiplatform
1个回答
0
投票

编写自定义代码

@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
                }
            }
        }
    }
)}

用法

 var selectedTabIndex by rememberSaveable { mutableStateOf(0) }


HorizontalChipTabs(
            selectedIndex = selectedTabIndex,
            items = tabs,
            onChipSelectedIndex = { index ->
                selectedTabIndex = index
                viewModel.clearData()
            }
        )
© www.soinside.com 2019 - 2024. All rights reserved.