如何将改造的 get 请求函数的结果返回到可变变量

问题描述 投票:0回答:1

我正在关注本教程 https://www.youtube.com/watch?v=HzbTCLnPR24&list=PLEGrY4uRTu5mn5Hky0xTZS3gK4TbYM_CR&index=1 但最后那家伙变得很困惑。我已经在一个单独的程序中编写过一次相同的代码,并且运行良好。现在我尝试更改变量名称并添加一个导航控制器以适合我的项目,但可变变量名称在函数内变为红色。当我在函数中将变量作为参数传递以查看代码是否有效时,它有效,但我无法将返回参数分配给可变变量。 Log.i("Tag", "$user") 返回 用户(用户名=Jack,电子邮件=“[电子邮件受保护]”) 用户是单独文件中的数据类 在教程最后(如 30:10),他没有返回值,他只是将 response.body() 分配给可变变量,在后面添加 .value,然后它会自动更新文本字段。我的函数甚至无法识别可变变量。我怎样才能做到这一点?

@Composable
fun PlayScreen(
    navController: NavController,
    context: Context = LocalContext.current,

){
    var user by remember{mutableStateOf(User("",""))}
    Column(
        modifier = Modifier
            .fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Bottom

    ) {
        Text(text = "$user")
        Button(onClick = {

            getRequest(context)
        }) {
            Text("Getuser")
        }
        
        
    }
}

@Composable

@Preview(showBackground = true)
fun PlayScreenPreview(){
    PlayScreen(
        navController = rememberNavController()
    )
}
fun getRequest(context: Context) { 
    
    GlobalScope.launch(Dispatchers.IO){
        
        val response = try{
            RetrofitInstance.api.getUser("Jack")
        }catch(e: HttpException){
           
            return@launch
        }catch(e: IOException){
            
            
            return@launch
        }
        
        if(response.isSuccessful && response.body() != null){
           
            withContext(Dispatchers.Main){
                user = response.body()!! <------User is red
                Log.i("Tag", "$user") <------Here too

            }

        }
    }

}

也欢迎提出可能存在问题的想法。 非常感谢您的帮助

kotlin android-studio android-jetpack-compose retrofit
1个回答
0
投票

您无法访问

user
中的
getRequest()
变量,因为它是在
PlayScreen()
中定义的,因此仅在
PlayScreen()
中可见。你可以做的是返回
getRequest()
:

的结果
fun getRequest(context: Context): User? { 
    
    GlobalScope.launch(Dispatchers.IO){
        
        val response = try{
            RetrofitInstance.api.getUser("Jack")
        }catch(e: HttpException){
           
            return@launch
        }catch(e: IOException){
            
            
            return@launch
        }
        
        if(response.isSuccessful && response.body() != null){
           
            withContext(Dispatchers.Main){
                return response.body()!!    
            }

        } else {
          return null
        }
    }

}

并将返回值赋给

user
内的
PlayScreen()
变量:

Button(onClick = {

    user = getRequest(context)
}

请注意,此代码可能不会按原样编译,因为您需要确保始终从

getRequest()
返回一些值,但希望它演示了这个想法。

© www.soinside.com 2019 - 2024. All rights reserved.