即使状态发生变化,我的可组合视图也不会自行重组 [英] My composable view doesn't recompose itself even though state changes
问题描述
我正在尝试使用 jetpack compose 开发示例聊天应用程序,并在状态中苦苦挣扎.我有包含消息的 lazyColumn.我的问题是当用户单击按钮时,我的ChatList"会出现.即使我的列表得到更新,函数也不会重构.它仅在消息"出现时重新组合.状态变化.因此,在我向文本字段键入内容后,我可以在列表中看到之前添加的消息.
I am trying to develop sample chat app with jetpack compose and struggling with states. I have lazyColumn which contains messages. My problem is when user clicks the button, my "ChatList" function doesn't recompose eventhough my list gets update. It only recompose when "message" state changes. So i can see previously added messages on list after i type something to texxtfield.
这是我的组合和视图模型:
Here is my composables and viewmodel :
@Composablefun ChatList() {
ConstraintLayout {
val (list, send) = createRefs()
val viewModel = viewModel<MainViewModel>()
val chatList by viewModel.messages.observeAsState(viewModel.messageList)
var message by rememberSaveable { mutableStateOf("") }
val state = rememberLazyListState()
LazyColumn(state = state, modifier = Modifier.constrainAs(list) {
top.linkTo(parent.top)
bottom.linkTo(send.top)
height = Dimension.fillToConstraints
}) {
items(chatList) { item ->
when (item.isMe) {
true -> ChatLayoutMe(item.message)
false -> ChatLayout(item.message)
}
}
}
SendMessage(message = message, modifier = Modifier.constrainAs(send) {
bottom.linkTo(parent.bottom)
}) {
message = it
}
}}
@Composablefun SendMessage(message: String, modifier: Modifier, onMessageChange: (String) -> Unit) {
......
Column(
modifier = Modifier
.clickable { viewModel.addMessage(message) }
......
}
class MainViewModel : ViewModel() {
val messages = MutableLiveData<List<ChatItem>>()
val messageList = mutableListOf<ChatItem>().apply {
............
}
fun addMessage(message: String) {
messageList.add(ChatItem(message, true))
messages.value = messageList
}
}
推荐答案
我猜你的 messageList
属性正在获取相同内存地址的相同实例(这将无法 - 触发- 通知新数据).尝试将 addMessage
函数内的代码更改为:
I guess your the messageList
property is getting the same instance of the same memory address (This won't be able to - trigger - notify new data). Try changing the code inside the addMessage
function to:
fun addMessage(message: String) {
messageList.add(ChatItem(message, true))
// messages.value = messageList
messages.value = messageList.toMutableList() // Copy it to a new memory address
}
这篇关于即使状态发生变化,我的可组合视图也不会自行重组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!