我有一個顯示預設串列的 Room 應用程式,用戶可以選擇通過按“新建快速預設”按鈕來添加它們:
將新專案插入 Room 資料庫的代碼(在 ViewModel 中):
fun insertQuickPreset(quickPreset: QuickPreset) {
viewModelScope.launch {
repository.insertQuickPreset(quickPreset)
}
}
狀態:
data class NewScreenState(
@StringRes val nameError: Int? = null,
@StringRes val widthError: Int? = null,
@StringRes val heightError: Int? = null,
val name: String = "",
val width: String = "",
val height: String = "",
val quickPresets: List<QuickPreset>
)
回購:
suspend fun insertQuickPreset(quickPreset: QuickPreset) {
return withContext(Dispatchers.IO) {
dao.insert(quickPreset)
}
}
可組合:
Button(
modifier = Modifier.align(Alignment.End),
onClick = {
viewModel.insertQuickPreset(QuickPreset(55,52))
}
) {
Text(
"New Quick Preset"
)
}
問題是,當用戶點擊“New Quick Preset”時,狀態不會更新,因此用戶需要回傳查看結果,然后按下按鈕再次進入螢屏。
我參加了 Compose 課程,他們從未演示如何添加專案,只演示如何獲取它們。我有添加專案的代碼,雖然我不知道如何從這里更新狀態以反映添加的值?我通常使用該.copy方法,但這僅適用于首次獲取資料庫內容時。
uj5u.com熱心網友回復:
使用SnapshotStateList.
val quickPresets: SnapShotStateList
并像這樣初始化它
val list = mutableStateListOf( your quick presets )
您對 a 所做的任何更新SnapshotStateList,例如
- 添加新的快速預設
- 洗掉快速預設
- 通過更新快速預設
.copy()
保證執行 a re-composition,假設它被可組合的 somewehere 觀察到
編輯:這是我自己的資料庫實作的片段
Repository
override fun fetchPeople(): Flow<List<People>> =
peopleDao.getPeople().map { entityList ->
entityList.map { entity ->
entity.toModel()
}
}
override suspend fun savePerson(PersonModel: PersonModel): Long {
return peopleDao.insertPerson(PersonModel.toEntity())
}
override suspend fun deletePerson(PersonModel: PersonModel) {
peopleDao.deletePerson(PersonModel.toEntity())
}
我只是通過觀察它ViewModel
private val _people = mutableStateListOf<Person>()
val people: List<Person> = _people
...
...
// no need for any 'get/fectch' call, changes being made
// to the repository (e.g add or delete) will be propagated back via `flow`
viewModelScope.launch {
repository.fetchPeople()
.collect {
_people.addAll(it)
}
}
對于您的滾動問題,您可以執行以下操作,
val scrollState = rememberLazyListState()
val coroutineScope = rememberCoroutineScope()
// scrollToItem after a successful `re-composition`
SideEffect {
coroutineScope.launch {
scrollState.scrollToItem(index)
}
}
讓composable包含你的list東西完成它需要做的事情,并scrollToItem在它成功之后做re-composition
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/516817.html
標籤:科特林android-jetpack-compose机器人房间安卓视图模型
