Home > Software engineering >  Get Context in a Jetpack Compose Noncomposable function
Get Context in a Jetpack Compose Noncomposable function

Time:12-13

I want to insert some data into Firebase. for that, I have a non-composable function and in that function, I'd like to call Toast.makeText . . in the .addOnSuccessListener part. However, there's no way for me to get the context that should be in the Toast.makeText statement

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")
        }
} 

I know that in order to display Toast from composable function, I should get context as:

val context = LocalContext.current

But have no idea how to get the context in this case.

CodePudding user response:

If you're going to call that function from a composable function, make it composable and access it via LocalContext.current. If you're calling it from a ViewModel, you can make it an AndroidViewModel and use the ApplicationContext instead. You shouldn't access a Context otherwise. Think about its name—"Context"—the circumstances that form the app state. Following this wavelength, it becomes easy to understand where you should access the Context: you can't just get it out of nowhere, you need to retrieve it from somewhere UI-related. Hence, try doing one the aforementioned methods. If none fit, please provide more information on where you're calling that function.

CodePudding user response:

To use the proper context in a composable function you have to use LocalContext.current. So please add the following line:

val context = LocalContext.current

Right before this line:

Toast.makeText(context, "Successfully Added to FB", Toast.LENGTH_SHORT).show()

Please also don't forget to add the corresponding import:

import androidx.compose.ui.platform.LocalContext
  • Related