Kotlin:如何在另一个可组合函数中设置Integer的mutableState?

g6ll5ycj  于 2022-12-04  发布在  Kotlin
关注(0)|答案(2)|浏览(129)

为了便于阅读,我想提取NavigationBar,它可以在另一个函数中组合。与PreviousButton相同。因此,我想将index的mutableState传递给这些函数。但是,将index作为参数传递是行不通的,因为我无法更新状态。我该怎么做呢?

@Composable
fun MyChickensScreen(){
    val art: List<Art> = Datasource().loadArt()
    var index: Int by remember { mutableStateOf(0) } 
    // IDE suggests making index a val, 
    // but I want to update the state in another composable.

    //...

    NavigationBar(index = index)
    }
}

//NavigationBar passes index to the PreviousButton Composable

@Composable
private fun PreviousButton(index: Int) {
    Button(
        onClick = { index = handlePrevClick(index) }, //Error: Val cannot be reassigned for index
    ) {
        //...
    }
}
9cbw7uwe

9cbw7uwe1#

你可以添加一个lambda函数来更新NavigationBarPreviousButton的可变状态的值:

@Composable
fun MyChickensScreen(){
    val art: List<Art> = Datasource().loadArt()
    var index: Int by remember { mutableStateOf(0) }
    // IDE suggests making index a val, 
    // but I want to update the state in another composable.

    //...

    NavigationBar(
        index = index,
        updateIndex = { index = it }
    )
}

@Composable
private fun PreviousButton(
    index: Int,
    updateIndex: (index: Int) -> Unit
) {
    Button(
        onClick = { updateIndex(handlePrevClick(index)) },
    ) {
        //...
    }
}

现在您可以通过将新值传递给updateIndex lambda函数来更新可变状态索引

ktecyv1j

ktecyv1j2#

有一个可能更好的解决方案,但我一直在做的是:
将一个变量放入视图模型中,并创建一个update方法,将视图模型或方法传递给composable
或者
向下传递方法以更新索引

NavigationBar(index = index, 
 update ={it->
     index = it
})
}

@Composable
private fun PreviousButton(index: Int, update: (Int)-> Unit {
    Button(
        onClick = { update.invoke(index) },
    ) {
        //...
    }
}

相关问题