我有一个ViewModel,它使用Flow从我的Room数据库获取Note对象:
var uiState by mutableStateOf(NoteUiState())
private set
private fun getNoteById(argument: Int) {
viewModelScope.launch {
try {
repository.getNoteById(argument).collect { note ->
uiState = NoteUiState(note = note)
}
} catch (e: Exception) {
uiState = NoteUiState(error = true)
}
}
}
备注类:
@Entity(tableName = "notes")
data class Note(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
@ColumnInfo(name = "title") val title: String = "",
@ColumnInfo(name = "text") val text: String = "",
) {
override fun toString() = title
}
这种方法工作得很好,直到我try 用Note对象的值作为它们的缺省值来创建一个可变字符串,这样我就可以更新2个TextField组合:
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun Note(
note: DataNote,
isNewNote: Boolean,
createNote: (DataNote) -> Unit,
updateNote: (DataNote) -> Unit,
back: () -> Unit,
trued: String,
) {
var title by remember { mutableStateOf(note.title) }
var content by remember { mutableStateOf(note.text) }
TextField(
value = title,
onValueChange = { title = it },
modifier = Modifier
.fillMaxWidth(),
placeholder = { Text(text = "Title") },
colors = TextFieldDefaults.textFieldColors(
containerColor = Color.Transparent
)
)
TextField(
value = content,
onValueChange = { content = it },
modifier = Modifier
.fillMaxWidth(),
placeholder = { Text(text = "Content") },
colors = TextFieldDefaults.textFieldColors(
containerColor = Color.Transparent
)
)
}
由于某些原因,第一次调用Note对象时它是空的,所以我想要一种更新标题和内容变量的方法.
Note对象本身更新时没有问题,但是标题和内容变量永远不会从初始值更改.如何更新标题和内容变量,同时使它们适用于文本字段?