kotlin 来自viewModel的值的可变状态不起作用

utugiqy6  于 2022-11-16  发布在  Kotlin
关注(0)|答案(1)|浏览(141)

我的ViewModel中有一个mutablestate,我试图在我的组合中设置和访问它。当我使用remember的委托属性时,它正在工作,但在viewModel中创建它并在组合中访问它后,变量的状态为空。如何在viewModel中使用状态
当状态在compose内时,一切都正常

var mSelectedText by remember { mutableStateOf("") }

但当我从viewModel更改中使用它并设置我的OutlinedTextField value = mainCatTitle和onValueChange = {mainCatTitle = it}时,选定的标题未显示在OutlinedTextField中,为空

private val _mainCatTitle = mutableStateOf("")
 val mainCatTitle: State<String> = _mainCatTitle

我的可组合

var mSelectedText by remember { mutableStateOf("") }
   var mainCatTitle = viewModel.mainCatTitle.value

   Column(Modifier.padding(20.dp)) {

    OutlinedTextField(
        value = mainCatTitle,
        onValueChange = { mainCatTitle = it },
        modifier = Modifier
            .fillMaxWidth()
            .onGloballyPositioned { coordinates ->
                mTextFieldSize = coordinates.size.toSize()
            },
        readOnly = true,
        label = { Text(text = "Select MainCategory") },
        trailingIcon = {
            Icon(icon, "contentDescription",
                Modifier.clickable { mExpanded = !mExpanded })
        }
    )

    DropdownMenu(expanded = mExpanded,
        onDismissRequest = { mExpanded = false },
        modifier = Modifier.width(with(
            LocalDensity.current) {
            mTextFieldSize.width.toDp()
        })) {
        selectCategory.forEach {
            DropdownMenuItem(onClick = {
                mainCatTitle = it.category_name.toString()
                mSelectedCategoryId = it.category_id.toString()
                mExpanded = false
                Log.i(TAG,"Before the CategoryName: $mainCatTitle " )
            }) {

                Text(text = it.category_name.toString())
            }
        }
    }
}

Log.i(TAG,"Getting the CategoryName: $mainCatTitle " )
}

在DropDownMenuItem内的第一个日志中,该日志显示“选定”字段,但第二个日志为空
已附加图像x1c 0d1x

w8f9ii69

w8f9ii691#

您直接修改onClick中的mainCatTitle变量,而不是修改ViewMoel提升的状态

DropdownMenuItem(onClick = {
        mainCatTitle = it.category_name.toString()
        ...

由于您没有提供任何有关ViewModel信息,因此如果您的ViewModel中没有可以这样调用的函数,我将假设并建议您创建一个函数,

DropdownMenuItem(onClick = {
       viewModel.onSelectedItem(it) // <-- this function
       ...
}

在你的ViewModel中你这样更新状态

fun onSelectedItem(item: String) { // <-- this is the function
    _mainCatTitle.value = item
}

相关问题