Context for Toast in JetPack Compose | Android
Let’s have a look at the arrow button in the image below 👇, we want to click it and show a Toast message in response to this user engagement.
Let’s begin
Toast.makeText(this, "This is a Toast Message !", Toast.LENGTH_SHORT).show().
We will encounter an error ‘this ’ is not defined in this context when called form a non composable function; although it will work fine in Java and Kotlin but not in Jetpack Compose.
When called from a Non Composable function
Following error will be thrown
❌ this ’ is not defined in this context
fun simpleToastMessage(context: Context) {
Toast.makeText(this, "This is a Toast Message !", Toast.LENGTH_SHORT).show()
}
When called from a Composable function
@Composable
fun simpleToastMessage(context: Context) {
Toast.makeText(this, "This is a Toast Message !", Toast.LENGTH_SHORT).show()
}
❌ Same will happen in composable when we call context directly with this keyword.
Now let replace this keyword with LocalContext.current 👇
@Composable
fun simpleToastMessage() {
Toast.makeText(LocalContext.current, "This is a Toast Message !", Toast.LENGTH_SHORT).show()
}
Following error will be thrown
❌@Composable invocations can only happen from the context of a @Composable function
✅Correct Way !
val context = LocalContext.current
Whether we call context from composable or non composable does not matter, we just need to declare and initialize context variable at the start of the function.
@Composable
fun simpleToastMessage() {
val context = LocalContext.current
Toast.makeText(context, "This is a Toast Message !", Toast.LENGTH_SHORT).show()
}
The Toast.makeText()
method requires three parameters:
- Context object: You need to pass the application context or the Activity context.
- UsingLocalContext.current
we can get theContext
object.
-LocalContext.current
can be used only from within a Composable function. Such as we are using it withinColumn()
function which is a composable function.LocalContext.current
cannot be used within a function which is not marked with@composable
annotation.
2. Message (CharSequence as String): You have to pass the message to be displayed in Toast.
3. Duration (int): Pass duration as Toast.LENGTH_SHORT
or Toast.LENGTH.LONG
to display Toast for shorter and longer duration on screen.