Skip to content

Get context in Jetpack compose

Get context in Jetpack compose

1. Overview

In this article, we will learn to get the context in the Jetpack Compose. To learn more about other Jetpack compose features, refer to these articles.

2. Get context in Jetpack compose

You can get the context by using the LocalContext:

val context = LocalContext.current

For example, you can retrieve the context and show a toast message inside the Jetpack composable.

@Composable
@Preview(showBackground = true)
fun showDropDown() {

    var expanded by remember { mutableStateOf(false) }

    val context = LocalContext.current
    Box(modifier = Modifier
        .fillMaxSize()
        .wrapContentSize(Alignment.TopEnd)) {
        IconButton(onClick = { expanded = true }) {
            Icon(Icons.Default.MoreVert, contentDescription = "Settings")
        }
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            Modifier.offset(10.dp, 10.dp)
        ) {
            DropdownMenuItem(onClick = {
                Toast.makeText(context,"Add",Toast.LENGTH_SHORT).show()
            }) {
                Text("Add")
            }
        }
    }
}

Trying to use the LocalContext.current directly inside the onClick function results in the compilation error “@composable invocations can only happen from the context of an @composable function”.

 DropdownMenuItem(onClick = {
                Toast.makeText(LocalContext.current,"Clear",Toast.LENGTH_SHORT).show()
            }) {
                Text("Clear")
            }

This is because the onClick function is not a composable function and so can’t accept composable functions. Since the LocalContext.current is composable, you can’t invoke it within the onClick function.

Alternatively, you can get the context outside the onClick function scope and use, as shown in the first example.

3. Conclusion

To sum up, we have learned to get the context in the compose. You can find code samples in our GitHub repository.

1 thought on “Get context in Jetpack compose”

  1. Pingback: Toast in Jetpack compose - TedBlob

Leave a Reply

Your email address will not be published. Required fields are marked *