我基本上有一个可组合函数,其中 lambda 返回一个文本可组合项应该显示的值。
data class CustomUiState(
val lookupList: HashMap<UUID, MutableList<String>> = HashMap()
)
class CustomViewModel(
): ViewModel() {
private val _uiState: MutableStateFlow(CustomUiState())
val uiState: StateFlow<CustomUiState> = _uiState.asStateFlow()
fun getValue(index: Int) {
// complex lookup with lookupList
return ...
}
fun updateValue(i: Int, s: String) {
_uiState.update { state ->
state.copy(
// Update lookupList with new value
lookupList = ...
)
}
}
}
@Composable
fun Screen(viewModel: CustomViewModel) {
Widget(
value = { viewModel.getValue(it) },
onValueChanged = { i, s viewModel.updateValue(i, s) }
)
}
@Composable
fun Widget(
value: (Int) -> String,
onValueChanged: (Int, String) -> Unit
) {
LazyRow() {
items(4) {
// This does not work
// Because Compose do not recompose when value(it) changes
Text(
text = value(it),
//lots of other configurations
...
)
}
}
}
我尝试过谷歌搜索,但没有成功。 我需要更改什么才能使其正常工作?
添加文本只是因为 StackOverflow 不允许我在问题中发布过少的文本。
以这种方式更改代码,看看它是否会根据值更改进行重组。
LazyRow() {
items(4) {
// This does not work
// Because Compose do not recompose when value(it) changes
var textValue by remember(value(it)) {
mutableStateOf(value(it))
}
Text(
text = textValue,
//lots of other configurations
...
)
}
}