如何在每次API请求时显示加载图标?二次请求加载图标不显示如何解决?
问题根源
你当前的逻辑是通过MessageCad的message字段是否为空判断是否展示加载图标,第一次请求完成后,_resultado已经被赋值为携带内容的MessageCad实例,后续再次发起请求时没有重置这个状态,因此value.message.isEmpty()的判断一直为false,自然不会触发加载图标的展示。
方案1:快速修复
修改ViewModel的create方法,每次发起请求前先重置_resultado为空的MessageCad实例,触发加载状态,同时补充异常场景的状态赋值,避免加载动画一直展示:
fun create(nome: String,email: String,cpf:String,telefone:String, celular:String,senha:String,endereco:String,bairro:String,numero:String, complemento:String,cidade:String ){ viewModelScope.launch { try { // 新增:请求发起前先重置状态,触发加载 _resultado.value = MessageCad() val r = cadastroRepository.createUser(nome,email,cpf,telefone,celular,senha,endereco,bairro, numero,complemento,cidade) _resultado.value = r } catch (e:Exception) { Log.d("Service error",e.toString()) // 新增:异常场景也赋值状态,避免一直显示加载 _resultado.value = MessageCad(message = "请求出错:${e.message?:"未知错误"}") } } }
方案2:更规范的状态管理(推荐)
用密封类拆分UI状态,明确区分初始、加载、成功、失败四种状态,避免靠业务字段判断状态的歧义问题:
- 首先定义UI状态密封类
sealed interface CadastroUiState { object Idle: CadastroUiState // 初始状态 object Loading: CadastroUiState // 加载中 data class Success(val data: MessageCad): CadastroUiState // 请求成功 data class Error(val errMsg: String): CadastroUiState // 请求失败 }
- 修改ViewModel的状态定义与请求逻辑
class CadastroViewModel:ViewModel() { private val cadastroRepository= CadastroRepository() private val _uiState: MutableStateFlow<CadastroUiState> = MutableStateFlow(CadastroUiState.Idle) val uiState: StateFlow<CadastroUiState> = _uiState.asStateFlow() fun create(nome: String,email: String,cpf:String,telefone:String, celular:String,senha:String,endereco:String,bairro:String,numero:String, complemento:String,cidade:String ){ viewModelScope.launch { try { // 置为加载状态 _uiState.value = CadastroUiState.Loading val r = cadastroRepository.createUser(nome,email,cpf,telefone,celular,senha,endereco,bairro, numero,complemento,cidade) _uiState.value = CadastroUiState.Success(r) } catch (e:Exception) { Log.d("Service error",e.toString()) _uiState.value = CadastroUiState.Error("请求失败:${e.localizedMessage?:"未知错误"}") } } } }
- 修改Compose层的调用逻辑
val uiState: CadastroUiState by model.uiState.collectAsState() when(uiState) { CadastroUiState.Loading -> CircularProgressIndicator(modifier = Modifier.wrapContentWidth(Alignment.CenterHorizontally)) is CadastroUiState.Success -> { val messageCad = (uiState as CadastroUiState.Success).data // 替换为你自己的成功逻辑,比如提示请求结果 Text(text = messageCad.message) } is CadastroUiState.Error -> { val errMsg = (uiState as CadastroUiState.Error).errMsg // 替换为你自己的错误提示逻辑 Text(text = errMsg, color = Color.Red) } CadastroUiState.Idle -> { // 初始状态展示,比如表单输入界面 } }
内容的提问来源于stack exchange,提问作者Rafael Souza
相关产品推荐
相关产品推荐

