Is there a good way to get Context when I use Jetpack Compose?

Viewed 62

I hope to get Context in @Composable function, but Code A is wrong.

At present, I have to use Code B to get Context.

I think Code B is not good, is there other way to get Context in @Composable function ?

Code A

@Composable
fun RecordTitleWithToolBar(){   
      
        IconButton(
            onClick = {
                LocalContext.current.toast(R.string.suggest_share_app)
            }
        ) {

        }
}

Code B

@Composable
fun RecordTitleWithToolBar(){   

        val context= LocalContext.current

        IconButton(           
            onClick = {
                context.toast(R.string.suggest_share_app)             
            }
        ) {
            
        }

}
1 Answers

LocalContext uses CompositionLocal to pass context implicitly.

If we check the onClick() definition for any Material Button, we can see that the methods do not have Composable context scope. So we cannot use composable functions in non-composable scope.

In other words code B is the correct one

Related