英文:
Is there any way to have public static variable with remember state in jetpack compose (kotlin)
问题
@Composable
fun Main() {
var cardsList: List<String> by remember { mutableStateOf(listOf("Test1", "Test2")) }
Column(
Cards(cardsList)
)
}
@Composable
fun Cards(cardsList: List<String>) {
for (item in cardsList) {
Button(
onClick = {
// Modify the list as needed
}
)
}
}
这是您的代码,我已经对其进行了一些修改,以便在Cards
函数中接受cardsList
作为参数。这样,当您修改cardsList
时,Cards
函数中的UI将自动刷新。在Main
函数中,我使用remember
来管理cardsList
的状态,以确保在重新组合时保留其状态。您可以在Cards
函数中的onClick
处理程序中修改cardsList
以执行所需的操作。
英文:
@Composable
fun Main() {
var cardsList: List<String> by remember { mutableStateOf( listOf("Test1","Test2") ) }
Column(
Cards()
)
}
@Composable
fun Cards() {
for(item in cardsList) {
Button(
onClick = {cardsList -= item}
)
}
}
This is my code, I need to re-assign the 'cardsList' out side of main function, also if 'cardsList' changed i want UI and all functions that use 'cardsList' as parameter refresh too
can a class help me? maybe i put my list in a class
I tried code below but didnt work
var cardsList: List<String> = listOf("Test1","Test2")
@Composable
fun Main() {
Column(
Cards()
)
}
@Composable
fun Cards() {
for(item in cardsList) {
Button(
onClick = {cardsList -= item}
)
}
}
答案1
得分: 2
这是使用state hoisting解决的:
@Composable fun Main() {
var cardsList: List<String> by remember { mutableStateOf(listOf("Test1", "Test2")) }
Cards(
cards = cardsList,
onCardClick = { card -> cardsList -= card }
)
}
@Composable fun Cards(
cards: List<String>,
onCardClick: (String) -> Unit,
) {
for (item in cards) {
Button(
onClick = { onCardClick(item) }
) { Text(text = item) }
}
}
如果您有更多类似的变量或更喜欢这种方式,您可以创建一个状态类:
class MainState {
var cardsList by mutableStateOf(listOf("Test1", "Test2"))
private set
fun removeCard(card: String) {
cardsList -= card
}
}
@Composable fun Main() {
val state = remember { MainState() }
Cards(state = state)
}
@Composable fun Cards(state: MainState) {
for (item in state.cardsList) {
Button(
onClick = { state.removeCard(item) }
) { Text(text = item) }
}
}
英文:
This is solved with state hoisting:
@Composable fun Main() {
var cardsList: List<String> by remember { mutableStateOf(listOf("Test1", "Test2")) }
Cards(
cards = cardsList,
onCardClick = { card -> cardsList -= card }
)
}
@Composable fun Cards(
cards: List<String>
onCardClick: (String) -> Unit,
) {
for(item in cards) {
Button(
onClick = { onCardClick(item) }
) { Text(text = item) }
}
}
If you have more such variables or you just prefer it that way, you can create a state class:
class MainState {
var cardsList by mutableStateOf(listOf("Test1", "Test2"))
private set
fun removeCard(card: String) {
cardsList -= card
}
}
@Composable fun Main() {
val state = remember { MainState() }
Cards(state = state)
}
@Composable fun Cards(state: MainState) {
for(item in state.cardsList) {
Button(
onClick = { state.removeCard(item) }
) { Text(text = item) }
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论