变量在组合中未更新

huangapple go评论50阅读模式
英文:

Variable not updated in compose

问题

我在Kotlin(Jetpack Compose)中有一个类,其中包含一个名为title的变量和一个更新title的ExoPlayer。

class Player {
    var title by mutableStatOf("value")
    // 其他代码...
    
    title = "new value"
    // 其他代码...
}

在用户界面中,创建了该类的一个实例并显示了标题,但在类中更新后,标题仍然不变。是否可以帮助解决这个问题?

英文:

I have a class in Kotlin (Jetpack compose) with a variable title and an exoplayer that updates the title.

class Player{
var title by mutableStatOf("value")
....

title= "new value"
...
}

@Composable
fun Display(){
val player = Player()

player.title?.let{
Text(it)
} 
}

In the user interface an instance of the class is created and the title displayed but it remains unchanged after being updated in the class. Can someone help?

答案1

得分: 1

你忘记了remember玩家实例。在这里,当您更改title时,您的可组合将被重新组合,因为它读取标题。但当它被重新组合时,您将使用默认标题创建Player的新实例。

英文:

You forgot to remember the player instance. Here, when you change title, your composable is recomposed because it reads the title. But when it is recomposed, you create new instance of Player with the default title.

val player = remember { Player() }

huangapple
  • 本文由 发表于 2023年6月2日 01:13:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76384235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定