我试图通过Volley连接获取api数据,并将其赋值到文本可组合中,但它没有工作并显示错误:
@Composable调用只能在@Composable函数的上下文中发生
我知道有一个类似的问题,但它并没有解决我的问题
如何解决这个错误?因为我是Jetpack的新手
代码:
@Composable
fun getJSON() {
val context = LocalContext.current
val queue = Volley.newRequestQueue(context)
val url = "https://adeega.xisaabso.online/android.php"
val stringRequest = StringRequest(Request.Method.POST, url,
{ response ->
val jsonObject = JSONObject(response)
val TotalMoney = jsonObject.get("Total")
Text(text = "$TotalMoney")
},
{
Toast.makeText(context, "Welcome to Error", Toast.LENGTH_SHORT).show()
})
queue.add(stringRequest)
}SetContent
setContent {
First_JetpackCompose_appTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
getJSON()
} // END Surface
}
}发布于 2021-08-20 19:34:34
不能在response块中使用Text(text = "$TotalMoney")。
使用ViewModel或只使用以下内容:
var totalMoney by remember { mutableStateOf("") }
Text(text = totalMoney)
val stringRequest = StringRequest(Request.Method.POST, url,
{ response ->
/* Your code */
totalMoney = ....
},
{
Toast.makeText(context, "Welcome to Error", Toast.LENGTH_SHORT).show()
})
queue.add(stringRequest)https://stackoverflow.com/questions/68863059
复制相似问题