在 Jetpack Compose 不可组合函数中获取上下文
Get Context in a Jetpack Compose Noncomposable function
我想向 Firebase 中插入一些数据。为此,我有一个不可组合的函数,在该函数中,我想调用 Toast.makeText 。 .在 .addOnSuccessListener 部分。
但是,我无法获得应该在 Toast.makeText 语句
中的上下文
fun saveActivityToFB(
answer: String,
question: String,
id: String
) {
var db: DatabaseReference = Firebase.database.reference
val ques = Question(answer, question)
db.child("activity").child("test").child(id).setValue(ques)
.addOnSuccessListener {
Log.d("FB", "OK")
//problems with context here!!
Toast.makeText(context, "Successfully Added to FB", Toast.LENGTH_SHORT).show()
}
.addOnFailureListener {
Log.d("FB", "Not inserted into FB")
}
}
我知道为了从可组合函数中显示 Toast,我应该将上下文获取为:
val context = LocalContext.current
但不知道在这种情况下如何获取上下文。
如果您要从可组合函数调用该函数,请使其可组合并通过 LocalContext.current
访问它。如果您从 ViewModel 调用它,则可以将其设为 AndroidViewModel
并改为使用 ApplicationContext
。否则您不应该访问上下文。想想它的名字——“上下文”——形成应用程序状态的环境。遵循这个波长,就很容易理解您应该从哪里访问上下文:您不能随便从哪里得到它,您需要从与 UI 相关的地方检索它。因此,尝试执行上述方法之一。如果 none 合适,请提供有关调用该函数的位置的更多信息。
@Composable
fun Test(){
val context = LocalContext.current // here no problem getting context
var db: DatabaseReference = Firebase.database.reference
db.child("activity").child("test").child(id).setValue(ques)
.addOnSuccessListener {
Log.d("FB", "OK")
//use context from outside of the scope here
Toast.makeText(context, "Successfully Added to FB", Toast.LENGTH_SHORT).show()
}
.addOnFailureListener {
Log.d("FB", "Not inserted into FB")
}
}
我想向 Firebase 中插入一些数据。为此,我有一个不可组合的函数,在该函数中,我想调用 Toast.makeText 。 .在 .addOnSuccessListener 部分。 但是,我无法获得应该在 Toast.makeText 语句
中的上下文fun saveActivityToFB(
answer: String,
question: String,
id: String
) {
var db: DatabaseReference = Firebase.database.reference
val ques = Question(answer, question)
db.child("activity").child("test").child(id).setValue(ques)
.addOnSuccessListener {
Log.d("FB", "OK")
//problems with context here!!
Toast.makeText(context, "Successfully Added to FB", Toast.LENGTH_SHORT).show()
}
.addOnFailureListener {
Log.d("FB", "Not inserted into FB")
}
}
我知道为了从可组合函数中显示 Toast,我应该将上下文获取为:
val context = LocalContext.current
但不知道在这种情况下如何获取上下文。
如果您要从可组合函数调用该函数,请使其可组合并通过 LocalContext.current
访问它。如果您从 ViewModel 调用它,则可以将其设为 AndroidViewModel
并改为使用 ApplicationContext
。否则您不应该访问上下文。想想它的名字——“上下文”——形成应用程序状态的环境。遵循这个波长,就很容易理解您应该从哪里访问上下文:您不能随便从哪里得到它,您需要从与 UI 相关的地方检索它。因此,尝试执行上述方法之一。如果 none 合适,请提供有关调用该函数的位置的更多信息。
@Composable
fun Test(){
val context = LocalContext.current // here no problem getting context
var db: DatabaseReference = Firebase.database.reference
db.child("activity").child("test").child(id).setValue(ques)
.addOnSuccessListener {
Log.d("FB", "OK")
//use context from outside of the scope here
Toast.makeText(context, "Successfully Added to FB", Toast.LENGTH_SHORT).show()
}
.addOnFailureListener {
Log.d("FB", "Not inserted into FB")
}
}