我正在開發一個應用程式,在其中顯示土豆串列,從 Firestore 檢索資料。
我添加了一個滑動操作來重繪 資料。使用我在下面顯示的代碼,資料更新正常,呼叫 Firestore 并更新顯示新值,以防它們存在,或停止顯示不再存在的值。
問題是當我滑動土豆串列螢屏時仍然是空白的,當對 Firestore 的呼叫結束時,它們會再次顯示。也就是說,有幾秒鐘的時間螢屏會變黑。
有沒有這種情況不會發生的可能性?這個效果有點丑
視圖模型:
@HiltViewModel
class PotatoesViewModel @Inject constructor(
private val getPotatoesDataUseCase: GetPotatoesData
) : ViewModel() {
private val _state = mutableStateOf(PotatoesState())
val state: State<PotatoesState> = _state
private val _isRefreshing = MutableStateFlow(false)
val isRefreshing: StateFlow<Boolean>
get() = _isRefreshing.asStateFlow()
init {
getPotatoes()
}
private fun getPotatoes() {
getPotatoesDataUseCase().onEach { result ->
when (result) {
is Resource.Success -> {
_state.value = PotatoesState(potatoes = result.data?.potatoes ?: emptyList())
}
is Resource.Error -> {
_state.value = PotatoesState(
error = result.message ?: "An unexpected error occurred"
)
}
is Resource.Loading -> {
_state.value = PotatoesState(isLoading = true)
}
}
}.launchIn(viewModelScope)
}
fun refresh() {
viewModelScope.launch {
_isRefreshing.emit(true)
getIncidents()
_isRefreshing.emit(false)
}
}
}
螢屏:
@Composable
fun PotatoesDataScreen(
navController: NavController,
viewModel: PotatoesViewModel = hiltViewModel()
) {
val state = viewModel.state.value
val isRefreshing by viewModel.isRefreshing.collectAsState()
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
stringResource(R.string.app_name),
fontWeight = FontWeight.Bold
)
},
backgroundColor = Primary,
contentColor = Color.White
)
},
content = {
Box(modifier = Modifier.fillMaxSize()) {
SwipeRefresh(
state = rememberSwipeRefreshState(isRefreshing),
onRefresh = { viewModel.refresh() }
) {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(vertical = 8.dp)
) {
items(state.potatoes) { potato ->
PotatoCard(
potato = potato
)
}
}
}
}
}
)
}
馬鈴薯狀態:
data class PotatoesState(
val isLoading: Boolean = false,
val potatoes: List<Potato> = emptyList(),
val error: String = ""
)
uj5u.com熱心網友回復:
當串列螢屏為空白時,這是進行 Api 呼叫的時間。當您撥打電話但仍未收到回復時,這也是串列空白的情況。每次執行以下操作時PotatoesState,mutableState都會向傳遞一個新物件:
- 收到回復,
- 得到一個錯誤,(用
Potatoes = emptyList()) - 或狀態正在加載。(與
Potatoes = emptyList())
UI 會根據MutableState您命名的_state.
如果你想保持相同的資料直到你得到新的回應,那么你只需要state.value: MutableState<PotatoesState>在你得到新的回應(AKA, is Resource.success)時才更新當前物件。
或者,您可以實作一個加載微調器,并在您啟動 Api 請求時顯示它,直到isLoading是false。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/397199.html
標籤:安卓 火力基地 科特林 谷歌云firestore android-jetpack-compose
上一篇:Kotlin函式未決議的參考
下一篇:做TCP警告意味著資料包被忽略,"Wireshark(Warning/Malformed):Shortsegment.Segment/fragmentdoesnotcontainafullT
