Jetpack Compose 显示来自 lambda 的值

问题描述 投票:0回答:1

我基本上有一个可组合函数,其中 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 不允许我在问题中发布过少的文本。

android android-jetpack-compose android-viewmodel android-compose
1个回答
0
投票

以这种方式更改代码,看看它是否会根据值更改进行重组。

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
                ...
            )
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.