为什么当TextfieldValue更改时,重新组件不会发生
由于某种原因,我的ViewModel
val names =
listOf(
"valeria",
"Daniela",
"Isabella",
"Liam",
"Noah",
"Jack",
"Oliver",
"Ava",
"Sophia",
"Amelia"
)
private val _namesList = MutableStateFlow(names)
val namesList = _namesList.asStateFlow()
fun getFilteredNames(state: MutableState<TextFieldValue>) {
viewModelScope.launch {
val searchedText = state.value.text
_namesList.value =
if (searchedText.isEmpty()) {
names
} else {
val resultList = ArrayList<String>()
for (item in names) {
if (item.lowercase(Locale.getDefault())
.contains(searchedText.lowercase(Locale.getDefault()))
) {
resultList.add(item)
}
}
Log.d("List: ", namesList.value.toString())
resultList
}
}
}
重新组件不会发生。
val viewModel: MainViewModel = viewModel()
val names = viewModel.namesList.collectAsState()
LazyColumn(
modifier = Modifier
.fillMaxSize().background(MaterialTheme.colors.background)
) {
items(names.value.size) {
SearchListItem(names.value[it]) {}
}
}
My ViewModel
val names =
listOf(
"valeria",
"Daniela",
"Isabella",
"Liam",
"Noah",
"Jack",
"Oliver",
"Ava",
"Sophia",
"Amelia"
)
private val _namesList = MutableStateFlow(names)
val namesList = _namesList.asStateFlow()
fun getFilteredNames(state: MutableState<TextFieldValue>) {
viewModelScope.launch {
val searchedText = state.value.text
_namesList.value =
if (searchedText.isEmpty()) {
names
} else {
val resultList = ArrayList<String>()
for (item in names) {
if (item.lowercase(Locale.getDefault())
.contains(searchedText.lowercase(Locale.getDefault()))
) {
resultList.add(item)
}
}
Log.d("List: ", namesList.value.toString())
resultList
}
}
}
Recomposition doesn't happen for some reason.
val viewModel: MainViewModel = viewModel()
val names = viewModel.namesList.collectAsState()
LazyColumn(
modifier = Modifier
.fillMaxSize().background(MaterialTheme.colors.background)
) {
items(names.value.size) {
SearchListItem(names.value[it]) {}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一旦我遇到了同样的问题(您可以看到它,还有一些其他答案在这里)。如果不久,仅当您发出新对象时才更新流量(具有与最后发射的项目不同的哈希码)。您正在更新同一列表,然后尝试将其传递给流程。如果您要创建列表的副本并发出此副本,那么一切都可以正常工作,因为它已经是另一个对象
Once I had the same question (you can see it and some other answers here). if shortly, flow is updated only when you emit the new object to it (with different hashcode than the last emitted item). and you are updating the same list and then trying to pass it to flow. if you will create the copy of the list and emit this copy, everything will work ok, as it is already another object
因此,我不确定您如何使用此回调来获取更多项目。简化了,就像:
只是,我使用了此导入:
So I am not sure how are you using this callback to get more items. Simplified it would be like:
Just, I used this import: