【问题标题】:Kotlin: How to set the mutableState of an Integer in another composable function?Kotlin:如何在另一个可组合函数中设置 Integer 的 mutableState?
【发布时间】:2022-12-02 21:54:36
【问题描述】:

出于可读性目的,我想在另一个函数中提取 NavigationBar 可组合项。与 PreviousButton 相同。因此我想将索引的 mutableState 传递给这些函数。但是将索引作为参数传递是行不通的,因为我无法更新状态。我能做些什么?

@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
    ) {
        //...
    }
}

【问题讨论】:

    标签: kotlin android-jetpack-compose


    【解决方案1】:

    您可以添加一个 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)) },
        ) {
            //...
        }
    }
    

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

    【讨论】:

    • 我调查了我的一个旧项目,并提出了与您的完全相同的解决方案!有用。还需要向下传递更新功能。
    【解决方案2】:

    可能有更好的解决方案,但我一直在做的是:

    在 viewmodel 中放置一个变量,并创建一个更新方法,将 view model 或方法传递给 composable

    或者

    向下传递方法以更新索引

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

    【讨论】:

    • 尽量减少将视图模型设置为可组合函数的参数,因为这使得该函数不可重用,特别是在具有不同视图模型的其他屏幕中
    猜你喜欢
    • 2022-08-14
    • 1970-01-01
    • 2010-11-17
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 2012-05-23
    • 1970-01-01
    相关资源
    最近更新 更多