Saturday, 26 February 2022

Get context in Jetpack Compose

In Android Compose, you can get the context by using the LocalContext, but it should be call'd from the composable function / scope.

val context = LocalContext.current

In the below code snippet we are retrieving the context and show a toast message inside the composable.

fun MyToastDisplay(name: String) {
    val ctx = LocalContext.current
            .fillMaxWidth(), verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(text = "Hello $name", color = Color.Red,
            modifier = Modifier
                .clickable {
                        .makeText(ctx, "Welcome to the Compose World", Toast.LENGTH_SHORT)

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

Since the LocalContext.current is composable, you can’t invoke it within the non-composable function.  i.e. clickable function is not a composable function and so can’t accept other composable functions. 

Alternatively, you can get the context outside the clickable function scope and use, as shown in the above code snippet.

Happy Coding :-)

No comments: